How to get the ASCII value of a character in Haskell?
As Travis Brown indicated in a comment, you have to import the ord
function from the module Data.Char
:
import Data.Char (ord)
main = print (ord 'a')
Only the Prelude
module is loaded by default, all other modules have to be imported explicitly.
You can also use fromEnum
. (defined in Enum
class, from Prelude.)
Prelude> :i Char
data Char = GHC.Types.C# GHC.Prim.Char# -- Defined in `GHC.Types'
instance Enum Char -- Defined in `GHC.Enum'
instance Eq Char -- Defined in `GHC.Classes'
...
So you can use fromEnum
and toEnum
, which uses the ASCII code as the Int value.
Prelude> fromEnum 'A'
65
Prelude> fromEnum 'a'
97
Prelude> toEnum 9 :: Char
'\t'
Prelude> toEnum 100 :: Char
'd'