首页 > 解决方案 > 将数字字符串转换为整数

问题描述

我正在尝试在 Haskell 中编写这个名为 atoi 的函数,它采用一串表示整数的数字到整数本身。

例如,atoi "123"应该给出 123。

到目前为止,这是我的实现:

atoi :: String -> Int
atoi str = show str :: Int

我收到一个错误说明

无法匹配类型

标签: haskell

解决方案


使用read

atoi :: String -> Int
atoi s = read s :: Int

例子:

Prelude> atoi s = read s :: Int
Prelude> atoi "12345"
12345

推荐阅读