Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Int to Char

Tags:

haskell

I am using the function fromEnum to convert a character to its corresponding ASCII Int. For example:

fromEnum 'A'

returns 65.

Now, assuming I had a function that did:

(fromEnum 'A')+1

And then wanted to convert the returned value (66) to a Char which would be 'B'. What is the best way of doing so?

Thanks!

like image 958
MrD Avatar asked Dec 18 '13 13:12

MrD


People also ask

How do I convert an Int to a char Haskell?

You can use ord :: Char -> Int and chr :: Int -> Char functions from Data.

How do you write a char 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. String constants in Haskell are values of type String.

How do I find the char of a number?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.


2 Answers

You can use ord :: Char -> Int and chr :: Int -> Char functions from Data.Char.

> chr (ord 'a' + 1)
'b'

But don't forget to import Data.Char in source file or :m +Data.Char in ghci.

The same thing with fromEnum :: Enum a => a -> Int and toEnum :: Enum a => Int -> a:

toEnum (fromEnum 'a' + 1) :: Char

The last part of this expression says haskell what type we are expecting to help the type system infer right type. But in this case we can drop :: Char:

isLower $ toEnum  (fromEnum 'a' + 1)

because isLower has type Char -> Bool. So it is expecting toEnum (fromEnum 'a' + 1) to be Char.

Anyway, the solution of bheklilr is good enough :) I just wanted to show you few ways of solving your problem.

like image 170
d12frosted Avatar answered Sep 20 '22 02:09

d12frosted


You can use succ to implement the behavior you want:

nextLetter :: Char -> Char
nextLetter c
    | c == 'Z' = 'A'
    | otherwise = succ c
like image 45
bheklilr Avatar answered Sep 20 '22 02:09

bheklilr