Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ASCII value of a character in Haskell?

Tags:

haskell

ascii

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?

like image 877
Chris Avatar asked Jul 16 '10 01:07

Chris


People also ask

How do you represent a character 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 many characters in ASCII?

ASCII is a 7-bit code - one bit (binary digit) is a single switch that can be on or off, zero or one. Character sets used today in the US are generally 8-bit sets with 256 different characters, effectively doubling the ASCII set. One bit can have 2 possible states.

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.


2 Answers

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.

like image 56
sth Avatar answered Sep 22 '22 17:09

sth


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'
like image 22
RnMss Avatar answered Sep 19 '22 17:09

RnMss