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.
$!
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 (ie 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 (eg using the $!!
operator from the Control.DeepSeq
module), your program would not terminate:
λ: import Control.DeepSeq (($!!))
λ: take 10 $!! repeat 1
^C
链接地址: http://www.djcxy.com/p/42972.html
上一篇: foldl如何懒惰?
下一篇: Haskell $! 运算符和无限列表