[英]How to define listTree so that it returns a list containing all the elements in order?
listTree :: Tree a -> [a]
listTree = foldTree f z
where
f x y z = x + y + z
z = []
This is what I have so far, but my f is wrong because the expected type is Tree a -> [a]
but the actual is Tree [a] -> [a]
这是我到目前为止所拥有的,但是我的 f 是错误的,因为预期的类型是
Tree a -> [a]
但实际是Tree [a] -> [a]
data Tree a
= Tip
| Bin (Tree a) a (Tree a)
deriving (Show, Eq)
foldTree :: (b -> a -> b -> b) -> b -> Tree a -> b
foldTree f z Tip = z
foldTree f z (Bin l x r) = f (foldTree f z l) x (foldTree f z r)
This is fold and data type for tree.这是树的折叠和数据类型。
Need help with defining f
.需要帮助定义
f
。
First of all, combining lists uses ++
in haskell.首先,组合列表在haskell 中使用
++
。 +
is only used for adding numbers. +
仅用于添加数字。 Second, the variable y
is of type a
, not [a]
, so you cannot use ++
on it directly.其次,变量
y
的类型为a
,而不是[a]
,因此您不能直接在其上使用++
。
listTree :: Tree a -> [a]
listTree = foldTree f z
where
f x y z = x ++ [y] ++ z
z = []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.