Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of monads in OCaml?

Tags:

monads

ocaml

This might be a stupid question, but since OCaml is not pure and has side effects built-in, what is the use of monads in OCaml?

like image 689
Bob Fang Avatar asked Apr 24 '15 15:04

Bob Fang


People also ask

Why do we need monad?

monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems.

What is maybe monad?

The Maybe monad represents computations which might "go wrong" by not returning a value.

Are monads composable?

Monads are not composable. This poses a problem, since composition is one of the foremost patterns in functional programming. However, many alternatives have been devised. One of the most common is the monad transformer.

Is a monad a functor?

An endofunctor is a functor mapping a category to itself, and a monad is an endofunctor together with two natural transformations required to fulfill certain coherence conditions.


1 Answers

Monads have nothing to do with purity, except that a pure language without Monads would be almost entirely useless.

In layman's terms, a Monad is just a set of rules that describe how a sequence of steps can be executed. Having a Monad abstraction gives you the ability to define a DSL for executing stuff. A Monad can be built to intelligently handle things like exceptions, ATOMIC rollbacks/commits, retry logic, sleeping between each step, or whatever.

Here are some examples of Monads:

https://wiki.haskell.org/Monad#Interesting_monads

I realize that this list is for Haskell, which is a pure language, but don't let that confuse you.

You don't need to understand category theory to understand what a Monad is, contrary to popular belief. A monad basically has 2 things: (paraphrased from this wikipedia article)

  1. A unit function, defined as (a -> M a), called "return" in Haskell, used to put a value into the context of a Monad.

  2. A binding operation, defined as (M t -> (t -> M u) -> M u), which looks scary but if you look carefully, this is a function that gets invoked between each step of the process, this is where you inject the good stuff.

Depending on the language, there may be more things, but this is the heart of it.

like image 131
James Watkins Avatar answered Oct 10 '22 11:10

James Watkins