[英]Reverse a custom nested list in Haskell
I am working on trying to reverse a nested list in Haskell. 我正在尝试反转Haskell中的嵌套列表。 I am aware that nested lists are not a thing in Haskell so I defined one: 我知道嵌套列表在Haskell中不是一回事,因此我定义了一个:
data NestedList a = Elem a | SubList [NestedList a]
I also have a flatten function: 我也有一个flatten函数:
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (SubList x) = concatMap flatten x
Now I wish to write my reverse function. 现在,我想编写我的反向函数。 The function is defined as: 该函数定义为:
myreverse :: NestedList a -> NestedList a
Which I think makes sense because I'm just rearranging the elements within the list. 我认为这是有道理的,因为我只是重新排列了列表中的元素。
I understand how to write a basic reverse function, and I also know that for Haskell's standard lists reverse is already defined. 我了解如何编写基本的反向函数,并且我也知道对于Haskell的标准列表,反向已经定义。
My question is: how do I deal with the case where the head of the list is also a list? 我的问题是:如何处理列表的头也是列表的情况? What I know needs to happen is that I reverse the head of the list and put it back onto the reverse of the tail. 我知道需要做的是,我将列表的开头反转并将其放回末尾。 But how to achieve this? 但是如何实现呢?
why not this way 为什么不这样
rev :: NestedList a -> NestedList a
rev (Elem a) = Elem a
rev (SubList xs) = SubList $ map rev $ reverse xs
if you add deriving (Show) to your data definition, 如果您在数据定义中添加派生(显示),
Prelude> rev $ SubList [Elem 1, SubList [Elem 2, Elem 3]]
SubList [SubList [Elem 3,Elem 2],Elem 1]
Prelude> rev $ SubList [Elem 1, SubList []]
SubList [SubList [],Elem 1]
Your nested list is actually a tree with elements at leavess: 您的嵌套列表实际上是一棵在叶子处有元素的树:
SubList
/ \
SubList Elem 4
/ | \
Elem 1 Elem 2 Elem 3
So your myreverse
would be a horizontal flip, ie recursive reverse
of each list in SubList
, as other answer points out. 因此,您的myreverse
将是水平翻转,即,如其他答案所指出的, SubList
中每个列表的递归reverse
。
The lesson here: Visualising data-structures helps to understand and implement actions on them. 此处的课程:可视化数据结构有助于理解和执行数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.