Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the divisors of n using the filter function in Haskell

Tags:

haskell

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]
like image 276
33lives Avatar asked Mar 01 '23 09:03

33lives


1 Answers

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 it three arguments at filter divides n [1..n].

Btw,

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

is semantically equivalent to

divides x y = mod x y == 0

and operationally it doesn't repeat the mod calculation and the test mod x y /= 0.

like image 140
pedrofurla Avatar answered Mar 15 '23 06:03

pedrofurla