Why does this work - haskell mysteries?
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'
else if w == 'b'
else if w == 'a'
else (\w -> 0 ) w
'a' is stored twice here, ( maybe compiler will optimize it out but
you see the lasted 'a' mapping value )
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?
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
The program connects a variable-name to value. The fun initial gives the
initial state, update sets a variable & value reads a value).
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
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
(This is not homework - I am a programmer who is curious about Haskell!)
Any clues, anyone?
-- 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
More information about the Haskell-Cafe