从幻像类型创建(获取)值实例

时间:2014-07-27 21:35:37

标签: haskell gadt phantom-types

我使用GADT为货币创建基本维度(如物理维度)系统。尺寸(例如美元,美元/欧元,欧元/美元)表示为幻像类型。 我希望能够以例如一种风格打印一定数量的货币。 " 10.3USD"或" 0EUR"以及例如" 10.3USD /欧元"使用Show。 我不太确定如何解释我的问题,所以我将举例说明我是如何解决它的:

{-# LANGUAGE GADTs #-}

class (Show a) => Currency a where unphantom :: a

data USD = USD deriving Show
data EUR = EUR deriving Show

instance Currency USD where unphantom = USD
instance Currency EUR where unphantom = EUR

data Amount a where
  Amount :: Currency a => Float -> Amount a
instance Show (Amount a) where 
  show (Amount x) = show x ++ show (unphantom :: a)

data Rate a b where
  Rate :: (Currency a, Currency b) => Float -> Rate a b
-- ...

使用此代码,我收到错误

$ ghc example.hs 
[1 of 1] Compiling Main             ( example.hs, example.o )

example.hs:14:37:
    Could not deduce (Currency a1) arising from a use of `unphantom'
    from the context (Currency a)
      bound by a pattern with constructor
                 Amount :: forall a. Currency a => Float -> Amount a,
               in an equation for `show'
      at example.hs:14:9-16
    Possible fix:
      add (Currency a1) to the context of
        an expression type signature: a1
        or the data constructor `Amount'
        or the instance declaration
    In the first argument of `show', namely `(unphantom :: a)'
    In the second argument of `(++)', namely `show (unphantom :: a)'
    In the expression: show x ++ show (unphantom :: a)

我必须说当我指定a1时,我不明白为什么这种情况下的编译器会讨论a类型。

当然,我想避免在haskell类型系统之外表示维度,因为这为我添加了额外的样板代码,并且据我所知在理论上是不必要的(即编译器应该有足够的信息来推断如何显示编译时的数量或速率)(并在运行时增加一点开销)。

1 个答案:

答案 0 :(得分:5)

使用ScopedTypeVariables,您的代码按原样编译。

特别是,当你写

时没有ScopedTypeVariables
instance Show (Amount a) where 
  show (Amount x) = show x ++ show (unphantom :: a)

a中的unphantom :: a 新鲜,而不是与a中的instance Show (Amount a) where统一。启用ScopedTypeVariables会强制它统一。