代码:
data Tree a b = Leaf a | Branch b [Tree a b] deriving (Eq,Read,Show)
- 使用这些树定义
t1 = Branch "+" [Leaf 10, Leaf 20, Branch "*" [Leaf 2, Leaf 3, Leaf 4], Leaf 50]
t2 = Branch "*" [t1,t1,t1] //should multiply t1 3 times
如何找到t1的值?如,10 + 20 +(2 * 3 * 4)+ 50 = 104
我已经启动了解决功能:
solve (Leaf a) = a
solve (Branch _ ts) = //not sure how to make it solve itself recursively here.
任何帮助将不胜感激。 谢谢。
答案 0 :(得分:3)
只需递归调用solve
即可。而且您也可以为运营商创建自己的类型,而不是使用字符串。
data Op = Plus | Mult
solve :: Tree Int Op -> Int
solve (Leaf a) = a
solve (Branch Plus args) = sum (map solve args)
solve (Branch Mult args) = product (map solve args)
答案 1 :(得分:1)
你可以试试这个:
data Tree a b = Leaf a
| Branch b [Tree a b]
deriving (Eq,Read,Show)
t1 = Branch '+' [Leaf 10, Leaf 20, Branch '*' [Leaf 2, Leaf 3, Leaf 4], Leaf 50]
t2 = Branch '*' [t1,t1,t1]
solve (Leaf a) = a
solve (Branch op ts) = op' $ map solve ts
where op' = case op of
'+' -> sum
'*' -> product
-- testing
main = do
print $ solve t1
print $ solve t2
测试
$ runghc t.hs
104
1124864
答案 2 :(得分:1)
通用解决方案如下:
solve (Leaf a) = a
solve (Branch f (t:ts)) = foldl' (\x -> f x . solve) (solve t) ts
现在您只需将Tree Int String
映射到Tree Int (Int->Int->Int)
:
mapop (Branch "*" ts) = Branch (*) $ map mapop ts
mapop (Branch "+" ts) = Branch (+) $ map mapop ts
mapop (Leaf x) = Leaf x
所以
> print $ solve $ mapop t1
104
但是真的mapop
要求派生Functor for Tree:
data Tree a b = Leaf a | Branch b [Tree a b] deriving (Eq,Show,Read,Functor)
mapop :: (Num a) => Tree a String -> Tree a (a->a->a)
mapop = fmap f where
f "+" = (+)
f "*" = (*)
请注意,我在这里没有假设Monoid
,因为您在提问时没有提及如何处理Branch
中的空列表。