Time cost of Haskell `seq` operator

前端 未结 5 1159
逝去的感伤
逝去的感伤 2021-02-13 22:32

This FAQ says that

The seq operator is

seq :: a -> b -> b

x seq y will evaluate x, enough to chec

5条回答
  •  旧巷少年郎
    2021-02-13 23:13

    No, it's not compute and forget, it's compute - which forces caching.

    For example, consider this code:

     let x = 1 + 1
     in x + 1
    

    Since Haskell is lazy, this evaluates to ((1 + 1) + 1). A thunk, containing the sum of a thunk and one, the inner thunk being one plus one.

    Let's use javascript, a non-lazy language, to show what this looks like:

     function(){
       var x = function(){ return 1 + 1 };
       return x() + 1;
     }
    

    Chaining together thunks like this can cause stack overflows, if done repeatedly, so seq to the rescue.

    let x = 1 + 1
    in x `seq` (x + 1)
    

    I'm lying when I tell you this evaluates to (2 + 1), but that's almost true - it's just that the calculation of the 2 is forced to happen before the rest happens (but the 2 is still calculated lazily).

    Going back to javascript:

     function(){
       var x = function(){ return 1 + 1 };
       return (function(x){
         return x + 1;
       })( x() );
     }
    

提交回复
热议问题