【问题标题】:Type error of function 'floor' in HaskellHaskell中函数'floor'的类型错误
【发布时间】:2011-05-21 07:40:27
【问题描述】:

我有一个函数接受 2 个整数 n、x,并计算下限 (log n/log x)。这里 n 和 x 都非常有限,所以 Int 对我来说就足够了。

func :: Int -> Int -> Int
func n x = floor (log . fromIntegral n / (log . fromIntegral x))

但这里出现了 ghci 中的错误:

No instance for (RealFrac (a -> b))
  arising from a use of `floor' at p5_evenly_divide.hs:20:11-63
Possible fix: add an instance declaration for (RealFrac (a -> b))
In the expression:
    floor (log . fromIntegral n / (log . fromIntegral x))
In the definition of `func':
    func n x = floor (log . fromIntegral n / (log . fromIntegral x))

我该如何度过这个难关?

【问题讨论】:

    标签: haskell floating-point int


    【解决方案1】:

    表达式log . fromIntegral n 等价于log . (fromIntegral n),而不是(log . fromIntegral) n,这可能是你想要的。不过,log (fromIntegral n) 可能更具可读性。

    对于一般的教育,当错误消息显示 No instance for (RealFrac (a -> b)) 时,它告诉您它无法弄清楚如何将函数用作小数,它正在尝试这样做,因为您正在将函数组合 (.) 应用于fromIntegral n 的结果。在这种情况下有点迟钝。

    【讨论】:

    • 我喜欢你解释问题和解决问题的方式。这真的很有帮助。
    • 我认为错误消息是说应该在 RealFrac 上使用“地板”,所以我一直在处理错误的方向。
    • @Ralph Zhang:这也差不多——floor(/) 需要小数类型,fromIntegral 可以产生任何数字类型,唯一强制特定类型的是(.)。一切都会检查函数 did 是否有 RealFrac 实例,这就是它所抱怨的。
    • @camccann:+1 表示很好的解释,+1 表示信息评论,学到了一些关于 (.) 的新知识。
    • log $ fromIntegral n 也非常易读,而且非常地道,很容易。
    【解决方案2】:

    试试这个:

    func :: Int -> Int -> Int 
    func n x = floor (k n / k x) where
      k = log . fromIntegral
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 2011-03-08
      相关资源
      最近更新 更多