简体   繁体   English

不知道如何正确键入我的 N 叉树

[英]Can't figure out how to properly type my N-ary tree

I made the following N-ary tree data type:我制作了以下 N 叉树数据类型:

data Tree a = Leaf a | Node a [Tree a] deriving (Show)

with the following method:使用以下方法:

listLeaf::Tree a -> [a]
listLeaf (Leaf a) = [a]
listLeaf (Node a (l:list)) = concat $ listLeaf l

I'm trying to make listLeaf so that it gives me a list that contains each element of a leaf inside my tree.我正在尝试制作 listLeaf 以便它给我一个列表,其中包含我的树中叶子的每个元素。 This means that if I have the following tree: Node 3 [Leaf 1, Leaf 2, Node 1 [Leaf 3]] , my objective would be to get [1,2,3].这意味着如果我有以下树: Node 3 [Leaf 1, Leaf 2, Node 1 [Leaf 3]] ,我的目标是获得 [1,2,3]。

As you probably noticed the type of my function doesn't add up because it expects a list of a, but I'm giving it a list of lists.您可能注意到我的 function 的类型没有加起来,因为它需要一个列表,但我给它一个列表列表。 Can't wrap my head around how I can have the base case (leaf) return me a type [a] and at the same time have the Node case give me the same kind of type.无法理解如何让基本案例(叶子)返回一个类型 [a],同时让节点案例给我同样的类型。 I feel like I need to use a higher order function aside from concat, but I got no clue.我觉得除了 concat 之外,我还需要使用更高阶的 function,但我不知道。 Any hints?有什么提示吗?

You are here only calling listLeaf on l , the first element of the list, so you will only obtain the leftmost leaf.您在这里仅在列表的第一个元素l上调用listLeaf ,因此您只会获得最左边的叶子。 Furthermor concat then does not make much sense, ince you have a list of values, not a list of lists of values.此外, concat然后没有多大意义,因为您有一个值列表,而不是值列表的列表。

You can use concatMap:: (a -> [b]) -> [a] -> [b] to perform a mapping on all elements and concatenate the lists of the results, so:您可以使用concatMap:: (a -> [b]) -> [a] -> [b]对所有元素执行映射并连接结果列表,因此:

listLeaf :: Tree a -> [a]
listLeaf (Leaf a) = [a]
listLeaf (Node _ cs) = concatMap listLeaf cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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