简体   繁体   English

如何定义 listTree 以便它返回一个按顺序包含所有元素的列表?

[英]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.

相关问题 如何定义 listTree 使其在线性时间内运行? - How to define listTree so that it runs in linear time? 定义一个函数,该函数将给定列表的所有可能排列作为对列表返回 - Define a function that returns all of the possible permutations of the given list as a list of pairs 如何定义返回 Haskell 中的列表或单个元素的 function? - How to define a function that returns a list or a single element in Haskell? 列表的所有元素*列表 - all elements of a List * List haskell中包含列表成员的第二个元素的列表 - list containing the second elements of the list members in haskell 如何在元组列表中找到所有最小元素? - How to find all minimum elements in a list of tuples? Haskell:一个函数,它接收一个列表xs和一个整数n,并返回所有长度为n的列表,其中包含来自xs的元素 - Haskell: A function that takes a list xs and an integer n and returns all list of length n with elements from xs 如何将所有其他元素的列表元素相乘? - How can I multiply the elements of a list by all the other elements? 如何进入列表并显示其元素和订单位置(HASKELL)? - How to travel into a list and show it's elements and order position (HASKELL)? Haskell - 如何以优雅的方式以相反的顺序迭代列表元素? - Haskell - how to iterate list elements in reverse order in an elegant way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM