类型类方法与独立函数中的范围类型变量

时间:2016-06-30 17:12:42

标签: haskell

这是一个简短的例子。我想知道为什么在TypeClass示例中我没有明确说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))

1 个答案:

答案 0 :(得分:5)

ScopedTypeVariables将实例头中的类型变量带入实例主体的范围,而没有明确的forall。类型签名不会发生这种情况;相反,您必须使用forallpk纳入showMe定义的范围。