How can seq evaluate an inifinite list in Haskell?

206 Views Asked by At

It is said that the Haskell seq function forces the evaluation of its first argument and returns the second. It is used to add strictness to evaluation of expressions. So how can the following simply return 5:

seq [1..] 5

Shouldn't it get stuck in trying to construct an infinite list?

1

There are 1 best solutions below

2
Michael Snoyman On BEST ANSWER

seq evaluates to weak head normal form (WHNF), which essentially means it evaluates one layer of data constructors. In this case, it means that it forces evaluation of the first cons cell (the : data constructor).

I have a pretty long post explaining details around this at https://haskell.fpcomplete.com/tutorial/all-about-strictness