我正在嘗試反轉類似于(A,B,(C,(D,E)),F)回傳(F,((E,D),C),B,A)Haskell 中的內容的串列。我知道如何回傳單個串列:
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = (rev xs) [x]
但是我將如何處理嵌套串列?
uj5u.com熱心網友回復:
一個可能的實作如下:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/339383.html
上一篇:Haskell字串/輸出操作
下一篇:根據用戶輸入創建多個文本框
