我遇到了這個定義錯誤,不知道為什么。
定義:
data Tree a = Leaf a | Node a [Tree a]
deriving (Eq,Show)
功能:
count :: Tree a -> Integer
count (Leaf a) = 0
count (Node l r) = 1 count l count r
錯誤:
Couldn't match expected type ‘Tree a2’
with actual type ‘[Tree a]’
? In the first argument of ‘count’, namely ‘r’
In the second argument of ‘( )’, namely ‘count r’
In the expression: 1 count l count r
? Relevant bindings include
r :: [Tree a]
uj5u.com熱心網友回復:
count :: Tree a -> Integer
count (Leaf a) = 0
count (Node l r) = 1 count l count r
考慮在簡單的測驗輸入上評估此函式時會發生什么。
-- | A small example tree:
--
-- > 1
-- > ├ 2
-- > └ 3
--
smallExample :: Tree Int
smallExample = Node 1 [Leaf 2, Leaf 3]
count smallExample是count (Node 1 [Leaf 2, Leaf 3])。Node 1 [Leaf 2, Leaf 3]不匹配第一個模式Leaf a,所以我們跳過第一個子句。Node 1 [Leaf 2, Leaf 3]匹配第二個模式Node l r,所以我們采用第二個子句。l是1型別Int。r是[Leaf 2, Leaf 3]型別[Tree Int]。1 count l count r是1 count 1 count [Leaf 2, Leaf 3]。
現在有兩個不一致的地方:
中
count l,Int不匹配Tree a。這可以通過count l從總和中完全洗掉來解決,因為1已經表示計算Node.中
count r,[Tree a]不匹配Tree a。這可以通過map計算所有子樹的大小sum并將它們相加來解決。count (Node l r) = 1 sum (map count r)
一些改進是可能的。l并且r不是很有幫助的名字。l看起來像一個左子樹,但它是樹中的一個元素;r看起來像一個右子樹,但它是一個子樹串列。
count (Leaf _value) = 0
count (Node _value subtrees) = 1 sum (map count subtrees)
現在這適用于更復雜的示例。
largerExample :: Tree Int
largerExample
= Node 1 -- 1
[ Node 2 -- 1
[ Leaf 4 -- 0
]
, Node 3 -- 1
[ Leaf 5 -- 0
, Leaf 6 -- 0
]
]
count largerExample是 3。
uj5u.com熱心網友回復:
錯誤訊息非常清楚:您正在嘗試將count函式應用于[Tree a]. 但它需要一個值Tree a(只是一棵樹,而不是樹的串列)。
要使其編譯,您需要以某種方式處理串列。您可以Data.List.foldl像這樣使用該功能:
count :: Tree a -> Integer
count (Leaf a) = 0
count (Node l r) = 1 count l foldl (\i t -> i count t) 0 r
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517177.html
標籤:哈斯克尔
上一篇:如何將帶有欄位的Haskell資料型別重構為標記的記錄聯合?
下一篇:從自定義屬性中獲取屬性文本
