ArticleslgStudy

mathematics

Monad (functional programming)

Monad (functional programming) is a mathematics topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Monad (functional programming) rather than just read about it. In short: In functional programming, monads are a way to structure computations as a sequence of steps, where each step produces a value, plus some extra information about the computation, such as a potential failure, non-determinism, or side effect. More formally, a monad is a type constructor M equipped with two operations, return : <A>(a : A) -> M(A) which lifts a value into the monadic context, and bind : <A,B>(m_a : M(A)…

Monad (functional programming) — main illustration
Monad (functional programming) — illustration

Key takeaways

  • Monad (functional programming) belongs to mathematics; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Monad (functional programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Monad (functional programming) from memory before moving on to harder problems.

Reference excerpt

In functional programming, monads are a way to structure computations as a sequence of steps, where each step produces a value, plus some extra information about the computation, such as a potential failure, non-determinism, or side effect. More formally, a monad is a type constructor M equipped with two operations, return : <A>(a : A) -> M(A) which lifts a value into the monadic context, and bind : <A,B>(m_a : M(A), f : A -> M(B)) -> M(B) which chains monadic computations. In simpler terms, monads can be thought of as interfaces implemented on type constructors, that allow for functions to abstract over various type constructor variants that implement monad (e.g. Option, List, etc.). Both the concept of a monad and the term originally come from category theory, where a monad is defined as an endofunctor with additional structure. Research beginning in the late 1980s and early 1990s established that monads could bring seemingly disparate computer-science problems under a unified, functional model. Category theory also provides a few formal requirements, known as the monad laws, which should be satisfied by any monad and can be used to verify monadic code. Since monads make semantics explicit for a kind of computation, they can also be used to implement convenient language features. Some languages, such as Haskell, even offer pre-built definitions in their core libraries for the general monad structure and common instances.

Overview "For a monad m, a value of type m a represents having access to a value of type a within the context of the monad." —C. A. McCann More exactly, a monad can be used where unrestricted access to a value is inappropriate for reasons specific to the scenario. In the case of the Maybe monad, it is because the value may not exist. In the case of the input/output (IO) monad, it is because the value may not be known yet, such as when the monad represents user input that will only be provided after a prompt is displayed. In all cases the scenarios in which access makes sense are captured by the bind operation defined for the monad; for the Maybe monad a value is bound only if it exists, and for the IO monad a value is bound only after the prior operations in the sequence are performed. A monad can be created by defining a type constructor M and two operations:

return :: a -> M a (often also called unit), which receives a value of type a and wraps it into a monadic value of type M a, and bind :: (M a) -> (a -> M b) -> (M b) (typically represented as >>=), which receives a monadic value of type M a and a function f that accepts values of the base type a. Bind unwraps M a, applies f to it, and can process the result of f as a monadic value M b. (An alternative but equivalent construct using the join function instead of the bind operator can be found in the later section § Derivation from functors.) With these elements, the programmer composes a sequence of function calls (a "pipeline") with several bind operators chained together in an expression. Each function call transforms its input plain-type value, and the bind operator handles the returned monadic value, which is fed into the next step in the sequence. Typically, the bind operator >>= may contain code unique to the monad that performs additional computation steps not available in the function received as a parameter. Between each pair of composed function calls, the bind operator can inject into the monadic value m a some additional information that is not accessible within the function f, and pass it along down the pipeline. It can also exert finer control of the flow of execution, for example by calling the function only under some conditions, or executing the function calls in a particular order.

An example: Maybe

One example of a monad is the Maybe type. Undefined null results are one particular pain point that many procedural languages don't provide specific tools for dealing with, requiring use of the null object pattern or checks to test for invalid values at each operation to handle undefined values. This causes bugs and makes it harder to build robust software that gracefully handles errors. The Maybe type forces the programmer to deal with these potentially undefined results by explicitly defining the two states of a result: Just ⌑result⌑, or Nothing. For example, the programmer might be constructing a parser, which is to return an intermediate result, or else signal a condition which the parser has detected, and which the programmer must also handle. With just a little extra functional spice on top, this Maybe type transforms into a fully-featured monad. In most languages, the Maybe monad is also known as an option type, which is just a type that marks whether or not it contains a value. Typically they are expressed as some kind of enumerated type. In the Rust programming language it is called Option<T> and variants of this type can either be a value of generic type T, or the empty variant: None.

Option<T> can also be understood as a "wrapping" type, and this is where its connection to monads comes in. In languages with some form of the Maybe type, there are functions that aid in their use such as composing monadic functions with each other and testing if a Maybe contains a value. In the following hard-coded example, a Maybe type is used as a result of functions that may fail, in this case the type returns nothing if there is a divide-by-zero.

One such way to test whether or not a Maybe contains a value is to use if statements.

Other languages may have pattern matchingMonads can compose functions that return Maybe, putting them together. A concrete example might have one function take in several Maybe parameters, and return a single Maybe whose value is Nothing when any of the parameters are Nothing, as in the following:

Instead of repeating Some expressions, we can use something called a bind operator. (also known as "map", "flatmap", or "shove"). This operation takes a monad and a function that returns a monad and runs the function on the inner value of the passed monad, returning the monad from the function.In Haskell, there is an operator bind, or (>>=) that allows for this monadic composition in a more elegant form similar to function composition.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Monad (functional programming)

Start with the simplest possible case. Write down what Monad (functional programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In mathematics, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Monad (functional programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Monad (functional programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Monad (functional programming)

In research
Monad (functional programming) appears in mathematics research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Monad (functional programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Monad (functional programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics 1991 in computing, Functional programming, Programming idioms, so understanding it makes those chapters shorter.
In everyday life
Look for Monad (functional programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Monad (functional programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Monad (functional programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Monad (functional programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Monad (functional programming) in simple terms?

In functional programming, monads are a way to structure computations as a sequence of steps, where each step produces a value, plus some extra information about the computation, such as a potential failure, non-determinism, or side effect. More formally, a monad is a type constructor M equipped wi…

Why does Monad (functional programming) matter?

Because it connects several mathematics ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Monad (functional programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Monad (functional programming).

Tags

  • 1991 in computing
  • Functional programming
  • Programming idioms
  • Software design patterns

Keep exploring