解析树然后计算haskell中的最终值

时间:2017-03-18 15:35:26

标签: haskell tree

给出一个概率列表(以Float s的形式)和逻辑运算列表,(String s"和"和"或&# 34;)程序将通过将它们组合成一个具有节点逻辑运算和叶子概率的树来找到所描述事件的概率。

我坚持使用下面的代码。解析列表的算法是:

  • 从概率列表中取出2个值
  • 和操作列表中的一个值
  • 将它们组合起来创建一个类似Node "or" 0.5 0.6的节点,意思是"(概率为0.5的事件或概率为0.6的事件发生的概率)"

如何修改代码以正确解析树,然后计算最终概率?示例输入:asgCode [0.5,0.4,0.5,0.6,0.3] ["or","or","and","and"]应解析为树Node "and" (Node "or" (Leaf 0.5) (Leaf 0.6)) (Node "and" (Leaf 0.3) (Node "or" (Leaf 0.5) (Leaf 0.4)))

输出的含义:(0.5 OR 0.6)AND(0.3 AND(0.5 OR 0.4))

到目前为止我的代码:

data Tree = Leaf Float | Node String Tree Tree deriving (Show, Eq, Ord)
leafify [] = []
leafify (x:xs) = [Leaf x] ++ leafify xs

-- Parse the top node of a tree
prob (y:z:ys) (x:[])  = [Node x y z] 

-- Parse a non-top node of a tree
prob (y:z:ys) (x:xs) = [Node x y z] ++ prob ys xs


asgCode list list2 = prob (leafify list) list2  

0 个答案:

没有答案