Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Char to Int in haskell

Tags:

haskell

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)’
like image 669
peeyush singh Avatar asked Nov 07 '18 09:11

peeyush singh


People also ask

How do you convert Int to Char in Haskell?

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.

How do I convert String to Char in Haskell?

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).

How do you write chars in Haskell?

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.


2 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']
like image 120
Willem Van Onsem Avatar answered Nov 15 '22 05:11

Willem Van Onsem


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?
like image 23
lsmor Avatar answered Nov 15 '22 05:11

lsmor