Search code examples
haskellghci

List comprehension not ending in a square bracket, console freezing


Entering a list comprehension into GHCi does not generate a list, the final square brackets are missing, and the console freezes. This is what I have come up with:

[13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000]

I believe the problem lies either with x <- [1..], or 13*x + 3 <= 1000. By 13*x + 3 <= 1000 I meant to determine the upper limit of the values x in x <- [1..] can take.

I'm given back a result [341, but it does the second square bracket is missing, and the console freezes.


Solution

  • Your program enters an infinite loop.

    The first number is 341, but in order to produce the next number, your program keeps looking through all the subsequent values of x, evaluates all the guards for those values, and checks if all the guards are true. The very last guard, 13*x + 3 <= 1000 never becomes true again, so the program just keeps enumerating values of x forever. It's looking for the next such x for which all guards are true, and as soon as it finds one, it's going to print it. But such x never comes.

    If you want the list to end once x*13 + 3 > 1000, you have to use takeWhile:

    ... | x <- takeWhile (\y -> y*13 + 3 <= 1000) [1..],  ...
    

    That way the list will actually stop when it reaches 1000. No more values of x would be produced.