我应该写这样的代码
具有任意数量子节点的多态树类型可以表示如下(请注意,叶子存储一个列表,内部节点存储“ListTree”列表):
data ListTree a = ListLEAF [a] | ListNODE [(ListTree a)]
deriving (Show, Read, Eq)
写一个函数foldListTree
需要一个函数(f
),基值(base
) 和一个 ListTree (t
)并组合树中叶子注释列表中的值t
通过应用函数f
。 (从左到右扫描树的叶子)。foldListTree
被调用为:
foldListTree f base t
where f
是 type 的组合函数a->a->a
。的类型foldListTree
应该:
foldListTree :: (a -> a -> a) -> a -> ListTree a -> a
我试图读取列表中的每个节点,但我猜它正在进入无限循环。
data ListTree a = ListLEAF [a] | ListNODE [(ListTree a)] deriving (Show, Read, Eq)
foldListTree :: (Num a) => (a -> a -> a) -> a -> ListTree a -> a
foldListTree op base (ListLEAF []) = base
foldListTree op base (ListNODE []) = base
foldListTree op base (ListLEAF [a]) = foldr op base [a]
foldListTree op base (ListNODE b) = (op (foldListTree op base x)
(foldListTree op base (ListNODE xs)))
where x:xs = b
t4 = ListNODE
[ ListNODE
[ ListLEAF [1,2,3]
, ListLEAF [4,5]
, ListNODE [ListLEAF [6], ListLEAF []]
]
, ListNODE []
, ListLEAF [7,8]
, ListNODE [ListLEAF [], ListLEAF []]
]
命令:foldListTree (+) 0 t4
> 错误:*** 异常:indi.hs:(86,1)-(90,54):函数中的非详尽模式foldListTree