0

我想不通,代码:

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.

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

4

1 回答 1

2

查看(!!)和的类型take

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

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

于 2013-09-30T06:20:43.497 回答