Why does this work - haskell mysteries?!

,,,
Sun Oct 5 00:36:25 EDT 2003


Hi;

the proof of the pudding does lies in the eating... but I still wonder why 
this code is working (it is taken from the book "The Craft of functional 
programming").

The program connects a variable-name to value. The fun initial gives the 
initial state, update sets a variable & value reads a value).

I evaluate 

		value my_store 'b' to 5
   and  	value my_store 'a' to 3

as expected from the text in the book.

But I can't see what is happening here. The book has a parallel example where 
the data is held in a list, and this version is easy to follow, but this 
trick with storing a lambda-function inside a newtype beats me.

The problem is that I do not understand where the accumulated data is stored 
(not in a list - it seems like something like a chain of functions which can 
be pattern-matched, but I am not sure).

And why does not the lambda-function (\w -> if v==w then n else sto w) start a 
endless loop?

(This is not homework - I am a programmer who is curious about Haskell!)

Any clues, anyone?


Cheers,

Petter	      


-- Var is the type of variables.					

type Var = Char

newtype Store = Sto (Var -> Int) 					
--  
initial :: Store 

initial = Sto (\v -> 0)

value :: Store -> Var -> Int

value (Sto sto) v = sto v

update  :: Store -> Var -> Int -> Store

update (Sto sto) v n 
  = Sto (\w -> if v==w then n else sto w)

-- testit --

my_store = update (update (update initial 'a' 4) 'b' 5) 'a' 3)

		      




More information about the Haskell-Cafe mailing list