我写了一个函数,(应该)采取布尔的无限列表和计算时真亦假值在第一n个元素的比例:型铸造在Haskell,分数和Int
prob n list = foldr (+) 0 (map boolToInt (take n list))/n
where boolToInt b
| b == True = 1
| otherwise = 0
不幸这不是工作:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the expression: foldr (+) 0 (map boolToInt (take n list))/n
In an equation for `prob':
prob n list
= foldr (+) 0 (map boolToInt (take n list))/n
where
boolToInt b
| b == True = 1
| otherwise = 0
Failed, modules loaded: none.
我试图做一个转换,但不工作之一:
prob n list = foldr (+) 0 (map boolToInt (take (fromIntegral (toInteger n)) list))/n
where boolToInt b
| b == True = 1
| otherwise = 0
它的编制,但只要我尝试调用的函数,我得到一个错误:
*Main> prob 50 toCoin1
<interactive>:1:6:
Ambiguous type variable `a0' in the constraints:
(Num a0) arising from the literal `50' at <interactive>:1:6-7
(Integral a0) arising from a use of `prob' at <interactive>:1:1-4
(Fractional a0) arising from a use of `prob' at <interactive>:1:1-4
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `prob', namely `50'
In the expression: prob 50 toCoin1
In an equation for `it': it = prob 50 toCoin1
有什么建议?
这不适合我,应'fromRational'是'fromIntegral'? – huon 2012-03-10 02:57:19
@dbaupp:呃,是的,它应该。猜猜我不应该在网络浏览器中编码。 – 2012-03-10 03:03:06
@dbaupp:如果您为'prob'编写顶级类型声明,例如'prob :: Int - > [Bool] - > Float',那么你会得到一个更好的错误信息。 – 2012-03-10 03:05:06