Jiaqi Shao
Jiaqi Shao

Reputation: 55

How to compare a character to a number in Haskell?

I'm trying to do it by pattern matching with the following

[x| x <- "example string", x > 106]

I know you can compare things such as x > a, and I'm guessing an explicit conversion is needed. One method to do this I found online but doesn't work is

[x| x <- "example string", ord x > 106]

And apparently doesn't recognise ord as a valid keyword.

Upvotes: 2

Views: 296

Answers (2)

amalloy
amalloy

Reputation: 91907

If the number you are comparing to is a constant, you can always go the other direction: convert that number to a character constant, and then compare that to your characters directly:

filter (> 'j') "example string"

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

ord :: Char -> Int is not a keyword, it is a function from the Data.Char module:

import Data.Char(ord)

myExpr = [x | x <- "example string", ord x > 106]

Here it might be more convenient to work with filter:

import Data.Char(ord)

myExpr = filter ((106 <) . ord) "example string"

both return:

Prelude Data.Char> [x | x <- "example string", ord x > 106]
"xmplstrn"
Prelude Data.Char> filter ((106 <) . ord) "example string"
"xmplstrn"

Upvotes: 3

Related Questions