views:

197

answers:

2

Hi all, I'm a C# guy looking to learn F# and functional programming. I'm hearing a lot about "monads" .. which I think (thanks to Google), are called "Computation Expressions" in F#?

One aspect I'm trying to bend my head round is the State Monad/Computation Expression... But I need an idiot-proof, line-by-line, explanation about what's going on in the code.

I really feel this State issue is going to be my major stumbling block with functional programming... As far as I can understand: Immutability is king, and the state monad is a magical unicorn that gives you stateless-state. Unfortunately it's so arcane I just can't find a simple explanation of it :¬/

I hope some boffins out there can help me grasp the concept or link me to some idiot-proof info on the subject.

Thanks in advance,

JD.

+4  A: 

I would stay away from monads until such time as you have more experience/familiarity with a functional language and its syntax. Monads (and computation expressions in F#) are extremely cool, and also not very important to know on day 1 or day 10. Hold off until day 30, and then try to approach them with care.

(As an aside, since you're a C# guy, if you know LINQ, and know how the LINQ syntax desugars into method calls, then you already have a good operational definition of some of the main language features. What is interesting is applying these features to things other than collections/enumerables.)

Brian
+5  A: 

See this wikibooks article.

The trick behind the State monad is not actually changing state but using transitions for describing how to propagate change through the workflow in an abstract way. Using the special monadic syntax F# provides, one can define finely grained mutable states in a nearly imperative syntax.

But - as Brian said - it's not relevant for learning functional programming. You should know how to deal with immutable state by yourself and then you'll find the definition of how to hide the state using monads by yourself.

Dario
As the author of that article, I'd say its crap ;) Some history: I wrote the wikibook during some slow days at work as a way to teach myself F#, and its extremely verbose in the parts that **I** personally struggled with (I figure if I needed something explained, others do too, so try not to gloss over things). I had a bad understanding of monads at the time and will consider re-writing when I have the time/motivation to do so :)
Juliet
@Juliet: I like the part with the computation expressions. Nothing wrong with this explanation of monads. It's rather the Async Workflow article that's kind of problematic (you don't use `let!` in the download code at all, you just parallelize afterwards).
Dario