首页 > 解决方案 > 将 Maybe String 转换为 (Maybe?) Integer

问题描述

我想将 Maybe String 类型转换为 Integer。

我的实际代码是:

  let rule = getParamRule args -- this is a Maybe String type
  let rule_int = read rule::Int -- I would like to convert to (Maybe) Integer
  print rule
  print rule_int
test.hs:26:23: error:
    • Couldn't match type ‘Maybe String’ with ‘[Char]’
      Expected type: String
        Actual type: Maybe String
    • In the first argument of ‘read’, namely ‘rule’
      In the expression: read rule :: Maybe Int
      In an equation for ‘rule_int’: rule_int = read rule :: Maybe Int

标签: haskell

解决方案


利用Text.Read.readMaybe

readMaybe :: Read a => String -> Maybe a

使用 Read 实例解析字符串。如果只有一个有效结果,则成功。

> readMaybe "123" :: Maybe Int
Just 123

> readMaybe "hello" :: Maybe Int
Nothing

在使用之前,您需要使用导入模块

import Text.Read

在文件的开头(module ...如果有的话,在该行之后)。

请注意,您可以按 type搜索hoogle 。在这种情况下,搜索显示为第 11 个结果。可能会更好,但它仍然显示在第一页。String -> Maybe IntreadMaybe


推荐阅读