Ben Fossen
Ben Fossen

Reputation: 1007

updating a associated list in Haskell

I have a simple set of states like this:

st1 = [("x", 2), ("y", 3), ("z", 3)]

I want to update this as the program runs since the values will change. I have an update code like this:

update str val st = (str, val) : foldr step [] st where
    step x acc
        | fst x == str = acc
        | otherwise = x:acc

I want to make an assign function that is like this:

assign (str, val) env = update str val env

The problem I am having is that since Haskell has no side effects my updated list does not stay updated. Any ideas or suggestions on how to do this?

If I type in the interpreter if I do

let st2 = update "x" 1 st1

Then the new state is saved.

I want the function to do this:

update "x"  1 st1

Before:   [("x",1),("y",3),("z",3)]

After:    [("y",1),("x",2),("z",3)]

Upvotes: 1

Views: 129

Answers (1)

Tarrasch
Tarrasch

Reputation: 10547

You can't have side effects in Haskell as you already mentioned. Instead you might have multiple let expressions (or any other kind of definitions).

let st2 = update "x" 1 st1
let st3 = update "y" 2 st2

While there is one way around this called the State Monad, I would not recommend delving into that for now since the concept isn't trivial, instead, I would recommend to start out reading some haskell tutorial or book and you'll for sure encounter the state monad in the later chapters of the tutorial. Or even better than both options, invent the state monad on your own (it's easier than it sounds)!

Upvotes: 2

Related Questions