[Haskell] Force evaluation
Ben Rudiak-Gould
Benjamin.Rudiak-Gould at cl.cam.ac.uk
Mon Dec 6 11:23:19 EST 2004
Tomasz Zielonka wrote:
> I guess you could also do something like deepSeq with Data.Generics.
Ralf Hinze posted just such an implementation to one of the mailing
lists a couple of years back:
http://www.mail-archive.com/glasgow-haskell-users@haskell.org/msg03810.html
The end of the message seems to be cut off in the archive, so here's a
reconstructed version.
> module Force
> where
> import Generics
>
> class Force a where
> force :: a -> ()
>
> force{|Unit|} a = a `seq` ()
>
> force{|b :+: c|} a = case a of
> Inl b -> force b
> Inr c -> force c
>
> force{|b :*: c|} a = case a of
> b :*: c -> force b `seq` force c
>
> instance Force Char where
> force a = a `seq` ()
> instance Force Int where
> force a = a `seq` ()
>
> eval :: (Force a) => a -> a
> eval a = force a `seq` a
And here's a slight variation in which force has the type a -> a,
eliminating the need for the helper function eval. I'm not sure which
version is better.
> module Force'
> where
> import Generics
>
> class Force a where
> force :: a -> a
>
> force{|Unit|} a = a
>
> force{|b :+: c|} a = case a of
> Inl b -> force b `seq` a
> Inr c -> force c `seq` a
>
> force{|b :*: c|} a = case a of
> b :*: c -> force b `seq` force c
`seq` a
>
> instance Force Char where
> force a = a
> instance Force Int where
> force a = a
I haven't tested either of these.
-- Ben
More information about the Haskell
mailing list