简体   繁体   中英

List comprehensions in Haskell

I want to write a simple list comprehension in Haskell which consists of a list of infinite primes.

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! What is the issue?

The issue is in your isPrime function:

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. If any values are equal to zero, then isPrime will return false.

However, you start your list comprehension at one, which every number is divisible by.

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.

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