5

I can write a State Monad (in Scala/Java) and can pretty much follow the logic when I see others using it. I don't fully understand the problem it is solving. It is a monad wrapping the funciton S => (S,A).

As such, when you nest functions that result in a State Monad via flatMap it gives you a set of instructions/operations to perform on the data (S) (but hasn't executed them yet). Not until the very end, when you give it an S and tell it to run, does it do work.

What are the benefits of doing this versus just writing functions to pretty much do the same thing?

Monads don't compose, so having these functions in this way seems to have large implications for design. Please, if you provide code for an example, use Java or Scala (as I don't understand how to read Haskell or other strictly Functional languages). hanks!

user2864740
  • 60,010
  • 15
  • 145
  • 220
jordan3
  • 877
  • 5
  • 13

2 Answers2

1

The benefit, as it is in most cases with functional vs. imperative programming is referential transparency. That is, given a function, the same inputs will always return the same outputs. This is a property of systems that makes them much easier to reason about and to change them.

If you don't consider that to be an importan benefit, then probably there is not much value in using them. I think that is mostly a matter of opinion.

For an example, I'm going to link you to the excellent learning Scalaz post by Eugene Yokota.

emilianogc
  • 880
  • 4
  • 19
0

The power is in the ability to chain together functions that are otherwise dissimilar.

A function that takes a state-value pair and returns another state-value pair is fundamentally different from one that takes a value and returns a value. If you tried to rewrite the latter to use state-value pairs, it would be tedious, and perhaps even error-prone if you have a lot of functions like that. If you rewrote those functions directly, they would become less general; conversely, adding a thin wrapper around each of them would add a lot of boilerplate.

Using the state monad instead allows you to promote functions on state-value pairs to the monad using bind, and functions from values to values to the monad using fmap. The monad is then a common data type that all these promoted functions understand, making it suitable for function composition (not the same as monad composition). Your "boilerplate" in such a case is merely to use fmap/bind where needed.

Very little of that is particular to the state monad (just replace "state-value pair" with anything else).

Muphrid
  • 111
  • 2