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]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With