Haskell中的Int-literal
我正在试用《函数式编程的技巧》一书中的代码示例 我想创建一个包含Haskell中的Int-literal,haskell,Haskell,我正在试用《函数式编程的技巧》一书中的代码示例 我想创建一个包含Ints的树,但我似乎最终创建了一个包含整数的树(请参见下面GHCi中的执行) 如何创建包含Ints的树?有没有办法在Haskell中编写Intliteral *Chapter18> sumTree myTree <interactive>:35:9: Couldn't match type `Integer' with `Int' Expected type: Tree Int Ac
Int
s的树,但我似乎最终创建了一个包含整数的树(请参见下面GHCi中的执行)
如何创建包含Int
s的树?有没有办法在Haskell中编写Int
literal
*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
*第18章>sumTree myTree
:35:9:
无法将类型“Integer”与“Int”匹配
所需类型:Tree Int
实际类型:树整数
在'sumTree'的第一个参数中,即'myTree'
在表达式中:sumTree myTree
在“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
——一种二叉树。
myTree=Node 2(Nil)(Nil)
数据树a=Nil |节点a(树a)(树a)
--对整数树求和
--直接解决方案:
树整型->整型
应力零=0
应力(节点n t1 t2)=n+应力t1+应力t2
--一元解决方案:首先给出Id Int类型的值。。。
sumTree::Tree Int->Id Int
sumTree Nil=返回0
--sumTree(节点n t1 t2)
--=do num
sumTree t1>>=(\s1->
sumTree t2>>=(\s2->
返回(num+s1+s2)))
-- ... 然后调整以给出Int解
sTree'::Tree Int->Int
sTree'=摘录。萨姆特里
--其中,从Id monad中提取值,因此:
摘录::Id a->a
提取(Id x)=x
又来了!因为myTree
没有任何参数,编译器避免使其多态。但是数字文本是多态的(没有Int
文本,只有整数Num
文本!),因此编译器需要决定一些Num
类型。嗯,Int
如果你处理的是大量的数字,可能会有问题,所以它选择Integer
给myTree
一个明确的签名会阻止这种情况发生;任用
myTree :: Num a => Tree a
或
myTree :: Tree Int