7

타입이 같은 typeclass 인 한 임의의 값을 포함 할 수있는 맵이 필요합니다. 나의 첫번째 순진 방법은 다음과 같이이었다 :이기종 맵

type HMap = forall a . MyClass a => M.Map Int a 

했지만 작동하지 않는 것 : 다음 코드는 컴파일 오류를 제공합니다 :

testFunction :: (forall a . MyClass a => M.Map Int a) -> Int -> IO() 
testFunction m i = do 
    case M.lookup i m of 
     Nothing -> return() 
     Just v -> someActionFromMyClass v >> putStrLn "OK" 


Ambiguous type variable `a0' in the constraint: 
    (MyClass a0) arising from a use of `m' 
Probable fix: add a type signature that fixes these type variable(s) 
In the second argument of `M.lookup', namely `m' 
In the expression: (M.lookup i m) 
In a stmt of a 'do' block: 
    case (M.lookup i m) of { 
    Nothing -> return() 
    Just v -> someActionFromMyClass v >> putStrLn "OK" } 

내가 특별한 이기종 수집이 필요하다고 생각하지만 이상하게 this을 제외하고 Google에서 아무 것도 찾을 수 없지만이 라이브러리는 지저분하고 낡은 것처럼 보입니다. 올바르게이 작업을 수행하는 방법은 무엇입니까 (GHC 확장 기능 만 사용하면 다른 라이브러리 없이도 가능).

답변

9

적절한 실존 유형을 사용해보십시오.

{-# LANGUAGE ExistentialQuantification #-} 

data Elem = forall e. C e => Elem e 

type HMap = Map Int Elem 
+0

대단히 감사합니다. 내가 가지고 있지 않은 것이 부끄러운 일이다. 나는 내가 지금하는 것보다 더 많이 자야한다고 생각한다) –

관련 문제