在Haskell中键入问题

时间:2013-07-14 17:27:30

标签: haskell types

我正在编写一个函数来查找实数的整数除数。当我运行代码时,我收到以下错误:

Clean solutions.hs:70:33:
    Could not deduce (Integral a) arising from a use of `truncate'
    from the context (RealFrac a)
      bound by the type signature for divisors :: RealFrac a => a -> [a]
      at Clean solutions.hs:70:1-74
    Possible fix:
      add (Integral a) to the context of
        the type signature for divisors :: RealFrac a => a -> [a]
    In the first argument of `(==)', namely `(truncate (n / x))'
    In the expression: (truncate (n / x)) == (n / x)
    In the first argument of `filter', namely
      `(\ x -> (truncate (n / x)) == (n / x))'

Clean solutions.hs:70:59:
    Could not deduce (Enum a)
      arising from the arithmetic sequence `2.0, 3.0 .. n / 2'
    from the context (RealFrac a)
      bound by the type signature for divisors :: RealFrac a => a -> [a]
      at Clean solutions.hs:70:1-74
    Possible fix:
      add (Enum a) to the context of
        the type signature for divisors :: RealFrac a => a -> [a]
    In the second argument of `filter', namely `[2.0, 3.0 .. n / 2]'
    In the second argument of `(:)', namely
      `filter (\ x -> (truncate (n / x)) == (n / x)) [2.0, 3.0 .. n / 2]'
    In the expression:
      1
      : filter (\ x -> (truncate (n / x)) == (n / x)) [2.0, 3.0 .. n / 2]

我发现很难理解我做错了什么,尽管花了一两个小时刷新Haskell中的类型。我的代码如下:

divisors :: RealFrac a => a -> [a]
divisors n = 1 : filter (\x -> (truncate (n/x)) == (n/x)) [2.0, 3.0.. n/2]

谢谢, 萨姆。

1 个答案:

答案 0 :(得分:1)

怎么样:

 divisors :: (RealFrac a, Enum a) => a -> [a]
 divisors n = filter (\x -> n/x == fromIntegral (truncate (n/x))) [1.0..(n/2)]