Måns Nilsson
Måns Nilsson

Reputation: 451

Haskell list comprehension doesn't work

Here is a list comprehension I've made in Haskell:

[x|x <- [1..], n <- [1..], n <= 10, n >= 1, x == ((7 * n) + 4)]

I expect it to print out the first 10 natural numbers that are 4 mod 7, but when I execute it, it doesn't print out anything and never terminates. Why?

Upvotes: 0

Views: 127

Answers (1)

chepner
chepner

Reputation: 530843

The compiler does not infer that n <- [1..], n<=10, n >=1 is equivalent to n <- [1..10]. The code will merrily pull values of n from [1..] forever, verifying for each one whether it should be used or not per the guards n <= 10 and n >= 1. n <- [1..10] without further tests on n would be sufficient, but if you want to be explicit, try something like

[x|x <- [1..], n <- takeWhile (<= 10) [1..], x == ((7 * n) + 4)]

Pulling x from a separate list and comparing them to a function of n is also inefficient. You can just construct your list from n alone:

[ 7*n + 4 | n <- [1..10] ]

Upvotes: 5

Related Questions