Haskell: Want to do better: value == x || value == y ||

I'm new to Haskell, so sorry if this is incredibly obvious ...





I made the following function (used as an example here to ask about a few checks value==something || value==somethingElse ) to check if a character is a number:


 isDigit :: Char -> Bool isDigit x = if x == '0' || x == '1' || x == '2' || x == '3' || x == '4' || x == '5' || x == '6' || x == '7' || x == '8' || x == '9' then True else False 


Of course, although there should be a neat way to write functions like the above, so you don’t need to repeat a lot || x == || x == ?



Thank you in advance for your help :)

(If relevant: I use Hugs as an interpreter.)

+7
idioms haskell
source share
2 answers

In this case, you can use elem from Prelude:

 isDigit x = elem x "0123456789" 

(Remember that strings are Char lists)

Or you can use isDigit from Data.Char

Yes, there is a neat way to write almost every repeating pattern. Here's how to do it for this. Start with a list of characters (I will just do 0-4 for short)

 "01234" 

Compare comparisons:

 map (x ==) "01234" = [x == '0', x == '1', x == '2', x == '3', x == '4'] = (x == '0') : (x == '1') : (x == '2') : (x == '3') : (x == '4') : [] 

Then use foldr . foldr fz best described as a function that takes a list and replaces : with f and [] with z .

 foldr (||) False (map (x ==) "01234") = x == '0' || x == '1' || x == '2' || x == '3' || x == '4' || False 

And you have it. foldr is a kind of grandfather of list functions, so this is the "lowest level" way for this without explicit recursion. Here are two more words for your dictionary:

 isDigit x = any (x ==) "0123456789" isDigit x = or [ x == d | d <- "0123456789" ] 

If I had to guess the most common "idiomatic" spelling, it would probably be a variant of the first:

 isDigit = (`elem` "0123456789") 

As soon as you get to know all the convenient features in Prelude, writing code like this is a joyful breeze :-)

+30
source share

Another style issue that I haven't mentioned before is that the function

 if expr then True else False 

equivalent simply

 expr 
+6
source share

All Articles