Use 'any' to tell you true/false, if a list contains some value(s) divisible by 42

  • A+

Having fun working through a Haskell tutorial...

One problem posed is as you see in the subject line... this is one I'd really like to figure out, but I'm at a loss... I've used any like so:

ghci >any (==55) [15,25,35,45,55,65,75,85,95] True ghci >any (==55) [15,25,35,45,54,65,75,85,95] False ghci >all even [2,4,6,8] True ghci >all even [1,3,5,7,9] False 

and it seems like checking if a list element is divisible by 42 or not, should be fairly easy...

I mean, you would check if any of the numbers in the list are n `mod` 42 == 0, right?

But how do you state that in the expression? Or do you need to write a 'helper' function?


Composing (0==) and (`mod 42`):

f :: [Integer] -> Bool f = any ((0==).(`mod` 42)) 

futher reducing parenthesis noise:

f :: [Integer] -> Bool f = any $ (0==).(`mod` 42) 

Helper function:

f :: [Integer] -> Bool f = any div42   where     div42 n = n `mod` 42 == 0 

Stylistically, for this function, either way seems fine. However, say you wanted to check if any values are divisible by 42 OR 52, then utilizing composition may become more obfuscated/complex/futile. Whereas using a helper function keeps things readable: div42Or52 n = n `mod` 42 == 0 || n `mod` 52 == 0. Note, I've used a where clause above, but a let in expression or a lambda are possible alternative ways to structure helper functions.

Ultimately, its up to the developer to balance concise code with understandable code.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: