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!
You can use ord :: Char -> Int and chr :: Int -> Char functions from Data.
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.
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.
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.
You can use succ
to implement the behavior you want:
nextLetter :: Char -> Char
nextLetter c
| c == 'Z' = 'A'
| otherwise = succ c
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