我编写了一个函数,它(应该)接受一个无限的 bool 值列表并计算前 n 个元素的 True 和 False 值的比率:
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
围绕整个foldr
和 n
.
prob n list = fromIntegral count / fromIntegral n
where count = foldr (+) 0 (map boolToInt (take n list))
boolToInt b
| b == True = 1
| otherwise = 0
哦,还有你的
boolToInt
功能与 fromEnum
相同专攻Bool
s。prob n list = fromIntegral count / fromIntegral n
where count = foldr (+) 0 (map fromEnum (take n list))
您尝试做的事情的根本问题是您对
prob
的第一个参数强加了相互冲突的要求。 .您对 toInteger
的使用受限 n
成为 Integral
,但它在 /
中的使用要求它是 Fractional
,并且没有任何类型是 Integral
和 Fractional
.
关于haskell - 在 haskell、Fractional 和 Int 中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643506/