ArchHaskeller
ArchHaskeller

Reputation: 1320

Haskell Immutable data

Since Haskell's data are Immutable,how would you globally store a list that can be modified by any function?Would you muiltithread it and store it in a loop?or write the list to a file? I need to record the amount of buttons the user clicks.

Upvotes: 4

Views: 1507

Answers (2)

Ben
Ben

Reputation: 71430

Generally you don't since, as you say, Haskell's data is (mostly) immutable.

If you are going to start with a list and run it through a whole bunch of update functions, you have each function take the list as an argument and return the updated list as a result. Then you have some coordinating function (possibly main, if this is all your program is doing) that feeds the output of each update to the next updater.

It is possible to use things like the State monad to program with implicit state update, or using STRefs in the ST monad or IORefs in the IO Monad to program with implicit state update that can actually update things in-place. But Haskell programmers would usually prefer not to put a large portion of their programs in such monads to have implicit global access to writeable values.

Upvotes: 12

Retief
Retief

Reputation: 3217

You would use the state monad (or the io monad, the ST monad, or something else similar). Alternately, you could pass it in as a parameter to every function and return the new value from every function (this is what the various monads do for you).

There is no way to have global mutable state without making every function that needs the state use monads. This is an intentional choice on the part of the designers of Haskell - every non-monadic function needs to be referentially transparent (this means that the function always returns the same value for a given set of inputs) and if there was mutable state accessible from a non-monadic function, it could return the mutable state and violate referential transparency.

Technically, monadic functions are also referentially transparent - even the ones that simulate side effects do this by taking and returning an extra world parameter (which is hidden as part of the monad).

Upvotes: 2

Related Questions