[Haskell-beginners] Question about data structures

Daniel Fischer daniel.is.fischer at web.de
Wed Nov 24 15:26:34 EST 2010

On Wednesday 24 November 2010 20:40:02, Russ Abbott wrote:
> I would appreciate some advice about the best way to manipulate data
> structures in Haskell.
> Let's assume I have what in an OO language would be a class with a
> number of instance variables.  When I want to change one of the values
> of one of those instance variables in Haskell I must rebuild the entire
> structure.  Even worse, if one of those instance variables is a
> reference to another data structure, then when I change that referenced
> data structure, I am forced to rebuild my top level variable.  For
> example.
> data Struct1  =  Struct1  {var1  :: Struct11, var2 :: Struct1, ... }
> data Struct11 = Struct11 {var11 :: ... }
> Let's assume I have x :: Struct1 and that I change the value of var11 .
> var1 $ x.  Doesn't that require that I rebuild x?

No, x doesn't change.
What you probably mean is

y = x{ var1 = (var1 x){ var11 = somethingNew } }

Then y shares all fields except var1 with x, the var1 field of y must be 
built, but it shares everything except the var11 field with (var1 x).

Since values are immutable, the bulk of the structure is shared between an 
original value and a modified one (except if the structures are very small 
so there's little to share, but then building is cheap, or the modification 
changes very much of the structure, but then the modification would be 
expensive also in a language with mutable values).

> Is there a better way?
> Thanks.
> *
> -- Russ*

More information about the Beginners mailing list