Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell $! operator and infinite lists

I read that the $! operator forces strict evaluation. So why does this still work?

Prelude> take 10 $! repeat 1
[1,1,1,1,1,1,1,1,1,1]

I was expecting ghc to grind away forever trying to evaluate the infinite list of 1's.

like image 672
knick Avatar asked May 12 '14 14:05

knick


1 Answers

$! forces its second argument to weak head normal form, which basically means it evaluates its argument's outermost constructor. So in your case, it will not force the evaluation of the whole list, but only evaluate the outermost (i.e. first) : constructor.

There is a good explanation of normal form vs WHNF at Haskell: What is Weak Head Normal Form? .

Note that if you forced evaluation of the whole list (e.g. using the $!! operator from the Control.DeepSeq module), your program would not terminate:

λ: import Control.DeepSeq (($!!))
λ: take 10 $!! repeat 1
^C
like image 137
fjh Avatar answered Oct 18 '22 18:10

fjh