haskell - 在 haskell、Fractional 和 Int 中进行类型转换

标签 haskell

我编写了一个函数,它(应该)接受一个无限的 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围绕整个foldrn .

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 ,并且没有任何类型是 IntegralFractional .

关于haskell - 在 haskell、Fractional 和 Int 中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643506/

相关文章:

haskell - 预组合单子(monad)更改器(mutator)

haskell - 从完成的第一个线程获取结果

haskell - 共递归是如何处理的?

haskell - 如何为强制长度为 2^n 的向量类型定义可用的 Applicative 实例

json - Haskell::Aeson::根据字段值解析ADT

haskell - 自动将 Either 提升到 exceptT

haskell - 是否可以在 Yesod 路由中指定查询参数?

Haskell Double 除以 Int

list - 无法理解 Haskell 中的原始递归定义

haskell - 了解 Monad Transformer 类型签名