haskell - 将 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
解决方案
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 Int
readMaybe
推荐阅读
- python - AttributeError: 'str' 对象在运行 Tkinter 时没有属性 'tk'
- laravel - 我应该在哪里定义将在刀片模板中使用的逻辑?
- laravel - 如何解决图像干预渲染速度问题?
- react-native - 未捕获的 ReferenceError:使用 React-Native web 时未定义导出
- postgresql - 模式匹配 Postgres 以替换列的拼写错误的单词
- linux-kernel - v4l2 在使用 async kapi 时控制子设备上的继承
- r - 函数返回错误:矩阵错误(NA_character_,nrow = nrow(indt),ncol = Ncol):无效的“ncol”值(太大或 NA)
- node.js - PM2 Process Manager 没有显示每个项目 package.json 版本的实际版本,而是 NVM 版本号
- sass - Sass 函数到 Less 的转换
- php - 使用数组创建输入名称(php)