在实例上显示不同的路径

时间:2015-02-08 16:34:52

标签: haskell binary-tree

我有以下树:

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 ++ "? "

但我不确定如何让它显示出每一条可能的道路。我该怎么做?感谢。

1 个答案:

答案 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的路径是:

的并集
  1. 与否定答案有关的问题,前面有问题和&#34;否&#34;和
  2. 与肯定答案相关的问题,前面有问题和&#34;是&#34;。
  3. 您可能希望使用map而不是列表推导 - 这只是个人品味的问题。