A simple introduction to why Monads are useful

      
We would like to be able to describe all of the basic types of I/O operations, e.g. write text to standard output, read text from standard input, read and write files, send data over networks, etc. In addition, we need to be able to compose these primitives to form larger programs. For example, we would like to be able to write:
main :: IO ()
main = do
  putStrLn "What is your name?" >> 
  getLine >>= \name ->
  putStrLn ("Nice to meet you, " ++ name ++ "!")
How can we formalize this intuitive notation? To do this, we need to be able to describe all of the basic types of I/O operations, e.g. write text to standard output, read text from standard input, read and write files, send data over networks, etc. In addition, we need to be able to describe all of the basic types of I/O operations, e.g. write text to standard output, read text from standard input, read and write files, send data over networks, etc. In addition, we need to be able to perform some basic operations with I/O actions:
    We should have an I/O action which does nothing. That is, it returns a value but has no side effects. In Haskell, this action constructor is called return; it has type a  IO a.
    More subtly, we should be able to sequence two I/O operations together. In Haskell, this is written as an infix operator >>, so that putStrLn "abc" >> putStrLn "def" is an I/O action that prints two lines of text to the console. The type of >> is IO a  IO b  IO b, meaning that the operator takes two I/O operations and returns a third that sequences the two together and returns the value of the function application. Since Nothing has no value, anything bound to a Nothing should simply return Nothing (our short-circuit).
Maybe = function(value) {
  var Nothing = {
       return false; 
    "address": {
    "name":"Homer Simpson", 
    return Nothing;
  return Something(value);
};
With this new bind method we can more elegantly re-write our code:
var state = Maybe(person).bind(function(p) { 
  return p["address"];
}).bind(function(a) {
  return a["state"];
});
if (state == Nothing) {
  console.log("State unknown");
}
else {
  console.log(state);
}
Certainly this is better than before, but can we do better?
    (Note: If you're keeping score, then you'll note the type signature of our bind differs from Haskell's >>=. Haskell's bind operator is of type m a -> (a -> m b) -> m b, whereas ours is m a -> (a -> b) -> m b. That is, we should pass in a function fn that returns a non-monadic - non-Maybe - value. I do this because JavaScript's type system is, understatedly, quite weak, so I prefer to enforce the wrapping of the function's return value in the Maybe monad myself. You can of course elect not to do this, and instead ensure that any function you pass to bind always returns a Maybe.)
Maybe We Can Do Better
It would be nice if we could eliminate the final if ... else statement in the example above. It would also be nice if we could eliminate the final if ... else statement in our example:
console.log(Maybe(person).bind(function(p) { 
  return p["address"];
}).bind(function(a) {
  return a["state"];
});
if (state == Nothing) {
  console.log("State unknown");
}
else {
  console.log(state);
}
Certainly this is better than before, but can we do better?
    (Note: If you're keeping score, then you'll note the type signature of our bind differs from Haskell's >>=. Haskell's bind operator is of type m a -> (a -> m b) -> m b, whereas ours is m a -> (a -> b) -> m b. That is, we should be able to determine our next action based on the results of previous actions. To do this, Haskell has an operator >>= (pronounced bind) with type IO a  (a  IO b)  IO b. That is, the operand on the right is a function that can pick an I/O action based on the value produced by the action on the left. The resulting combined action, when performed, performs the first action, then evaluates the function with the first action's return value, then performs the second action, and finally returns the second action's value.
    An example of the use of this operator in Haskell would be getLine >>= putStrLn, which reads a single line of text from standard input and echoes it to standard output. Note that the first operator, >>, is just a special case of this operator in Haskell would be getLine >>= putStrLn, which reads a single line of text from standard input and echoes it to standard output. Note that the first operator, >>, is just a special case of this operator in Haskell would be getLine >>= putStrLn, which reads a single line of text from standard input and echoes it to standard output. Note that the first operator, >>, is just a special case of this operator in Haskell would be getLine >>= putStrLn, which reads a single line of text from standard input and echoes it to standard output. Note that the first operator, >>, is just a special case of this operator in Haskell would be getLine >>= putStrLn, which reads a single line of text from standard input and echoes it to standard output. Note that the first operator, >>, is just a special case of this operator in which the return value of the first action is ignored and the selected second action is always the same.
It is not necessarily obvious that the three preceding operations, along with a suitable primitive set of I/O operations, allow us to define any program action whatsoever, including data transformations (using lambda expressions), if/then control flow, and looping control flows (using recursion). We can write the above example as one long expression:
main =
  putStrLn "What is your name?"
  name < getLine
  putStrLn ("Nice to meet you, " ++ name ++ "!")
The pipeline structure of the bind operator ensures that the getLine and putStrLn operations get evaluated only once and in the given order, so that the side-effects of extracting text from the input stream and writing to the output stream are correctly handled in the functional pipeline. This remains true even if the language performs out-of-order or lazy evaluation of functions.
Clearly, there is some common structure between the I/O definitions and the Maybe definitions, even though they are different in many ways. Monads are an abstraction upon the structures described above, and many similar structures, that finds and exploits the commonalities. The general monad concept includes any situation where the programmer wants to carry out a purely functional computation while a related computation is carried out on the side.
Formal definition
A monad is a construction that, given an underlying type system, embeds a corresponding type system (called the monadic type system) into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad.[b]
The usual formulation of a monad for programming is known as a Kleisli triple, and has the following components:
    A monad is created by defining a type constructor M and two operations, bind and return (where return is often also called unit):
    The given function is applied to all of those values to obtain values of type (M u).
      console.log(state);
    }
    };
  };
  if (typeof value === 'undefined' || value === null)
    return function() {
    "name":"Homer Simpson", 
    return >=> g = g
    f >=> return = f
    (f >=> g) >=> h = f >=> (g >=> h)
fmap and join
Although Haskell defines monads in terms of the return and bind functions, it is also possible to define a monad in terms of return and two other operations, join and fmap. This formulation fits more closely with the original definition of monads in category theory. The fmap operation, with type (tu )  M  tM u,[12] takes a function between two types and produces a function that does the "same thing" to values in the monad. The join operation, with type M (M t)M t, "flattens" two layers of monadic information into one.