简体   繁体   中英

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]

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 .

First of all, combining lists uses ++ in haskell. + is only used for adding numbers. Second, the variable y is of type a , not [a] , so you cannot use ++ on it directly.

listTree :: Tree a -> [a]
listTree = foldTree f z
    where
    f x y z = x ++ [y] ++ z
    z = []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM