读取和表示指定要使用的数据类型的输入

sas*_*nin 5 polymorphism haskell

我想读一些本身指定要使用的数据类型的数据.

例如,假设可能存在以下用户输入:

integer pair 1 2
integer triple 1 2 3
real pair 1 2
real triple 1 2 3
Run Code Online (Sandbox Code Playgroud)

并且有一种数据类型来表示它:

data (MValue a) => T a = TP (Pair a) | TT (Triple a)
  deriving (Show, Eq)

data Pair a = Pair a a deriving (Show, Eq)
data Triple a = Triple a a a deriving (Show, Eq)
Run Code Online (Sandbox Code Playgroud)

允许的值类型必须属于MValue类:

class (Num a, Read a) => MValue a where
  typename :: a -> String
  readval  :: [String] -> Maybe a

instance MValue Int where
  typename _ = "integer"
  readval [s] = maybeRead s
  readval _   = Nothing

instance MValue Double where
  typename _ = "real"
  readval [s] = maybeRead s
  readval _   = Nothing

maybeRead s =
  case reads s of
    [(x,_)] -> Just x
    _       -> Nothing
Run Code Online (Sandbox Code Playgroud)

我可以轻松地为Pairs和Triples 写读者:

readPair (w1:w2:[]) = Pair <$> maybeRead w1 <*> maybeRead w2
readTriple (w1:w2:w3:[]) = Triple <$> maybeRead w1 <*> maybeRead w2 <*> maybeRead w3
Run Code Online (Sandbox Code Playgroud)

问题是如何为整个T a类型编写多态读取器?:

readT :: (MValue a, Read a) => String -> Maybe (T a)
Run Code Online (Sandbox Code Playgroud)

我想要:

  1. 类型a由调用者选择.
  2. readTNothing如果用户的输入与之不兼容,应该产生a.
  3. readTJust (T a)如果输入有效,应该产生.
  4. 数字应根据输入读取为整数或双精度数.

一个天真的实现

readT :: (MValue a, Read a) => String -> Maybe (T a)
readT s =
  case words s of
    (tp:frm:rest) ->
        if tp /= typename (undefined :: a)
           then Nothing
           else case frm of
             "pair" -> TP <$> readPair rest
             "triple" -> TT <$> readTriple rest
             _ -> Nothing
    _ -> Nothing
Run Code Online (Sandbox Code Playgroud)

在行中给出错误if tp /= typename (undefined :: a):

rd.hs:45:17:
    Ambiguous type variable `a' in the constraint:
      `MValue a' arising from a use of `typename' at rd.hs:45:17-41
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

如果我删除此检查,则错误消失,但如何验证用户输入是否与调用者选择的数据类型兼容?一个解决办法是有单独的readTIntreadTDouble,但我想同readT为多态的工作方式相同read呢.

mok*_*kus 5

该问题是aundefined :: a是不一样的a作为的人readT的签名.GHC中有一种语言扩展可以实现,称为"ScopedTypeVariables".一个更便携的修复方法是引入一些额外的代码来明确地将类型绑定在一起,例如:

readT :: (MValue a, Read a) => String -> Maybe (T a)
readT s = result
  where
    result = 
      case words s of
        (tp:frm:rest) ->
            if tp /= typename ((const :: a -> Maybe (T a) -> a) undefined result)
               then Nothing
               else case frm of
                 "pair" -> TP <$> readPair rest
                 "triple" -> TT <$> readTriple rest
                 _ -> Nothing
        _ -> Nothing
Run Code Online (Sandbox Code Playgroud)

这是对代码的一个非常快速和肮脏的修改,我可以更优雅地进行更改,但这应该有效.