我正在尝试书中的代码示例" The Craft of Functional Programming"。
我想创建一个包含Int
s的树,但我似乎最终在其中创建了一个带有整数的树(请参阅下面的GHCi中的执行)。
如何创建一个包含Int
s的树?有没有办法在Haskell中编写Int
文字?
*Chapter18> sumTree myTree
<interactive>:35:9:
Couldn't match type `Integer' with `Int'
Expected type: Tree Int
Actual type: Tree Integer
In the first argument of `sumTree', namely `myTree'
In the expression: sumTree myTree
In an equation for `it': it = sumTree myTree
以下是相应的代码:
-- A type of binary trees.
myTree = Node 2 (Nil) (Nil)
data Tree a = Nil | Node a (Tree a) (Tree a)
-- Summing a tree of integers
-- A direct solution:
sTree :: Tree Int -> Int
sTree Nil = 0
sTree (Node n t1 t2) = n + sTree t1 + sTree t2
-- A monadic solution: first giving a value of type Id Int ...
sumTree :: Tree Int -> Id Int
sumTree Nil = return 0
--sumTree (Node n t1 t2)
-- = do num <- return n
-- s1 <- sumTree t1
-- s2 <- sumTree t2
-- return (num + s1 + s2)
sumTree (Node n t1 t2) =
return n >>=(\num ->
sumTree t1 >>= (\s1 ->
sumTree t2 >>= (\s2 ->
return (num + s1 + s2))))
-- ... then adapted to give an Int solution
sTree' :: Tree Int -> Int
sTree' = extract . sumTree
-- where the value is extracted from the Id monad thus:
extract :: Id a -> a
extract (Id x) = x
答案 0 :(得分:7)
Monomorphism restriction再次罢工!因为myTree
没有任何参数,所以编译器避免使其变为多态。但是数字文字是多态的(没有Int
文字,只有整数Num
文字!),所以编译器需要决定一些Num
类型。好吧,如果你处理大量数字,Int
可能是一个问题,所以选择Integer
。
给予myTree
明确的签名会阻止这种情况;要么使用
myTree :: Num a => Tree a
或者
myTree :: Tree Int