>一所以我有一個樹定義爲無價值樹一 - 在Haskell
data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show
我知道我可以定義葉是葉一。但我真的只想讓我的節點具有價值。我的問題是,當我做了搜索我型
Tree a -> a
的返回值函數由於葉子有沒有價值我很困惑怎麼說,如果你遇到一個葉無能爲力。我試過nil
," "
,' '
,[]
似乎沒有任何工作。
編輯代碼
data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show
breadthFirst :: Tree a -> [a]
breadthFirst x = _breadthFirst [x]
_breadthFirst :: [Tree a] -> [a]
_breadthFirst [] = []
_breadthFirst xs = map treeValue xs ++
_breadthFirst (concat (map immediateChildren xs))
immediateChildren :: Tree a -> [Tree a]
immediateChildren (Leaf) = []
immediateChildren (Node n left right) = [left, right]
treeValue :: Tree a -> a
treeValue (Leaf) = //this is where i need nil
treeValue (Node n left right) = n
test = breadthFirst (Node 1 (Node 2 (Node 4 Leaf Leaf) Leaf) (Node 3 Leaf (Node 5 Leaf Leaf)))
main =
do putStrLn $ show $ test
你想搜索一個具有特定值的節點嗎?然後'也許一個'可能是一個很好的返回類型。 – gspr 2013-05-10 17:55:53
沒有它首先遍歷寬度,然後打印它按順序查找的值。問題在於它遇到了葉子,就像我做了什麼,我只是說沒有繼續。 – Slowbro 2013-05-10 17:59:32
更新代碼 – Slowbro 2013-05-10 18:05:24