[Haskell-cafe] Expressing seq
haskell at list.mightyreason.com
Wed Sep 27 18:08:56 EDT 2006
Chad Scherrer wrote:
> I was reading on p. 29 of "A History of Haskell" (a great read, by the
> way) about the controversy of adding seq to the language. But other
> than for efficiency reasons, is there really any new primitive that
> needs to be added to support this?
> As long as the compiler doesn't optimize it away, why not just do
> something like this (in ghci)?
> Prelude> let sq x y = if x == x then y else y
> Prelude> 1 `sq` 2
> Prelude> (length [1..]) `sq` 2
> There must be a subtlety I'm missing, right?
The (sq x) function depends on x being an instance of typeclass Eq.
Imagine a new typeclass Seq that is auto-defined for all types:
class Seq a where
seq :: a -> (b -> b)
data Foo x = Bar x | Baz | Foo y x
The instances always use a "case" to force just enough evaluation to compute the
constructor, then return id:
instance Seq Foo where
seq a = case a of
Bar _ -> id
Baz -> id
Foo _ _ -> id
foo1,foo2 :: Foo Int
foo1 = undefined
foo2 = Bar 1
Now "(seq foo1) b" will also be undefined which "(seq foo2) b" will be "id b"
which is "b".
More information about the Haskell-Cafe