2016-08-27 3 views
0

은 (http://lpaste.net/180651에서) 다음과 같은 코드를 생각해GHC가 왜이 유형을 추론 할 수 없습니까?

test.hs:11:33: error: 
    • Could not deduce (Natural n0) arising from a use of ‘dim’ 
     from the context: Natural n 
     bound by the type signature for: 
        bad_fromList :: Natural n => [a] -> V n a 
     at test.hs:10:1-41 
     The type variable ‘n0’ is ambiguous 
    • In the second argument of ‘(==)’, namely ‘dim v’ 
     In the expression: length l == dim v 
     In the expression: if length l == dim v then v else undefined 

왜 GHCI이 유형을 추론 할 수 없습니다

{-# LANGUAGE ScopedTypeVariables #-} 

class Natural n 

newtype V n a = V [a] 

dim :: Natural n => V n a -> Int 
dim = undefined -- defined in my actual code 

bad_fromList :: Natural n => [a] -> V n a 
bad_fromList l = if length l == dim v then v else undefined -- this is line 11 
    where v = V l 

good_fromList :: forall n a. Natural n => [a] -> V n a 
good_fromList l = if length l == dim v then v else undefined 
    where v = V l :: V n a 

GHCI 다음과 같은 오류 메시지를 제공합니다?

또는 다음 코드에서는 pure '와 good_f가 컴파일되지만 bad_f는 비슷한 오류 메시지를 표시합니다. 왜?

pure' :: Natural n => a -> V n a 
pure' x = v 
    where v = V $ replicate (dim v) x 

bad_f :: Natural n => [a] -> (V n a, Int) 
bad_f xs = (v, dim v) 
    where v = V xs 

good_f :: Natural n => a -> (V n a, Int) 
good_f x = (v, dim v) 
    where v = V $ replicate (dim v) x 
+4

문제는 'v'는 ** 모든 ** 가능한 유형 'n'에 대해 'V n a'유형을가집니다. 하스켈이 공개 세계 가정에 의존하고 있다는 점을 감안할 때,'자연 n '의 어떤 인스턴스가 거기에서 사용되어야 하는지를 알 수있는 방법이 없기 때문에'n0 '이 모호하다는 오류가있다. GHC는 임의 유형을 선택하기를 원하지 않는다. '희미 해 '라고 부를 수있다. 코드를 애매하게 만들지 않아야합니다. – Bakuriu

+0

여기에있는 유형은 실제로 모호하지 않습니다. 이러한 오류는 컴파일러가 필요한 것보다 더 일반적인 형식 시그니처를 추론하려고하기 때문에 발생합니다. '-XMonoLocalBinds'를 활성화하면 코드가 작동합니다 (https://ideone.com/GsEHSO). – user2407038

+0

@ user2407038 감사합니다. MonoLocalBinds를 사용할 때의 단점이 있습니까? – Kevin

답변

0

user2407038 제안대로 -XMonoLocalBinds를 사용하면 코드가 작동합니다.