如何反转 Haskell 中的嵌套列表
How can I reverse a nested list in Haskell
我正在尝试将类似于 (A,B,(C,(D,E)),F)
的列表反转为 return 类似于 haskell 中的 (F,((E,D),C),B,A)
。
我知道如何 return 一个列表:
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = (rev xs) ++ [x]
但是对于嵌套列表我该如何处理呢?
一种可能的实现方式如下:
data Tree a = Leaf a | Node [Tree a] deriving (Eq, Show)
rev (Leaf x) = Leaf x
rev (Node xs) = Node (go (reverse xs)) where
go ((Leaf y):ys) = Leaf y: go ys
go ((Node y):ys) = rev (Node y): go ys
go [] = []
一个简短的测试:
λ> tree = Node [Leaf 'A', Leaf 'B', Node [Leaf 'C', Node [Leaf 'D', Leaf 'E']]]
λ> rev tree
Node [Node [Node [Leaf 'E',Leaf 'D'],Leaf 'C'],Leaf 'B',Leaf 'A']
正如 Daniel Wagner 所指出的,这可以更简单、更优雅地实现:
rev2 (Leaf x) = Leaf x
rev2 (Node xs) = Node (reverse (map rev2 xs))
我正在尝试将类似于 (A,B,(C,(D,E)),F)
的列表反转为 return 类似于 haskell 中的 (F,((E,D),C),B,A)
。
我知道如何 return 一个列表:
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = (rev xs) ++ [x]
但是对于嵌套列表我该如何处理呢?
一种可能的实现方式如下:
data Tree a = Leaf a | Node [Tree a] deriving (Eq, Show)
rev (Leaf x) = Leaf x
rev (Node xs) = Node (go (reverse xs)) where
go ((Leaf y):ys) = Leaf y: go ys
go ((Node y):ys) = rev (Node y): go ys
go [] = []
一个简短的测试:
λ> tree = Node [Leaf 'A', Leaf 'B', Node [Leaf 'C', Node [Leaf 'D', Leaf 'E']]]
λ> rev tree
Node [Node [Node [Leaf 'E',Leaf 'D'],Leaf 'C'],Leaf 'B',Leaf 'A']
正如 Daniel Wagner 所指出的,这可以更简单、更优雅地实现:
rev2 (Leaf x) = Leaf x
rev2 (Node xs) = Node (reverse (map rev2 xs))