[英]Haskell - Creating a list by using functions
我想按照標題中的說明進行操作,但是這會使我顯示錯誤。 我把我的代碼放在下面。
data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show
treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a):(treeToList b)
它會顯示如下內容:
treeToList分支(分支(葉子2)(葉子3))(葉子4)
[2,3,4]
在第一個模式匹配中,您將獲得類型列表的值。 現在,您所要做的就是在與Branch
構造函數進行模式匹配時將它們串聯起來。
treeToList :: Tree a -> [a]
treeToList (Leaf x) = [x]
treeToList (Branch a b) = (treeToList a) ++ (treeToList b)
ghci中的演示:
*Main> treeToList (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4))
[2,3,4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.