Use or in list comprehension

I am trying to take out every number from 1 to 10, which is divisible by 5 or 3
Here is my code so far -

giveList = [ x | x <- [1..10] , (x `mod` 5 == 0) or (x `mod` 3 == 0) ] 

And then load the function into ghci. But that gives me an error -

 > [1 of 1] Compiling Main ( problem1.hs, interpreted ) problem1.hs:4:10: The function `x `mod` 5 == 0' is applied to two arguments, but its type `Bool' has none In the expression: (x `mod` 5 == 0) or (x `mod` 3 == 0) In a stmt of a list comprehension: (x `mod` 5 == 0) or (x `mod` 3 == 0) In the expression: [x | x <- [1 .. 10], (x `mod` 5 == 0) or (x `mod` 3 == 0)] Failed, modules loaded: none. 

My question is

  • Can we use "or" in the list comprehension?
  • If not, please tell me how this can be done in other ways.

I am new to functional programming, please help me.

+4
source share
4 answers

You can use or in lists, but

 Prelude> :t or or :: [Bool] -> Bool 

which is not the one you need in this place, this is a function that checks if there is any item in the True list. There you need

 (||) :: Bool -> Bool -> Bool 

And if you want to use a function with a name consisting of the letters infix, you need to wrap it in reverse cycles, as you did with mod , but since or takes only one argument, you cannot use this function infix.

The correct version of your list will be

 giveList = [ x | x <- [1 .. 10], x `mod` 5 == 0 || x `mod` 3 == 0] 
+13
source

or has a signature like or :: [Bool] -> Bool . It takes a list of booleans and returns True if either of them is True or False otherwise.

The function you are looking for is || :: Bool -> Bool -> Bool || :: Bool -> Bool -> Bool . It takes two Boolean values ​​and returns True if either of them is True or False otherwise.

 [x | x <- [1..10], x `mod` 5 == 0 || x `mod` 3 == 0] 
+8
source

You can do the following:

 [x | x <- [1..10], ((x `mod` 3) == 0) || ((x `mod` 5) == 0)] 
Function

or works on lists

+2
source

Actually, it may not be so bad for me to use or here:

 [x | x <- [1..10], or $ map ((==0).(x `mod`)) [3,5]] 

... or perhaps more readable ...

 [x | x <- [1..10], any (==0) $ map (x `mod`) [3,5]] 

The downside is that it may look a little scary, but on the back, you can easily test more divisors this way.

0
source

All Articles