33

How to get the ASCII value of a character in Haskell? I've tried to use the ord function in GHCi, based on what I read here bug the the error message:

Not in scope: `ord'

For example:

GHCi, version 6.12.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude> ord 'a'

<interactive>:1:0: Not in scope: `ord'
Prelude>

What am I doing wrong?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Chris
  • 39,719
  • 45
  • 189
  • 235

2 Answers2

40

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.

sth
  • 222,467
  • 53
  • 283
  • 367
  • Is this just a ghci thing? Or do i have to import these kind of modules when i'm making .hs files too? – Chris Jul 16 '10 at 01:27
  • 4
    @Chris: Only stuff defined in `Prelude` is imported by default, for other modules you have to specify additional imports. – sth Jul 16 '10 at 01:29
19

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'
RnMss
  • 3,696
  • 3
  • 28
  • 37