【问题标题】:Haskell read function report error couldn't match expected typeHaskell 读取函数报告错误无法匹配预期类型
【发布时间】:2016-05-01 23:33:24
【问题描述】:

我是一个初学者,我正在尝试编写一个函数来检查一个字符串是否可以解释为数字。这是我的代码:

string' xs = if (all isDigit xs == False)
             then "can not be interpreted"
             else read xs::Int 

但它一直报告错误“无法将预期类型'[Char]'与实际类型'Int'匹配” 不知道为什么,有人遇到过这个问题吗?

【问题讨论】:

  • string' 的类型是什么 - 是 string' :: String -> String 还是 string' :: String -> Int?在 haskell 中,您不能有一个函数根据输入的运行时属性返回两种不同类型中的一种。
  • 您可能还喜欢reads :: String -> [(Int, String)],它将检查输入是否适合您,如果不是,则返回[](以及成功解析的列表以及如果成功则未解析的任何内容)。
  • 样式注释:考虑使用not (...) 而不是(...) == False。这是一个口味问题,但第一个看起来更“自然”。或者,完全删除它并交换 then/else 分支。 (丹尼尔上面关于reads的建议会更好。)

标签: haskell


【解决方案1】:

if-then-else 的两个分支需要具有相同的类型。您的“then”分支的类型为 [Char],而您的“else”分支的类型为 Int。看起来你的“then”分支应该会导致某种错误。在这种情况下可以使用error,它具有多态类型,可以代替使用。

更好的解决方案(建议在评论部分)是使用Either 类型,它可以返回两个选项之一(Left 或Right)。

string' xs = if (all isDigit xs == False)
             then Left "can not be interpreted"
             else Right (read xs::Int)

另一个常见的做法是使用Maybe 类型

string' xs = if (all isDigit xs == False)
             then Nothing
             else Just (read xs::Int)

【讨论】:

  • 当然,或者OP可以使用Either String Int作为返回类型并返回Left "can not ..."或Right (read xs :: Int)。
猜你喜欢
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多