Home > other >  Return the divisors of n using the filter function in Haskell
Return the divisors of n using the filter function in Haskell

Time:11-19

Create a divisors :: Int -> [Int] function that returns the divisors of x.

I've successfully made a divides function that returns True if y is a divisor of x.

divides x y | mod x y == 0 = True
            | mod x y /= 0 = False

I've tried to use it to filter numbers from [1..n] , but can't exactly get a grasp on how the filter function works. Can anyone set me in the right direction?

divisors n = filter divides n [1..n]

CodePudding user response:

You are in the right track. Only that your problem is not exactly how filter works, but how Haskell works.

divisors n = filter (divides n) [1..n]

The above will do the trick. See, filter takes two arguments, so does divisors. But you are giving were giving it three arguments at filter divides n [1..n].

CodePudding user response:

filter takes as its second argument a list to filter - here your [1..n] - and as first argument a function which takes one of those list elements as input and returns a boolean.

So think about what this function would be, in terms of your pre-defined function divides. Since, as you have it, divides x y actually means "y is a divisor of x", you can easily express this with a lambda function:

divisors n = filter (\m -> divides n m) [1..n]

which can be further simplified by "eta-reduction" (or coloquially, "cancelling the m) to

divisors n = filter (divides n) [1..n]
  • Related