在Haskell中将Char转换为Int

pee*_*ngh 1 haskell

我正在尝试将(数字)字符串转换为单个数字。有多种解决方法,一种是map digitToInt "1234"

我正在尝试类似的方法,但是没有digitToInt尝试使用,而是尝试使用该read::Char->Int函数。但是,当我使用上述方法时,出现编译错误,如下所示:

map (read::Char->Int) ['1','2']
Run Code Online (Sandbox Code Playgroud)

给我下面给出的以下错误。我不确定这里出了什么问题,我正在尝试映射一个将Char替换为Char列表的函数,我还缺少什么?

请不要告诉我其他方法,因为我了解还有其他几种方法可以做到这一点。只想了解这里发生了什么。

Couldn't match type ‘Char’ with ‘[Char]’
      Expected type: Char -> Int
        Actual type: String -> Int
    • In the first argument of ‘map’, namely ‘(read :: Char -> Int)’
Run Code Online (Sandbox Code Playgroud)

lsm*_*mor 5

问题是read :: Read a => String -> a。所以read应适用于String不适用Char。尝试以下方法:

 map (read :: String -> Int) ["1", "2"]
 -- or
 map read ["1", "2"] :: [Int] -- same but clearer?
Run Code Online (Sandbox Code Playgroud)

  • 啊完全忘了 read 只能以字符串作为输入!谢谢。 (2认同)

Wil*_*sem 5

read :: Read a => String -> a字符串转换为Read能干的元素。因此,如果您想从字符串中读取数字,则可以使用:

map (read . pure :: Char -> Int) ['1','2']
Run Code Online (Sandbox Code Playgroud)

但是如果字符是数字,则最好使用以下digitToInt :: Char -> Int功能:

import Data.Char(digitToInt)

map digitToInt ['1', '2']
Run Code Online (Sandbox Code Playgroud)