piggyback
piggyback

Reputation: 9254

Return true if list has only even numbers with foldr

I would like to have a function that checks if a list contains only even numbers; if so, it should return True, otherwise - False.

Functions I would like to use are map / filter / foldr, possibly without length.

Here is my attempt:

ListOfeven :: [Integral] -> Bool
ListOfeven xs = 
  | foldr (+) True filter odd xs < 0 = True
  | otherwise = False

I am pretty sure that there is a cleaner way.. isn't there any? :)

Upvotes: 1

Views: 5503

Answers (3)

fredugolon
fredugolon

Reputation: 518

Frerich's solution works well, but can be optimized just a touch:

evenList :: [Integer] -> Bool
evenList = foldr ((&&) . even) True

This will only run through the list once. The function composition here is a bit strange, but becomes more clear upon examining its type:

(&&) . even :: Integral a => a -> Bool -> Bool

The result of even, which takes a single argument, is then bound to the first argument to the && operator, used here in prefix notation.

Upvotes: 1

Satvik
Satvik

Reputation: 11208

myfunc = foldr (\a b -> even a && b) True

Upvotes: 5

Frerich Raabe
Frerich Raabe

Reputation: 94329

The easiest would be to just use the all function from the Prelude:

evenList = all even

If you insist on just using map, filter and foldr:

evenList = foldr (&&) True . map even

Upvotes: 7

Related Questions