[Haskell-cafe] I just don't get it (data structures and OO)

Donald Bruce Stewart dons at cse.unsw.edu.au
Sun Jun 3 03:34:18 EDT 2007


Phlex:
> Hello all,
> 
> I'm coming from the OO world, and there's something i don't quite 
> understand in the way haskellers manipulate data (as all functional 
> programmers i guess).
> 
> Let's say i have a deep nested data structure.
> Universe containing galaxies, containing solar systems, containing 
> planets, containing countries, containing inhabitants, containing 
> ...whatever.
> 
> Using the OO paradigm, once i get a reference to an inhabitant, i can 
> update it quite easily (say by changing it's age), and that's the end of it.
> 
> On the other side, using the functional paradigm, it seems to me that 
> the function i use in order to create a _new_ inhabitant with a 
> different age will need to have knowledge of the country over it, the 
> planet ..and so on up to the universe...as i need to update all these 
> structures to reflect the change. This is pretty bad and most probably 
> doesn't need to be like this.
> 
> So here I am hoping for you all to give me some pointers on how this is 
> done "the functional way".
> 

Nope, its not done like that. You share as much of the original
structure as you can, as a general principle.

Imagine updating a node in a tree by just detaching and reattaching a
pointer.

    [1]                         [1]
    / \                         / \
  [2] [3]     update node 5   [2] [3] 
       / \     with value 7       / \
     [4] [5]                     [4] *

and share the rest of the structure. Since the rest isn't mutable
anyway, you can share all over.

-- Don


More information about the Haskell-Cafe mailing list