0

I've been reading and watching material on FP for the past few weeks and now I'm trying to apply a simple State Monad as an example. I'm programming in Javascript (I know, it's not Haskell..), and I'm struggling with this simple example, so I guess I might be assuming something wrong from the start.

The simple example I'm talking about is transforming a string into a list of characters, like this:

// toChars :: String -> [String]
// "hello" => ['h','e','l','l','o']

I found this video of Brian Beckman explaining the State Monad really interesting so I wanted to give it a shot. I've been reviewing the C# example posted here which labels a binary tree (adds a number to the each leaf that's incremented every time it reaches a leaf). In that case, the state is the number and the contents is a Labeled Tree.

The problem is, I can't really decide what's my state and what's my content in the string-to-array example, since both will be mutating, and I need both things passed on to the next monad in the chain.

Is there some kind of rule to follow to decide what's contents and what's state?

Thanks!

user1232579
  • 63
  • 1
  • 5
  • A pure function has exactly one result value for each input. A stateful function has a composite return value consisting of the actual return value and the additional state value. This state value acts like a global environement, which you can read from and write to across function calls. Since the state type is a wrapper for a function it is only evaluated when the initial state is passed by calling `runState(initialState)`. As a result you can compose stateful computations with `chain` without rendering your program impure. –  Nov 14 '19 at 16:09
  • `State` is a complex type and hence not a good one to start with. You can make a lot of FP experiences without touching `State`. –  Nov 14 '19 at 16:12
  • Why do you even need the state monad to implement the `toChars` functions? – Aadit M Shah Nov 15 '19 at 12:41
  • Hey @AaditMShah -- I know it's now a good use case for it, I'm just trying to do a very simple example to learn how to use it properly. – user1232579 Nov 15 '19 at 15:59
  • Then pick a different example which is stateful. The `toChars` function doesn't require any state. – Aadit M Shah Nov 16 '19 at 03:15

0 Answers0