I am trying to convert a string (of numbers) into individual digits. There are multiple ways to solve this, one being to map digitToInt "1234"
I was trying a similar approach but instead of using digitToInt
, I was trying to use the read::Char->Int
function. However I am getting compilation error when I use the above, as in:
map (read::Char->Int) ['1','2']
gives me the following error given below. I am not sure what is wrong here, I am trying to map a function which takes Char over a list of Char, what am I missing?
Please do not tell me of alternate approach as I understand there are several other ways to do this. Just want to understand what is happening here.
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)’
You can use ord :: Char -> Int and chr :: Int -> Char functions from Data. Char . But don't forget to import Data. Char in source file or :m +Data.
A String is already a list of Char (it is even defined like this: type String = [Char] ), so you don't have to do anything else. If you need a list of String s, where every String consists of just one char, then use map to wrap every char (once again, every String is a list, so you are allowed to use map on these).
A character literal in Haskell has type Char. To convert a Char to or from the corresponding Int value defined by Unicode, use toEnum and fromEnum from the Enum class respectively (or equivalently ord and chr). A String is a list of characters.
read :: Read a => String -> a
converts a string to a Read
able element. So if you want to read the digits from a string, you can use:
map (read . pure :: Char -> Int) ['1','2']
but if the characters are digits, it might be better to use the digitToInt :: Char -> Int
function:
import Data.Char(digitToInt)
map digitToInt ['1', '2']
The problem is read :: Read a => String -> a
. So read
should be applied to String
not to Char
. Try this instead:
map (read :: String -> Int) ["1", "2"]
-- or
map read ["1", "2"] :: [Int] -- same but clearer?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With