简体   繁体   English

Haskell-根据函数返回的条件创建列表

[英]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. 我现在有一个函数,尝试使用该函数的结果作为条件,如果为true,则会将值放入列表中;否则,它将忽略该值。 Since I started using Haskell 2 days ago, I am struggling greatly with doing this (I'm more used to Python). 自从两天前开始使用Haskell以来,我为此做了大量工作(我更习惯于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 我尝试了许多不同的Google搜索,以查看是否可以使用列表理解来创建此列表,

[] == [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? 因为我确实想学习Haskell,所以有人可以帮助我(最好仅使用前奏中可用的命令)使此条件检查生效吗?

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. 它已经保留了这些通过测试的数字in `mod` i == 0 ,并且丢弃所有其他数字。

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. [] ==在这里是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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