Search code examples
haskellpointfree

How to filter all multiples of a certain number out of a list in Haskell using filter


I know I can make a function to do this but can I use the filter function from the prelude. I can easily filter all numbers larger than 3 for instance from a list using

filter (>3) [list]

But I want something like

filter (not (.. `mod` 4 == 0)) [list]

that filters out all multiples of four. I put the .. here because I dont know what goes there. Is there any way I can do this using the filter function or should I make my own function to do this? Thanks in advance


Solution

  • You were almost there:

    filter (\n -> not (n `mod` 4 == 0)) [list]
    

    The \n is read "lambda n", and introduces an anonymous function. Namely, the function which, given n tests if it is not a multiple of 4.

    Otherwise, you can use the "pointfree" style, in which you compose several functions:

    filter (not . (== 0) . (`mod` 4)) [list]
    

    The function reads as: take the input, reduce it modulo 4, then test if the result is equal to 0, and finally negate the result of such test.

    Note that you can also use /= 0 instead of == 0 and negation.