Search code examples
haskellquickcheck

Create an elements generator with an infinite list


I'm playing with QuickCheck, and stumbled upon some strange behavior

sample $ elements [1..5]

works as expected, however

sample $ elements [1..]

hangs in ghci, even when using a finite type such as Int

sample $ elements [(1::Int)..]

Why doesn't it print arbitrary (pun intended :) large Ints?

Update

I've tested @amalloy's explanantion by using

sample $ elements ([1 .. ] :: [Int8])

which does terminate.


Solution

  • elements chooses elements uniformly at random, which means on average it will be reaching length / 2 items into the list. For infinite values this is impossible, and for large finite lists like [1..] :: [Int], this is still reaching like 1 billion items in, one at a time through the linked list. Quite a slow operation!