2

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?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
user3560270
  • 413
  • 2
  • 7
  • `seq (undefined, undefined) True` won't evaluate the `undefined`s. Ditto for `seq (undefined : undefined) True`. This is because `seq` only evaluates enough to expose the first constructor, and does not go deep (also see `deepseq`). – chi Feb 27 '19 at 12:48
  • 2
    Lists aren't really infinite. Skipping a lot of details, `seq` sees `[1..]` and evaluates it to `1 : [2..]`, then stops. The tail stays unevaluated until someone actually needs it. – chepner Feb 27 '19 at 12:55

1 Answers1

12

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

Michael Snoyman
  • 31,100
  • 3
  • 48
  • 77