简体   繁体   English

Haskell - 将结果定义为列表并返回null

[英]Haskell - Defining result as a list and returning null

listX n = xs
if sum[x | x <- [2, 4..n-1], y <- [1..n-1], y `rem` x == 0] == y
    then insert y xs
    else return ()

Alright, first time trying to work with Haskell, and only having novice Java knowledge has led to some problems. 好吧,第一次尝试使用Haskell,并且只有新手Java知识导致了一些问题。 What I was trying to do, was to define the result of the function listX n as a list called xs. 我试图做的是将函数listX n的结果定义为名为xs的列表。 My idea was that the program would grab every number of from 1 to n, and check if it was equal to the sum of its positive divisors. 我的想法是程序会抓取从1到n的每个数字,并检查它是否等于其正除数的总和。 Clearly, I have failed horribly and need help, pointers to concepts I haven't understood is extremely appreciated. 显然,我已经失败了,需要帮助,指向我尚未理解的概念非常感激。

Your main problem seems to be that you still think imperative (with the insert ) - also () is the value unit - you probably wanted to write [] (the empty list) instead - but still the xs here is totally undefined so you would have to fix this too (and I don't see how to be honest). 你的主要问题似乎是你仍然认为命令式(使用insert ) - 也是()是值单位 - 你可能想写[] (空列表)而不是 - 但是这里的xs完全未定义所以你会必须解决这个问题(我不明白如何诚实)。

perfect numbers 完美的数字

I think I can see a basic idea in there, and I think the best way to fix this is to go full list-comprehension (as you seem to understand them quite well) - here is a version that should work: 我认为我可以在那里看到一个基本的想法,我认为解决这个问题的最好方法是全面列表理解(因为你似乎很了解它们) - 这是一个应该工作的版本:

listX n = [ x | x <- [1..n], sum [ y | y <- [1..x-1], x `mod` y == 0] == x]

As you can see I changed this a bit - first I check all x from 1 to n if they could be perfect - and I do this by checking by summing up all proper divisors and checking if the sum is equal to x (that's the job of the sum [...] == x part) - in case you don't know this works because you can add guards to list comprehensions (the sum [..] == x filters out all values of x where this is true). 你可以看到我改变了一点 - 首先我检查所有x1n如果它们可能是完美的 - 我通过总结所有适当的除数并检查总和是否等于x (这是工作)来做到这一点在的sum [...] == x部分) -如果你不知道这个作品,因为你可以添加卫士列出内涵(的sum [..] == x筛选出的所有值x在那里,这是真正)。

a nicer version 一个更好的版本

to make this a bit more readable (and separate the concerns) I would suggest writing it that way: 为了使这个更具可读性(并将问题分开),我建议以这样的方式编写它:

properDivisors :: Integer -> [Integer]
properDivisors n = [ d | d <- [1..n-1], n `mod` d == 0]

isPerfect :: Integer -> Bool
isPerfect n = sum (properDivisors n) == n

perfectNumbers :: [Integer]
perfectNumbers = filter isPerfect [1..]

perfectNumbersUpTo :: Integer -> [Integer]
perfectNumbersUpTo n = takeWhile (<= n) perfectNumbers

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

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