mutable records
Tom Pledger
Tom.Pledger@peace.com
Fri, 6 Sep 2002 08:26:48 +1200
Scott J. writes:
:
| Sill I want to make objects packed with their objects and
| functions. Doesn't mean that I have to use existential data types?
Sometimes you can avoid using existentials by making all your
object-updating functions return the post-update object explicitly.
For example:
module FiniteMap where
data FM k v
= FM {set :: k -> v -> FM k v,
get :: k -> Maybe v,
toList :: [(k, v)]}
module RedBlack(empty) where
import FiniteMap
empty :: Ord k => FM k v -- a finite map implemented as a red/black tree
...
In this case, the red/black tree itself is effectively a private field
of the object. The privacy is achieved by *not* making the tree a
field of the FM record. Instead, it gets passed around as the
parameter of an auxiliary function:
-- module RedBlack, continued
empty = fm emptyRedBlackMap
fm rb = FM {set = \k v -> fm (extendRedBlackMap rb k v),
get = \k -> ...,
toList = redBlackMapToList rb}
HTH,
Tom