Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Converting Char to Int in haskell

Writer Andrew Mclaughlin

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)’
2

4 Answers

read :: Read a => String -> a converts a string to a Readable 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?
1

You can try doing it this way map (\x -> read (x:[]) :: Int) "12"This should work, if you have any doubts about it just search lambda expressions.

You could try something like that:

toInt x = read x :: Int
map (toInt . (:"")) ['1', '2']

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy