【问题标题】:How to convert a String to an Enumerated Data Type in Haskell?如何在 Haskell 中将字符串转换为枚举数据类型?
【发布时间】:2019-11-07 16:24:16
【问题描述】:

我有一个看起来像这样的枚举数据类型:

data MathExpr a = X
               | Coef a
               | Sum (MathExpr a) (MathExpr a)
               | Prod (MathExpr a) (MathExpr a)
               | Quot (MathExpr a) (MathExpr a)
               | Exp (MathExpr a)
               | Log (MathExpr a)
                 deriving (Eq,Show,Read)

我正在尝试将 String 转换为这种类型。我想使用前奏曲中可用的读取功能。为此,我创建了另一个函数:

readMathExpr :: String -> MathExpr a
readMathExpr = read

这在编译时给我一个错误,说没有因使用“读取”而产生的 (Read a) 实例。如果有人能指出我正确的方向或链接有关读取功能的有用教程,我将非常感激。谢谢 !

【问题讨论】:

  • 提示:要编译函数show' :: a -> String; show' = show需要做什么? (提示提示:show 的签名是什么?(提示提示:GHCi 有一个:t 命令来查找某物的类型,或者Hoogle will show it 给你。)
  • 您可以从为您的MathExpr a 类型编写一个Read 类型类实例开始。
  • @Redu 不需要,GHC 可以推导出(并且已经在 OP 中)。
  • 可能值得指出的是,您不需要定义新函数。 read "Sum (Coef 1) (Coef 2)" :: MathExpr Int 表达式直接起作用,当 GHC 可以推断类型时(在现实程序中通常会出现这种情况),您可以删除类型注释 :: MathExpr Int

标签: haskell


【解决方案1】:

问题只是您提出的类型签名过于笼统。 MathExpr aRead 的派生实例仅在已经存在 aRead 实例时才有效。也就是说,如果您要自己写出实例,它将开始:

instance (Read a) => Read (MathExpr a) where ...

我不认为在实践中您会希望读取类型为a 的类型为MathExpr a 的值,这些类型本身不是Read 的实例,因此解决方法只是添加必要的类型类对签名的约束:

readMathExpr :: (Read a) => String -> MathExpr a
readMathExpr = read

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2018-02-14
    • 2021-07-21
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多