Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seq vs. rnf in Haskell

Tags:

haskell

According to the definitions given by "Parallel and Concurrent Programming in Haskell" on page 29, the class method "return normal form" is defined as:

rnf a = a `seq` ()

Just to see if wrapping seq in another function, as the authors prescribe, really had the result of forcing 'a' to be evaluated to normal form, I tried implementing the function myself and got a result in the negative:

Prelude Control.DeepSeq > myrnf a = a `seq` ()
Prelude Control.DeepSeq > xs = map (+1) [1..10] :: [Int]
Prelude Control.DeepSeq > :sprint xs
xs = _
Prelude Control.DeepSeq > myrunf xs
()
Prelude Control.DeepSeq > :sprint xs
xs = _ : _
Prelude Control.DeepSeq > rnf xs
()
Prelude Control.DeepSeq > :sprint xs
xs = [2,3,4,5,6,7,8,9,10,11]

So have the authors made a glaring mistake, or am I missing something here?

Edit: I realised my original question contained elementary mistakes. Here is the proper form of the question.

like image 900
Raskell Avatar asked Feb 20 '26 17:02

Raskell


1 Answers

Perhaps, by declaring the implementation in class, one is saying that that is the default implementation, unless stated otherwise in a specific instance declaration?

Yes, that's exactly what it means. What's unusual (IMO) is that normally this default implementation is valid (i.e. does what you want) for all instances but may be overridden for efficiency or to break a cycle of default definitions (e.g. in Eq the default implementations are x == y = not (x /= y) and x /= y = not (x == y), so you can override whichever is more convenient).

But in case of rnf, the documentation for 1.3.0.0 says

The default implementation of rnf ... may be convenient when defining instances for data types with no unevaluated fields (e.g. enumerations).

i.e. it doesn't really work for nearly all types.

This problem has been fixed since 1.4.0.0.

like image 112
Alexey Romanov Avatar answered Feb 22 '26 06:02

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!