I've been looking into perfect numbers, and I found this interesting bit of code on rosettacode:
perfect n = n == sum [i | i <- [1..n-1], n `mod` i == 0]
Now, I understand what a perfect number is, and I know which numbers are considered perfect, however I'm struggling to work out which parts of this code do what.
I understand that it's working out the factors of the inputted number, and combining them together to see if it matches the input itself, but I'm not sure how it's doing this.
If anyone could possibly break down this bit of code in a beginner-friendly manner I'd be very appreciative.
For
i
from1
ton-1
(that is,[1, 2, 3, 4 ... n-1]
)And only for those values where
i
evenly dividesn
. Discarding values that do not match this requirement.Include
i
in the result list.Add the elements of this list together.
And return
True
iff the total equalsn
.Starting from the middle, you can read it like this: for each element
i
of the[1..n-1]
list, check ifn `mod` i
equals0
. If it does, includei
in the result list (that's the part to the left of the|
. Without using the list comprehension syntax, that might be written using thefilter
function:The elements of the resulting list are then added with
sum
, and, finally, the sum is tested for equality withn
.