Haskell类型类错误

时间:2013-09-30 06:13:44

标签: haskell

我无法弄明白,代码:

smallSum :: (Ord a, Integral a) => a -> a
smallSum n 
    | n < 0 = 0
    | (n < 20) = n + smallSum (n - 1)
    | otherwise = error "Number needs to be in 1..10"

fastSumOfSeriesLength :: (Ord a, Integral a) => a -> a
fastSumOfSeriesLength x 
    | x < 10 = smallSum x
    | x >= 10 = sum (take (rest - 1) [dif !! (firstDigit - 1), dif !! (firstDigit - 1) + 100..]) + smallList !! (firstDigit - 1)
    where
        smallList = [smallSum x | x <- [1..10]]
        largeList = [smallSum x | x <- [11..20]]
        dif = [l - s | l <- largeList, s <- smallList]
        firstDigit = x `mod` 10
        rest = x `div` 10

错误:

ghci> :r
[1 of 1] Compiling Main             ( learn.hs, interpreted )

learn.hs:194:32:
    Could not deduce (a ~ Int)
    from the context (Ord a, Integral a)
      bound by the type signature for
                 fastSumOfSeriesLength :: (Ord a, Integral a) => a -> a
      at learn.hs:191:26-54
      `a' is a rigid type variable bound by
          the type signature for
            fastSumOfSeriesLength :: (Ord a, Integral a) => a -> a
          at learn.hs:191:26
    In the first argument of `(-)', namely `rest'
    In the first argument of `take', namely `(rest - 1)'
    In the first argument of `sum', namely
      `(take
          (rest - 1)
          [dif !! (firstDigit - 1), dif !! (firstDigit - 1) + 100 .. ])'
Failed, modules loaded: none.

我正在寻找有人指出什么是错的,它看起来很轻松,我需要谷歌来了解更多关于这个错误的信息。

1 个答案:

答案 0 :(得分:2)

查看(!!)take的类型:

*Main> :t (!!)
(!!) :: [a] -> Int -> a
*Main> :t take
take :: Int -> [a] -> [a]

由于您在与x类型相同的表达式上使用这些,这意味着x必须是Int - 但您声明此函数应该适用于任何类型(积分数。 (如果您慢慢阅读错误,希望您能够看到它说出来。)最简单的解决方法是导入Data.List并使用genericIndexgenericTake代替。