Testing if an inputted Int is a perfect number

孤人 提交于 2019-12-02 08:41:47
n == sum [i | i <- [1..n-1], n `mod` i == 0]
              ^^^^^^^^^

For i from 1 to n-1 (that is, [1, 2, 3, 4 ... n-1])

n == sum [i | i <- [1..n-1], n `mod` i == 0]
                              ^^^^^^

And only for those values where i evenly divides n. Discarding values that do not match this requirement.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
         ^^^

Include i in the result list.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
     ^^^^

Add the elements of this list together.

n == sum [i | i <- [1..n-1], n `mod` i == 0]
^^^^

And return True iff the total equals n.

[i | i <- [1..n-1], n `mod` i == 0]

Starting from the middle, you can read it like this: for each element i of the [1..n-1] list, check if n `mod` i equals 0. If it does, include i in the result list (that's the part to the left of the |. Without using the list comprehension syntax, that might be written using the filter function:

filter (\i -> n `mod` i == 0)

The elements of the resulting list are then added with sum, and, finally, the sum is tested for equality with n.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!