简体   繁体   English

列表理解Haskell

[英]List comprehensions in Haskell

I want to write a simple list comprehension in Haskell which consists of a list of infinite primes. 我想在Haskell中编写一个简单的列表理解方法,其中包含无限质数的列表。

My attempt: 我的尝试:

isPrime 1 = False
isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]

primes = [x | x <-[1..], isPrime x ]

But when I try running this on console as take 10 primes it gets stuck! 但是,当我尝试take 10 primes在控制台上运行它时,它会卡住! What is the issue? 有什么问题

The issue is in your isPrime function: 问题出在您的isPrime函数中:

isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]

You take each element from 1 to x-1, and check if the remainder is not equal to zero. 您将每个元素从1取到x-1,然后检查余数是否不等于零。 If any values are equal to zero, then isPrime will return false. 如果任何值等于零,则isPrime将返回false。

However, you start your list comprehension at one, which every number is divisible by. 但是,您的列表理解从1开始,每个数字都可以被其整除。

So, we just need to start at two instead. 因此,我们只需要从两个开始。

isPrime x = and [x `mod` z /= 0 | z <- [2..x-1]]

Now it works as expected. 现在它可以按预期工作了。

λ> take 10 primes
[2,3,5,7,11,13,17,19,23,29]

If you get a problem in a larger function, try breaking it down and running each individual part to ensure the results are as you expect. 如果在较大的功能中遇到问题,请尝试将其分解并运行每个零件,以确保结果符合预期。 In this case, isPrime 2 == False hints to where the problem is. 在这种情况下, isPrime 2 == False提示问题出在哪里。

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

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