2016-06-30 42 views
0

下面是一個簡短的例子。我不知道爲什麼在類型類的例子,我沒有明確地說forall而在功能定義,而forall它失敗編譯:類型類方法中的作用域類型變量與獨立函數

Couldn't match kind ‘Nat’ with ‘*’ 
    When matching types 
     proxy0 :: Nat -> * 
     Proxy :: * -> * 
    Expected type: proxy0 n0 
     Actual type: Proxy p0 
    In the first argument of ‘natVal’, namely ‘(Proxy :: Proxy p)’ 
    In the second argument of ‘($)’, namely ‘natVal (Proxy :: Proxy p)’ 
    In the first argument of ‘(++)’, namely 
     ‘(show $ natVal (Proxy :: Proxy p))’ 

代碼:

{-# LANGUAGE DataKinds   #-} 
{-# LANGUAGE KindSignatures  #-} 
{-# LANGUAGE RankNTypes   #-} 
{-# LANGUAGE RoleAnnotations  #-} 
{-# LANGUAGE ScopedTypeVariables #-} 
{-# LANGUAGE TypeOperators  #-} 
{-# LANGUAGE TypeFamilies  #-} 

data Container (p :: Nat) (k :: Nat) = Container { first :: [Int], second :: [Int] } 

instance (KnownNat p, KnownNat k) => Show (Container p k) where 
    show c = "Container " ++ (show $ natVal (Proxy :: Proxy p)) ++ 
        " " ++ (show $ natVal (Proxy :: Proxy k)) 

showMe :: forall p k . (KnownNat p, KnownNat k) => Container p k -> String 
showMe c = "Container " ++ (show $ natVal (Proxy :: Proxy p)) ++ 
        " " ++ (show $ natVal (Proxy :: Proxy k)) 

回答

5

ScopedTypeVariables帶來輸入實例變量頭在沒有明確的forall的實例主體中的範圍內。對於類型簽名不會發生這種情況;相反,您必須使用forallpk納入showMe的定義範圍內。