我无法弄明白,代码:
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.
我正在寻找有人指出什么是错的,它看起来很轻松,我需要谷歌来了解更多关于这个错误的信息。
答案 0 :(得分:2)
查看(!!)
和take
的类型:
*Main> :t (!!)
(!!) :: [a] -> Int -> a
*Main> :t take
take :: Int -> [a] -> [a]
由于您在与x
类型相同的表达式上使用这些,这意味着x
必须是Int
- 但您声明此函数应该适用于任何类型(积分数。 (如果您慢慢阅读错误,希望您能够看到它说出来。)最简单的解决方法是导入Data.List
并使用genericIndex
和genericTake
代替。