2013-09-30 10 views
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. 

임 사람을 찾고가 지적하는 무슨 잘못이 빛 작업을 보일 것이다 무엇 이 오류에 대해 자세히 알아 보려면 Google에 필요한 정보 (!!)take의 유형 밖으로

+0

빠른 팁 : 함수의 형식 선언을 제거한 다음 GHCi에서로드 할 수 있습니다. ': t expr' 명령으로 함수의 타입을 물어볼 수 있습니다. –

답변

2

확인 : 당신이 x와 같은 형태로 표현에서 이러한를 사용하기 때문에

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

,이 xInt해야 의미 -하지만 당신은이 기능이 작동한다는 것을 선언 어떤 종류의 (필수) 숫자에. (오류를 천천히 읽으면,이 말을 잘 볼 수있을 것입니다.) 가장 간단한 해결 방법은 Data.List을 가져오고 대신 genericIndexgenericTake을 사용하는 것입니다.

+0

나는 차라리 가장 쉬운 수정은 타입 선언을 삭제하거나 을 Int -> Int로 만드는 것이라고 말하고 싶지만, 다형성이 필요한지에 달려있다. – MdxBhmt

+1

@MdxBhmt 아마 전체 파일을 삭제하는 것이 가장 쉽습니다. 그러나 "단순"에 대한 나의 기준은 "쉬운"것에 대한 나의 기준보다 덜 효과적입니다. =) –