我有以下树:
data Questionario = Answer String
| Question String Questionario Questionario
左侧的子树是否定答案,右侧的子树是肯定答案。
我想将Questionario定义为一个实例,显示所有可能的路径。例如:
q = Question "a >= b"
(Question "a >= c"
(Question "b >= c"
(Answer "a b c")
(Answer "a c b"))
(Answer "c a b"))
(Question "a >= c"
(Answer "b a c")
(Question "b >= c"
(Answer "b c a")
(Answer "c b a")))
必须显示为:
*Main> q
a >= b? No a >= c? No b >= c? No ANSWER: a b c
a >= b? No a >= c? No b >= c? Yes ANSWER: a c b
a >= b? No a >= c? Yes ANSWER: c a b
a >= b? Yes a >= c? No ANSWER: b a c
a >= b? Yes a >= c? Yes b >= c? No ANSWER: b c a
a >= b? Yes a >= c? Yes b >= c? Yes ANSWER: c b a
我已经写过:
instance Show Questionario where
show (Answer x) = "ANSWER " ++ x
show (Question q r l) = q ++ "? "
但我不确定如何让它显示出每一条可能的道路。我该怎么做?感谢。
答案 0 :(得分:1)
您希望函数生成所有路径。可能的方法是:
paths :: Questionario -> [String]
paths (Answer x) = ["ANSWER " ++ x]
paths (Question q l r) = [q ++ "? No " ++ s | s <- paths l] ++
[q ++ "? Yes " ++ s | s <- paths r]
Answer
只有一条路径。相反,Question
的路径是:
您可能希望使用map
而不是列表推导 - 这只是个人品味的问题。