Why does this work - haskell mysteries?

Michael Wang Michael.Wang at synopsys.com
Fri Oct 3 18:26:37 EDT 2003


I am guessing this is how the data got accumulated:
in you my_store, the function stored is like

\w -> if w == 'a'
        then 3
        else if w == 'b'
               then 5
               else if w == 'a'
                      then 4
                      else (\w -> 0 ) w


'a' is stored twice here, ( maybe compiler will optimize it out but
basically
you see the lasted 'a' mapping value  )



-----Original Message-----
From: haskell-cafe-bounces at haskell.org
[mailto:haskell-cafe-bounces at haskell.org]On Behalf Of Petter Egesund
Sent: Saturday, October 04, 2003 4:48 PM
To: haskell-cafe at haskell.org
Subject: Why does this work - haskell mysteries?


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)



_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list