PotentialNewo
PotentialNewo

Reputation: 35

Putting two Integers into a list from a single list comprehension

I need to find all primes ± 2 in list comprehension however after looking i cant find out how to do it, so far i have:

primeTwins :: Integer -> [Integer]
primeTwins x = [x+2 | x <- [2..x], prime x]

However this obviously only produces primes+2 when i need primes-2. (prime x finds if the number is a prime). If it isnt possible, i need 2 compregensions but i also dont know how to go about that either. From my research i havent found anything relavant so any help would be helpful. Thats for any help given

Upvotes: 0

Views: 57

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477308

You can use another generator that takes x-2 and x+2, and then yields both:

primeTwins :: Integer -> [Integer]
primeTwins x = [ y | x <- [2..x], prime x, y <- [x-2, x+2] ]

It is however possible that the same element occurs twice in the list. For example, 3 and 7 are both prime, so that means that 1 and 5 are generated because 3 is prime; and 5 and 9 are generated because 7 is prime, so then 5 is generated twice.

Upvotes: 3

Related Questions