简体   繁体   中英

Haskell - Creating a List based on conditions returned by functions

I have a function that figures out if a certain value is a Perfect Number (Adding up all it's factors, except itself, produces itself) and returns a Boolean based on it's result:

isPerfect :: Int -> Bool
isPerfect n = n == sum [i | i <- [1..n-1], n mod i == 0]

I now have a function which tries to use this function's result as a condition, which if true, results in a value being placed into a list, and if not, it ignores that value. Since I started using Haskell 2 days ago, I am struggling greatly with doing this (I'm more used to Python). This is my first attempt at something plausible:

isPerfectUpToN :: Int -> [Int]
isPerfectUpToN n = [] insert y
where
y = [1..n] AND isPerfect y == True

I've tried many different google searches to see if this list could be created using list comprehension, something along the lines of

[] == [y | y <- [1..n], isPerfect y]

But this implementation didn't work. Since I do want to learn Haskell, can somebody help me (preferably using only the commands available in prelude) with getting this conditional check to work?

Look closer at your definition

isPerfect n = n == sum [i | i <- [1..n-1], n `mod` i == 0]   -- NB the `mod`

it is already keeping such numbers i that pass the test, n `mod` i == 0 , and drops all the others.

So you just make use of the same principle:

perfectsTo :: Int -> [Int]
perfectsTo n = [i | i <- [1..n], isPerfect i]

Yes it does work. The [] == is superfluous there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM