1

I'm reading "Learn You a Haskell for Great Good!", pretty fine book, I know how to handle states using recursion inside a function or in many cases a simple folding can substitute code where in an empirical language would require mutation, that is ok

I've read about state monad, it is nice but I feel that it is only a trick. This phrase describes concisely what is the state monad

The State monad is really an abstraction over the idea of passing state around in an extra parameter to your functions - it's still pure, it just gives you a lot of syntactic help

how to simulate haskell state?

now I'm thinking in a hypotetical code:

I've 3 functions, the first one "user" returns a tuple with the user name and his age ("tom",20). The second one returns also a tuple with the company name and its year of foundation ("google",1998) and the third could be a non profit organization ("mozilla", 2003), pretty simple.

But what happen if I need that on every call? These tuples will be appended to one list?

Checking this response it seems that I can (could?) use mutable states

Managing state - chapter 3 of SICP

Is it possible an immutable and pure alternative? I'm pretty sure that using functional reactive programming it's possible but I wish to know the "classic pure functional solution".

Community
  • 1
  • 1
user1050817
  • 915
  • 2
  • 11
  • 21
  • 1
    It's unclear to me what you are asking. If each function returns one of those three values,what is the state for? – Cirdec Sep 13 '14 at 05:56
  • Why not, simply return a new list with appended data. – 4lex1v Sep 13 '14 at 06:14
  • Hi Cirde, sorry if my question is not clear: I need than all these functions add a tuple to the same list l ...the state will be in the single list – user1050817 Sep 13 '14 at 06:19

1 Answers1

4

Assuming you'd like to distinguish between those three types of tuple

data Item = User      String Int
          | Company   String Int
          | NonProfit String Int

Then added Items to a list in state is pretty simple:

addUser, addCompany, addNonProfit :: String -> Int -> State [Item] ()
addUser      name age     = modify (\st -> User      name age     : st)
addCompany   name founded = modify (\st -> Company   name founded : st)
addNonProfit name founded = modify (\st -> NonProfit name founded : st)
J. Abrahamson
  • 72,246
  • 9
  • 135
  • 180