News for hackers. Stuff that matters.
Re:Monads in JavaScript by theophrastus on Monday July 20, 2015 @10:42PM (#9920301)
I'd say you're now almost guilt-edged required to provide us with your simple explanation here. But i'll warn you, i've been nicely flummoxed by competing 'simple' explanations in this forum previously: "A Monad is an object whose methods return monads.", "They're simply a highly specific way of chaining operations together.", "You know how jQuery methods can string out multiple methods with periods? That's what monads are.", "Monads are merely an analogy to control flow what abstract data types are to data."
Re:Monads in JavaScript by anon4 on Tuesday July 21, 2015 @02:53AM (#9920849)
Haskell is a pure language. Purity is a concept that is absolutely bizarre to the real world, where adding two numbers together results in tons of side effects (load into registers, oops, have to load cache lines, alter memory, raise the ambient temperature, etc. etc.). However, the idea of pure functions is useful. So we make our basic program blocks from pure functions that don't "do" stuff, but just transform values.

However, we must chain these into useful programs somehow. Monad is the type name chosen in Haskell for the construct that does this. It's kind of simple if you work it backwards from the syntax. You want to be able to say

    do
      a <- readInt
      b <- readInt
      add a b
      print
The first two can fail, rely on side effects and the last one is purely a side effect. The only pure function is add, which can't work if a or b aren't there. Monads serve as a way to represent the real-world-ness without it seeping into the add function. You can think of each line as a closure getting the next value from the previous line. So readInt returns a Maybe Int. If it returns a Nothing, the next closure is simply skipped. You can insert a check after the add, if you want to, to see if you got Nothing and alert the user, etc. However, the basic idea is that the program does not crash with a NullPointerException. We know what to do if we get Nothing. The add function doesn't need to concern itself with that.

Hence, the Monad. It wraps a real world concern around a type (it has a type constructor). You must be able to make one from a concrete value that is unburdened with exceptional state (it has the unit function). You must be able to call pure functions on these monadic values without the side state seeping into the function (it has the bind function).

Edit: the reason you don't see Monads in other languages is because they're not essential to them. You can do stuff in C without Monads. To Haskell, Monads are like the Higgs boson. It's how you bind stuff together.

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @09:30AM (#9922084)
A few quibbles:

* Purity is not at all bizarre to the real world. If I have two apples in one pile and three in the other, then merely regarding them as the same pile is (2 + 3) very, very purely. Computers are the bizarre ones!

* "The first two can fail, rely on side effects and the last one is purely a side effect." It'd be much nicer to say that the first two are "side effecting computations with interesting return values" and the third one it the same... except we are not interested in the return.

* "The only pure function is add". I highly doubt that `add` is pure in your example! (1) this wouldn't typecheck in Haskell now if it were and (2) it'd imply that we are just throwing away the result of the addition.

* "the reason you don't see Monads in other languages is because they're not essential to them" I would challenge you to turn this exactly on it's head. The reason you don't see monads in other languages it that they are so essential to them that you cannot perceive parts without the monad.

Re:Monads in JavaScript by dllthomas on Tuesday July 21, 2015 @02:56AM (#9920858)
"You must be able to call pure functions on these monadic values without the side state seeping into the function (it has the bind function)."

That sounds more like fmap.

Re:Monads in JavaScript by pdpi on Tuesday July 21, 2015 @07:04AM (#9921426)
First three lines could just be written using applicatives only:

(+) <$> readLn <> readLn

The monadic part only comes into play in the last line:

(+) <$> readLn <> readLn >>= print

It's part of what makes it monadic that the action takes an argument.

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @09:41AM (#9922154)
It's really the add function, strangely, which is monadic here.

Or the whole thing is an applicative if you take at face value his claim that add is pure.

Re:Monads in JavaScript by nemothekid on Tuesday July 21, 2015 @03:50AM (#9920963)
Your explanation makes sense, but I don't see how are Monads different from Rust's Option Type (or Java's Optional Type?), or any other nullable type?
Re:Monads in JavaScript by andrewaylett on Tuesday July 21, 2015 @04:59AM (#9921107)
Option and Optional are indeed monads, and Java's Optional.flatMap() function is the monadic /bind/ function. But not all monads are Optional -- List is also a monad, and they go on to get a lot more complex than that.

I found that reading about Haskell really helpful for my Java development, and that looking at really simple monads like Optional, and using them in my code, was really helpful for understanding how more complicated monads work. Jumping straight into Haskell's IO monad is really unhelpful.

Re:Monads in JavaScript by eutectic on Tuesday July 21, 2015 @04:02AM (#9920987)
The maybe monad is just being used as an example here, but Haskell allows you to implement the same interface for any applicable type. for example; IO, mutable state, parsers, etc.
Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @09:24AM (#9922034)
"Monad" is more like an adjective. "Option" is a monad, but, interestingly, the union type (A | null) is not.
Re:Monads in JavaScript by dllthomas on Tuesday July 21, 2015 @09:58PM (#9927284)
As I understand it, this is because nullability (typically?) doesn't nest and so can't be a functor (with the whole of the types of the language as domain). If you can't wind up with m (m a), then there is no place for join.
Re:Monads in JavaScript by tel on Wednesday July 22, 2015 @08:05PM (#9933190)
Yeah, exactly. The other way to see it is to note that `Nothing(null)` is a perfectly reasonable Javascript expression which ought to mean something different from `null` alone. If that cannot be true then you don't actually have parametricity.
Re:Monads in JavaScript by belovedeagle on Tuesday July 21, 2015 @01:34AM (#9920702)
So this is going to sound snarky and/or stupid at first, but: Monads are functors with a 'join' ("flatten") operation.

A functor is a type parameterized by another type[1], say 'a', with a function 'fmap' taking a function 'a -> b', yielding the original object except that its type is now parameterized by 'b'[2]. A monad's 'join' operation takes 'f (f a)' onto 'f a'.

On top of this, there are certain laws which must be obeyed. The functor laws amount to saying that 'fmap' can't change anything about the object (including structure) which doesn't depend on the parameter 'a', but must change everything which does depend on 'a'. The monad laws amount to saying that 'join' has a certain associative structure[3], and also that there is a left- and right-identity 'return: a -> f a'.

[1] a la Java generics, for those not into FP

[2] i.e., fmap has type 'forall a b. (a -> b) -> (f a -> f b)'

[3] Explaining exactly what this associative structure is in these terms is tricky, since 'join' as described is unary. Here's where you have to introduce the function 'bind', '(\f -> join . fmap f)': 'bind g . bind f' === 'bind (bind g . f)'. But it's really not essential; the most intuitive consequence is that Haskell's 'do' notation works like you want it to.

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @08:39AM (#9921765)
You need "return" too. Can't get that from merely being a functor.
Re:Monads in JavaScript by belovedeagle on Saturday July 25, 2015 @02:04PM (#9948402)
> and also that there is a left- and right-identity 'return: a -> f a'

RTF, uh, Comment.

The point being that I think it's best to understand return in the context of the more important operation join. You might wonder, "well why don't functors have a generic constructor", and (among other answers to that) the reason is that it doesn't serve any purpose in the functor laws. But return does serve a purpose for the monad laws, namely, being an identity of sorts.

Re:Monads in JavaScript by flippinburgers on Tuesday July 21, 2015 @04:27AM (#9921048)
https://www.youtube.com/watch?v=yvwaxYro4FU

I've struggled with blog posts about monads countless times. Maybe I just find it easier to listen to some explanations rather than read them.

Re:Monads in JavaScript by sportanova on Monday July 20, 2015 @11:17PM (#9920394)
A monad has two operations - bind and return - and they're used for chaining
Re:Monads in JavaScript by theophrastus on Monday July 20, 2015 @11:23PM (#9920410)
Now i've got N+1 'simple' explanations which I can use to confuse me [wink]. "bind" and "return" you say? so they're quite like a socket library?
Re:Monads in JavaScript by im3w1l on Tuesday July 21, 2015 @12:33AM (#9920577)
Those names are not very good. return takes a value and "monadifies" it. If you have function that takes a normal argument and emits a monadified value (e.g. int -> monad string). Then bind can transform your function so that it takes a monadified argument (e.g. monad int -> monad string) instead.

return and bind satisfy three laws:

1. If you have function that takes a normal argument and emits a monadified value. You could apply it to some argument right. Or you could monadify the argument with return, and then use bind on the function so it will accept the monadified argument. These two ways of using the function give the same result.

2. Remember how return takes an argument, and emits a monadified value? That means we can bind it! The second law states that the resulting function is just the identity for monadified stuff.

3. Lets say you have two functions f (e.g. float -> monad string) and g (e.g. string -> monad int) from normal argument to monadified value. We could bind them both and then compose them.

    g_ = bind(g)
    f_ = bind(f)
    g_f_(x) = g_(f_(x))
Or we could imagine instead binding only the second function, then composing the functions, and then monadifying the composition.

    g_ = bind(g)
    g_f(x) = g_(f(x))
    g_f_ = bind(g_f)
Law 3 states that these two procedures yield the same g_f_
Re:Monads in JavaScript by theophrastus on Tuesday July 21, 2015 @01:11AM (#9920662)
Having offered this kindly explanation, would you say that this continues in the holy pursuit of a 'simple explanation' of what a monad is?

Here's an intermediate question triggered on your explanation: what is the byte level nature of your "monadification"? you say one has a function which converts a floating point to a "monad string", a string value to a "monad int" (a raven into a 'monad writing desk')? exactly what bytes characterize a "monad string" from a string? a "monad int" from a plain old int? it's perhaps a structure? maybe it has stack pointers among those structural elements?

Re:Monads in JavaScript by efnx on Tuesday July 21, 2015 @01:54AM (#9920738)
If 'm' is a monad then the difference between a 'String' and a 'm String' (monad string) is most likely just a constructor, but it's really up to that particular monad's implementation. It isn't a byte level difference, it's a context level difference. Constructors are very different in Haskell than (insert imperative Lang). They are much simpler. Monads are similarly simple but hard to explain without any familiarity with the language. I suggest you just dive in. The cool thing about Haskell is you don't have to understand everything in order to work with it.
Re:Monads in JavaScript by im3w1l on Tuesday July 21, 2015 @07:34AM (#9921501)
There are many monads, so the answer will depend on which one it is. For instance the "Maybe" monad I described in a sibling comment to yours could be implemented with a pointer that could be null, or not.

Another Monad could be a Logger monad. "return" transform a value into a pair of a value and an empty log. So in this case a monad int could be implemented as a pair<int, string>. (bind would take a function that starts logging from scratch and make it a function that appends to a preexisting log).

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @09:35AM (#9922113)
It's really, really vital to note that "monad" is not a noun but an adjective. Your question thus has no answer as stated.

Let's pick a type which happens to be monadic, though, like list. If `A` is a type and `List A` is the type of singly-linked lists with values in `A` then `fun a -> Cons a Nil` is what's sometimes called `return` and `flatten :: List (List A) -> List A` is what's sometimes called `join` and (List, return, join) is monadic.

And anyway, the byte-structure of SLLs can vary from place to place, but any good implementation that works generically will do.

Re:Monads in JavaScript by theophrastus on Tuesday July 21, 2015 @11:34AM (#9922933)
Since you raised the linguistic characterization, (..'monad' is an adjective, not a noun, so your question doesn't apply), you'd therefore say there's "thus no answer" to the question: what's the difference between a "blue envelope" and a basic envelope? ('blue' being an adjective)

In my experience, here's often what's lacking with teaching the latest in programming formalisms: folks need the new concepts explained in some terms of the old in order to understand them, (hence why i was trying to get someone to explain monads in terms of crusty old terms like (C) structures). The frustrating tendency always seems to be to concoct a host of new terms, and then to define them only among those unfamiliar terms; often giving well-intentioned detailed examples yet only using those novel terms and syntax. It would be akin to teaching a foreign language but not even trying to pick up a familiar object and point to it in association with saying the new term for it.

By the bye, i accept and appreciate the explanation given somewhere here (likely by 'im3w1l'), that monadization generates a different structure for different incidences of monadification. This helps conceptualizing the mechanism, in a way that "binding of flattened functors returning null or non-null monads" doesn't. It's worthy to assume that we didn't all spring forth full grown out of the forehead of a particular computer science theory class.

Nonetheless, the efforts are appreciated. Even given the root commenter here promised that monad was a "simple concept" with a simple definition. If you scan about this comment section, do you think this view is well supported?

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @12:25PM (#9923403)
I agree with you, but think monad is a poor place to start such a discourse. It's a "simple" concept once you've gotten some other ideas firmly cemented.

I also think there's the standard "simple/easy" dichotomy going on here. Monad is SO simple that it can be quite hard to grok in the same way that quantum physics is.

I fully agree with im3w1l's note about different things coming from different "monadifications" and find that completely consistent with what I've been saying. I'm not sure who uttered the other quote but it's as misleading as it is nonsensical. I think that's the risk with explaining this stuff partially anyway: simplicity isn't necessarily easy and there are lots of partial understandings of "monad" floating around.

Re:Monads in JavaScript by theophrastus on Tuesday July 21, 2015 @01:19PM (#9923913)
hm... "it's so simple it's hard to understand". i'm also very familiar with the 'monads can't be explained until later!' concept. yet folks who say they understand monads so often make heavy use of the term considerably earlier than "later".

"quantum physics" is an interesting reference for me. as it's often my job to implement quantum mechanics in software. computers are dumb. they 'understand' little beyond patches of memory upon which simple algebraic operations are done. so when i'm teaching quantum mechanics i often find it useful to explain how one applies it for (dumb) computers. "ooooh! second order differential equations are implemented as simple iterative passes over an array of floating point values - that's easy!" the student comes to see through the notable complexity of quantum mechanics by observing how we 'teach' it to a computer. why the hell do i bore you-all with this? well, it's possible that showing how one implements a monad in terms of dumb patches of memory, dumb interrupt vectors, bits and bytes, might not be a bad starting point for a common language ..maybe. anyway thank you for trying (it won't be the last time monads are null-functor flattened re-re-re-hashed)

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @02:29PM (#9924574)
Fair enough, and I also provided a "raw patches of memory" example earlier provided that you are willing to buy linked lists as common language :)

QM via approximation is an interesting point! I suppose in that sense my metaphor breaks down. Approximation works in some fashions, but you need notions of convergence to make that go. These cannot be had in describing monad-nature.

I'd definitely say that once you "have" the concept it becomes standard and nigh universally useful vocabulary. You want to use it a lot because it makes a lot of sense to do so, but this isn't a good didactic method.

I also kind of want to argue generally against the idea that computers are just dumb machines capable only of shuffling memory around. Of course to a certain degree this is true, but only in the same way that algebra is just a series of symbolic algorithms. It's true, but there's nothing interesting to be had from that POV.

The fun stuff occurs when you take the perspective that what's going on inside the model represents faithfully something more interesting going on inside our own heads or out in the world.

Monads are a powerful, simple and subtle thing which happen entirely abstractly—it's just up to us as humans to recognize the pattern (or, equivalently, up to automated computer algebra pattern inference machines to do the same).

Re:Monads in JavaScript by im3w1l on Tuesday July 21, 2015 @10:14AM (#9922372)
I don't think you can define a monad in terms of just (return,join). (return,bind) works, or (fmap,join).

EDIT: As a counterexample to uniqueness, consider fmap defined such that for all f and x, (fmap(f))(x)=[].

It is consistent with your return and join.

Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @12:27PM (#9923418)
Also with your edit it's worth noting that your given fmap cannot be: it violates both functor laws. As it turns out, for Haskell and most datatype-like functors there is exactly one law abiding implementation of fmap implicit in the structure of the type.
Re:Monads in JavaScript by im3w1l on Tuesday July 21, 2015 @01:10PM (#9923833)
Ah yes, you are right.
Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @12:18PM (#9923351)
Sorry, that's a good point. The triple formalism (T, mu, eta) already assumes T to be a functor, but I didn't state that explicitly! So you need (List, map, return, flatten) all of them.
Re:Monads in JavaScript by im3w1l on Tuesday July 21, 2015 @12:50AM (#9920618)
Ok let me give you an example of a monad! The Maybe monad. In this case a monadified value either has a normal value, or it has a null. Ok, so for the operations. "return" should monadify a value. In this case it does this by creating a Maybe that has that value (Maybes that have null can not be created with return. They must be created in some other way.). The bind operation creates a new function that takes a Maybe value from one that doesn't. If the Maybe has a normal value then the function is run like normal. But if the Maybe has a null, the function is not run. Instead null is emitted directly.

Why is this a good thing? It means you can chain together many failure prone operations, and you only have to check for null at the end, not in the middle. So it works a little bit like exceptions.

Let's verify the laws:

1. We have some value, and some function that could take that value, and either emit a result, or a null. If we monadify our value, we get a Maybe that has that value. If we bind our function, and then run it with our Maybe, what happens? Well we know our Maybe is not null, because we just put in a totally legit value. So because of how we defined our bind, the function will run just like normal.

2. Ok so lets bind "return" and see what happens. If the input is a maybe that has null, then we never run "return" but just emit null. Consistent with identity! If the input is a maybe with a normal value, then we run "return" with that value. Return creates a maybe that has that value. So we get out what we put in, it works!

3. There are a number of cases we have to go through but let's do them one by one.

First construction: a) x is null. f_ skips f and just emits null. g_ skips g and just emits null. b) x is non-null. first we put x in f_. Since x is not null we just apply f to the normal value. Now f can either emit a normal value or null. b1) f emits null. g_ is skipped result is null. b2) If result is not null, g is run with the normal result, and result of overall computation is g(f(normal argument))

Second construction: a) x is null. g_f_ skips g_f and just emits null. Same result as before b) x is not null. g_f is run with value in x. To run g_f we first run f. Two cases. f emits normal value or null. b1) f emits null. g_ of null is null. So if value in x causes f to emit null we have null just as before. b2) f does not emit null. g_ just runs g with normal result. So if value in x does not cause f to emit null, result of computation is g(f(normal argument))

So both constructions work the same, they continue running until problem arises.

Re:Monads in JavaScript by sportanova on Monday July 20, 2015 @11:46PM (#9920467)
ha well it's more like a burrito that has two operations
Re:Monads in JavaScript by gimboland on Tuesday July 21, 2015 @04:32AM (#9921061)
s/guilt/gilt/
Re:Monads in JavaScript by tel on Tuesday July 21, 2015 @09:02AM (#9921892)
Let's try this one.

"A monad" isn't a thing, but we can ask what it takes for something to "have monad-nature" or "be a monad". For this to occur our something must be three things, a triple

    (T, mu, eta)
The names are all meaningless so for the moment they just get short letters.

T must be what's known as a Functor. For PLs really, though, it's even more specific. It's an "endofunctor on the type category of your language". What this means is simple

* For any (static) type `a` in your language, `T a` is also a static type.

* For any function `f` from type `a` to type `b`, `T f` is a function from type `T a` to `T b`.

If your language doesn't have static types then you can approximate this by pretending that it does. Also note that `T f` is not usually the syntax used, but it'll do for now.

Now to make a monad we take any choice of Functor `T` and give it two operations. `eta` takes values in type `a` to values in type `T a` while `mu` takes values in type `T (T a)` to values in type `T a`. In other words they give you a "layer manipulation toolkit".

They must follow laws as well, but these laws are all "common sense laws" which allow you to think of values in the following types: `a`, `T a`, `T (T a)`, `T (T (T a))`, `T (T (T (T a)))`, ... as all being the same as values with just one layer: `T a`. This is the "flatten" idea.

And there you have it! Anything at all which can be regarded as equivalent to one of these triples following this design and laws is a monad!

---

So the real question is why should someone care? The answer is simple.

Lots of things have monad-nature in a typed language. By recognizing their common nature we can (a) see them in a new light full of perhaps previously unknown similarities, (b) share terminology lightening the burden of how to use them, (c) write generic operations which work over any monad and expect them to work with each specific one in a similar way, (d) introduce new syntactic sugar which is built entirely from (mu, eta) and expect it to work similarly for every thing with monadic-nature, (e) begin to form theories and impressions of "what it means to be a monad".

The reasons (a-d) show up all the time once you recognize this pattern since monads are really common.

Reason (e) is what everyone wants to hear about but it's hard to talk about without being super arm-wavey. But I'll try.

In order to provide the operation `mu :: T (T a) -> T a` the type `T a` must be able to "internalize itself" without losing too much information. In order to follow the laws, one bit of important information is an idea of sequence or nesting—but one unique to each particular monadic triple.

In this way monads are a very, very, very general way of talking about sequencing or nesting.

What makes thins interesting is that you can see imperative languages as being about sequencing or nesting as well. If you have a listing of statements { X ; Y ; Z } then you can see { Y ; Z } as being nested in the execution context that X created and { Z } being nested in the execution context that { X ; Y } created.

This would maybe make you think that imperative languages have monad nature and indeed they do. This leads to an interesting study of questions like "For some given imperative language, what is a pure-functional representation of the monad representing it?" which sometimes has interesting answers.

What's even more interesting is that one example of reason (d) above is to introduce a syntax sugar which makes any monad look a bit like an imperative language. This leads to an interesting study of questions like "What does the imperative language for some monad X feel like?"

So if you really like imperative languages and recognize that there's a larger design space here that most have any familiarity with then monads are a good thing to keep an eye out for.