如何在这个例子中得到更好的Haskell中的多态类型推断?

我有以下数据类型:

data PValue = IV Int | BV Bool | SV String
            deriving (Show, Eq)

我想写一个从Int,Bool或String生成PValue的函数,如下所示:

> loadVal 3
IV 3

> loadVal True
BV Bool

> loadVal "Ha"
SV "Ha"

由于loadVal的参数是多态的,我尝试创建一个类:

class PValues v where
  loadVal :: v -> PValue

instance PValues Int where
  loadVal v = IV v

instance PValues Bool where
  loadVal v = BV v

instance PValues String where
  loadVal s = SV s

这似乎工作,除了诠释:

> loadVal "Abc"
SV "Abc"
> loadVal False
BV False
> loadVal 3

<interactive>:8:1:
    No instance for (PValues v0) arising from a use of `loadVal'
    The type variable `v0' is ambiguous
    Note: there are several potential instances:
      instance PValues String -- Defined at Types.hs:22:10
      instance PValues Bool -- Defined at Types.hs:19:10
      instance PValues Int -- Defined at Types.hs:16:10
    In the expression: loadVal 3
    In an equation for `it': it = loadVal 3

<interactive>:8:9:
    No instance for (Num v0) arising from the literal `3'
    The type variable `v0' is ambiguous
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus 8 others
    In the first argument of `loadVal', namely `3'
    In the expression: loadVal 3
    In an equation for `it': it = loadVal 3

我明白这是因为3本身是模糊的类型(可以是IntFloat等)。 有没有一种方法来强制这种类型推断,而不必在呼叫站点中明确注释它?


在此扩展@ AndrewC的评论。 为了使loadVal 3能够正常工作,请在实例化时进行类型转换:

instance PValues Integer where
  loadVal v = IV (fromInteger v)

现在,如果您希望使用Text类型并且不希望用户明确注释它,请同时为StringText实例:

data PValue = IV Int | BV Bool | SV Text
            deriving (Show, Eq)

instance PValues String where
  loadVal s = SV (pack s)

instance PValues Text where
  loadVal s = SV s

对于编译器能够推断出你的输入是Text数据类型的场所,它不必经历pack开销。

链接地址: http://www.djcxy.com/p/7457.html

上一篇: How to get better Polymorphic Type Inference in Haskell for this example?

下一篇: Circular Typing with Constraints