How to compare a character to a number in Haskell?

Viewed 107

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.

2 Answers

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"

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"
Related