Wolfram Language Paclet Repository

Community-contributed installable additions to the Wolfram Language

Primary Navigation

    • Cloud & Deployment
    • Core Language & Structure
    • Data Manipulation & Analysis
    • Engineering Data & Computation
    • External Interfaces & Connections
    • Financial Data & Computation
    • Geographic Data & Computation
    • Geometry
    • Graphs & Networks
    • Higher Mathematical Computation
    • Images
    • Knowledge Representation & Natural Language
    • Machine Learning
    • Notebook Documents & Presentation
    • Scientific and Medical Data & Computation
    • Social, Cultural & Linguistic Data
    • Strings & Text
    • Symbolic & Numeric Computation
    • System Operation & Setup
    • Time-Related Computation
    • User Interface Construction
    • Visualization & Graphics
    • Random Paclet
    • Alphabetical List
  • Using Paclets
    • Get Started
    • Download Definition Notebook
  • Learn More about Wolfram Language

MonadMakers

Guides

  • Monad making

Tech Notes

  • Monad code generation and extension

Symbols

  • AssociationModule
  • GenerateMonadAccessors
  • GenerateMonadDroper
  • GenerateMonadSetter
  • GenerateMonadTaker
  • GenerateStateMonadCode
  • Grid87
  • TraceMonadBind
  • TraceMonadEchoGrid
  • TraceMonad
  • TraceMonadTakeGrid
  • TraceMonadUnit
  • $TraceMonadFailure
Monad code generation and extension
Introduction
General work-flow of monad code generation utilization
What is a monad?
Software design with monadic programming
The basic Maybe monad
Contextual monad classification (case study)
Extensions with polymorphic behavior
Tracing monad pipelines (case study)
Monad code generation
Summary
Flow control in monads
References
Introduction
This document aims to introduce monadic programming in Mathematica / Wolfram Language (WL) in a concise and code-direct manner. The core of the monad codes discussed is simple, derived from the fundamental principles of Mathematica / WL.
The usefulness of the monadic programming approach manifests in multiple ways. Here are a few we are interested in:
1
.
Easy to construct, read, and modify sequences of commands (pipelines)
2
.
Easy to program polymorphic behaviour
3
.
Easy to program context utilization
Speaking informally,
Monad programming provides an interface that allows interactive, dynamic creation and change of sequentially structured computations with polymorphic and context-aware behavior.
The theoretical background provided in this document is given in the Wikipedia article on Monadic programming, [
Wk1
], and the article
“The essence of functional programming”
by Philip Wadler, [
H3
]. The code in this document is based on the primary monad definition given [Wk1,H3]. (Based on the
“Kleisli triple”
and used in Haskell.)
The general monad structure can be seen as:
4
.
A software design pattern
5
.
A fundamental programming construct (similar to class in object-oriented programming)
6
.
An interface for software types to have implementations of
In this document we treat the monad structure as a
design pattern
, [
Wk3
]. (After reading [H3] point 2 becomes more obvious. A similar in spirit, minimalistic approach to
Object-oriented Design Patterns
is given in [AA1].)
We do not deal with types for monads explicitly, we generate code for monads instead. One reason for this is the “monad design pattern” perspective; another one is that in Mathematica / WL the notion of algebraic data type is not needed -- pattern matching comes from the core “book of replacement rules” principle.
The rest of the document is organized as follows.
1. Fundamental sections​
The section "What is a monad?" gives the necessary definitions. The section "The basic Maybe monad" shows how to program a monad from scratch in Mathematica / WL. The section "Extensions with polymorphic behavior" shows how extensions of the basic monad functions can be made. (These three sections form a complete read on monadic programming, the rest of document can be skipped.)
2. Monadic programming in practice​
The section "Monad code generation" describes packages for generating monad code. The section "Flow control in monads" describes additional, control flow functionalities. The section "General work-flow of monad code generation utilization" gives a general perspective on the use monad code generation. The section "Software design with monadic programming" discusses (small scale) software design with monadic programming.
3. Case study sections​
The case study sections "Contextual monad classification" and "Tracing monad pipelines" hopefully have interesting and engaging examples of monad code generation, extension, and utilization.
What is a monad?

The monad definition

In this document a monad is any set of a symbol
m
and two operators unit and bind that adhere to the monad laws. (See the next sub-section.) The definition is taken from [Wk1] and [H3] and phrased in Mathematica / WL terms in this section. In order to be brief, we deliberately do not consider the equivalent monad definition based on unit, join, and map (also given in [H3].)
Here are operators for a monad associated with a certain symbol M:
1. monad unit function ("return" in Haskell notation) is Unit[x_] := M[x];
2. monad bind function (">>=" in Haskell notation) is a rule like Bind[M[x_], f_] := f[x] with MatchQ[f[x],M[_]] giving True.
Note that:
◼
  • the function Bind unwraps the content of M[_] and gives it to the function f;
  • ◼
  • the functions
    f
    i
    are responsible to return results wrapped with the monad symbol M.
  • Here is an illustration formula showing a monad pipeline:
    M[_]
    ⟹
    Bind[M[_],f_]
    f
    1
    ⟹
    Bind[M[_],f_]
    f
    2
    ⟹
    Bind[M[_],f_]
    f
    3
    ⟹
    Bind[M[_],f_]
    …
    ⟹
    Bind[M[_],f_]
    f
    k
    (1)
    From the definition and formula it should be clear that if for the result of Bind[_M,f[x]] the test MatchQ[f[x],_M] is True then the result is ready to be fed to the next binding operation in monad's pipeline. Also, it is clear that it is easy to program the pipeline functionality with Fold:
    Fold[Bind,M[x],{
    f
    1
    ,
    f
    2
    ,
    f
    3
    }]
    Bind[Bind[Bind[M[x],
    f
    1
    ],
    f
    2
    ],
    f
    3
    ]

    The monad laws

    The monad laws definitions are taken from [
    H1
    ] and [H3].
    In the monad laws given below the symbol “⟹” is for monad’s binding operation and
    (x↦expr)
    is for a function in anonymous form.
    Here is a table with the laws:
    #
    name
    LHS
    RHS
    1
    Left identity
    unit a ⟹ f
    ≡
    f a
    2
    Right identity
    m ⟹ unit
    ≡
    m
    3
    Associativity
    (m ⟹ f) ⟹ g
    ≡
    m ⟹ (x ↦ f x ⟹ g)
    Remark: The monad laws are satisfied for every symbol in Mathematica / WL with List being the unit operation and Apply being the binding operation.
    #
    name
    Input
    Output
    1
    Left identity
    Unit[a]⟹f
    f[a]
    2
    Right identity
    {a}⟹Unit
    {a}
    3
    Associativity LHS
    ({a}⟹({f1[#1]}&))⟹({f2[#1]}&)
    {f2[f1[a]]}
    4
    Associativity RHS
    {a}⟹Function[{x},{f1[x]}⟹({f2[#1]}&)]
    {f2[f1[a]]}

    Expected monadic programming features

    Looking at formula (
    0
    ) -- and having certain programming experiences -- we can expect the following features when using monadic programming.
    ◼
  • Computations that can be expressed with monad pipelines are easy to construct and read.
  • ◼
  • By programming the binding function we can tuck-in a variety of monad behaviours -- this is the so called “programmable semicolon” feature of monads.
  • ◼
  • Monad pipelines can be constructed with
    Fold
    , but with suitable definitions of infix operators like
    DoubleLongRightArrow
    (
    ⟹
    ) we can produce code that resembles the pipeline in formula (
    0
    ).
  • ◼
  • A monad pipeline can have polymorphic behaviour by overloading the signatures of
    f
    i
    (and if we have to, Bind.)
  • These points are clarified below. For more complete discussions see [
    Wk1
    ] or [H3].
    The basic Maybe monad
    It is fairly easy to program the basic monad Maybe discussed in [
    Wk1
    ].
    The goal of the Maybe monad is to provide easy exception handling in a sequence of chained computational steps. If one of the computation steps fails then the whole pipeline returns a designated failure symbol, say
    None
    ; otherwise the result after the last step is wrapped in another designated symbol, say Maybe.
    Here is the special version of the generic pipeline formula (
    0
    ) for the Maybe monad:
    Maybe[_]
    ⟹
    Bind[m_,f_]
    …
    ⟹
    Bind[m_,f_]
    None
    m≡None
    f
    i
    [x]
    m
    is
    Maybe[x_]
    ⟹
    Bind[m_,f_]
    …(2)
    Here is the minimal code to get a functional Maybe monad (for a more detailed exposition of code and explanations see [AA7]):
    MaybeUnitQ[x_]:=MatchQ[x,None]||MatchQ[x,Maybe[___]];
    MaybeUnit[None]:=None;​​MaybeUnit[x_]:=Maybe[x];
    MaybeBind[None,f_]:=None;​​MaybeBind[Maybe[x_],f_]:=Block[{res=f[x]},If[FreeQ[res,None],res,None]];
    MaybeEcho[x_]:=Maybe@Echo[x];​​MaybeEchoFunction[f___][x_]:=Maybe@EchoFunction[f][x];
    MaybeOption[f_][xs_]:=Block[{res=f[xs]},If[FreeQ[res,None],res,Maybe@xs]];
    In order to make the pipeline form of the code we write let us give definitions to a suitable infix operator (like “⟹”) to use MaybeBind:
    DoubleLongRightArrow[x_?MaybeUnitQ,f_]:=MaybeBind[x,f];​​DoubleLongRightArrow[x_,y_,z__]:=DoubleLongRightArrow[DoubleLongRightArrow[x,y],z];
    Here is an example of a Maybe monad pipeline using the definitions so far:
    data={0.61,0.48,0.92,0.90,0.32,0.11};
    code="MaybeUnit[data]⟹(* lift data into the monad *) (Maybe@Join[#,RandomInteger[8,3]]&)⟹(* add more values *) MaybeEcho⟹(* display current value *) (Maybe@Map[If[#<0.4,None,#]&,#]&)(* map values that are too small to None *)";​​GridOfCodeAndComments[code,​​"GridFunction"Automatic​​]​​ToExpression[code]​​AutoCollapse[]
    The result is None because:
    1. the data has a number that is too small, and
    2. the definition of MaybeBind stops the pipeline aggressively using a FreeQ[_,None] test.

    Monad laws verification

    Let us convince ourselves that the current definition of MaybeBind gives a monad.
    The verification is straightforward to program and shows that the implemented Maybe monad adheres to the monad laws.
    #
    name
    Input
    Output
    1
    Left identity
    MaybeUnit[a]⟹f
    f[a]
    2
    Right identity
    Maybe[a]⟹MaybeUnit
    Maybe[a]
    3
    Associativity LHS
    (Maybe[a]⟹(Maybe[f1[#1]]&))⟹(Maybe[f2[#1]]&)
    Maybe[f2[f1[a]]]
    4
    Associativity RHS
    Maybe[a]⟹Function[{x},Maybe[f1[x]]⟹(Maybe[f2[#1]]&)]
    Maybe[f2[f1[a]]]
    Extensions with polymorphic behavior
    We can see from formulas (1) and (2) that the monad codes can be easily extended through overloading the pipeline functions.
    For example the extension of the Maybe monad to handle of Dataset objects is fairly easy and straightforward.
    Here is the formula of the Maybe monad pipeline extended with Dataset objects:
    Here is an example of a polymorphic function definition for the Maybe monad:
    See [AA7] for more detailed examples of polymorphism in monadic programming with Mathematica / WL.
    A complete discussion can be found in [H3]. (The main message of [H3] is the poly-functional and polymorphic properties of monad implementations.)

    Polymorphic monads in R’s dplyr

    Here is a diagram of a typical work-flow with dplyr:
    The diagram shows how a pipeline made with dplyr can be re-run (or reused) for data stored in different data structures.
    Monad code generation
    In this section are given examples with packages that generate monad codes. The case study sections have examples of packages that utilize generated monad codes.

    Maybe monads code generation

    Here is an example:
    We see that we get the same result as above (None) and a message prompting failure.

    State monads code generation

    This generates the State monad for the prefix “StMon”:
    The following StMon pipeline code starts with a random matrix and then replaces numbers in the current pipeline value according to a threshold parameter kept in the context. Several times are invoked functions for context deposit and retrieval.
    Flow control in monads
    We can implement dedicated functions for governing the pipeline flow in a monad.
    Let us look at a breakdown of these kind of functions using the State monad StMon generated above.

    Optional acceptance of a function result

    Here is an example with StMonOption :
    Without StMonOption we get failure:

    Conditional execution of functions

    It is natural to want to have the ability to chose a pipeline function application based on a condition.
    This can be done with the functions StMonIfElse and StMonWhen.
    Remark: Using flow control functions like StMonIfElse and StMonWhen with appropriate messages is a better way of handling computations that might fail. The silent failures handling of the basic Maybe monad is convenient only in a small number of use cases.

    Iterative functions

    The last group of pipeline flow control functions we consider comprises iterative functions that provide the functionalities of Nest, NestWhile, FoldList, etc.
    Here is a basic example using Nest that corresponds to Nest[#+1&,1,3]:
    Consider this command that uses the full signature of NestWhileList:
    Here is the corresponding StMon iteration code:
    Here is another results accumulation example with FixedPointList :
    When the functions NestList, NestWhileList, FixedPointList are used with StMonIterate their results can be stored in the context. Here is an example:

    Partial pipelines

    Because of the associativity law we can design pipeline flows based on functions made of “sub-pipelines.“
    General work-flow of monad code generation utilization
    With the abilities to generate and utilize monad codes it is natural to consider the following work flow. (Also shown in the diagram below.)
    7
    .
    Come up with an idea that can be expressed with monadic programming.
    8
    .
    Look for suitable monad implementation.
    9
    .
    If there is no such implementation, make one (or two, or five.)
    10
    .
    Having a suitable monad implementation, generate the monad code.
    11
    .
    Implement additional pipeline functions addressing envisioned use cases.
    12
    .
    Start making pipelines for the problem domain of interest.
    13
    .
    Are the pipelines are satisfactory? If not go to 5. (Or 2.)

    Monad templates

    They are in five groups:
    1. base monad functions (unit testing, binding),
    2. display of the value and context,
    3. context manipulation (deposit, retrieval, modification),
    4. flow governing (optional new value, conditional function application, iteration),
    5. other convenience functions.
    We can say that all monad implementations will have their own versions of these groups of functions. The more specialized monads will have functions specific to their intended use. Such special monads are discussed in the case study sections.
    Software design with monadic programming
    The application of monadic programming to a particular problem domain is very similar to designing a software framework or designing and implementing a Domain Specific Language (DSL).
    The answers of the question “When to use monadic programming?” can form a large list. This section provides only a couple of general, personal viewpoints on monadic programming in software design and architecture. The principles of monadic programming can be used to build systems from scratch (like Haskell and Scala.) Here we discuss making specialized software with or within already existing systems.

    Framework design

    Software framework design is about architectural solutions that capture the commonality and variability in a problem domain in such a way that:
    1) significant speed-up can be achieved when making new applications, and
    2) a set of policies can be imposed on the new applications.
    The rigidness of the framework provides and supports its flexibility -- the framework has a backbone of rigid parts and a set of “hot spots” where new functionalities are plugged-in.
    Usually Object-Oriented Programming (OOP) frameworks provide inversion of control -- the general work-flow is already established, only parts of it are changed. (This is characterized with “leave the driving to us” and “don’t call us we will call you.”)
    The point of utilizing monadic programming is to be able to easily create different new work-flows that share certain features. (The end user is the driver, on certain rail paths.)
    In my opinion making a software framework of small to moderate size with monadic programming principles would produce a library of functions each with polymorphic behaviour that can be easily sequenced in monadic pipelines. This can be contrasted with OOP framework design in which we are more likely to end up with backbone structures that (i) are static and tree-like, and (ii) are extended or specialized by plugging-in relevant objects. (Those plugged-in objects themselves can be trees, but hopefully short ones.)

    DSL development

    Given a problem domain the general monad structure can be used to shape and guide the development of DSLs for that problem domain.
    Generally, in order to make a DSL we have to choose the language syntax and grammar. Using monadic programming the syntax and grammar commands are clear. (The monad pipelines are the commands.) What is left is “just” the choice of particular functions and their implementations.
    Another way to develop such a DSL is through a grammar of natural language commands. Generally speaking, just designing the grammar -- without developing the corresponding interpreters -- would be very helpful in figuring out the components at play. Monadic programming meshes very well with this approach and applying the two approaches together can be very fruitful.
    Contextual monad classification (case study)
    In this section we show an extension of the State monad into a monad aimed at machine learning classification work-flows.

    Motivation

    We want to provide a DSL for doing machine learning classification tasks that allows us:
    1) to do basic summarization and visualization of the data,
    1) to control splitting of the data into training and testing sets;
    2) to apply the built-in classifiers;
    4) to evaluate classifier performances with standard measures and
    5) ROC plots.
    Also, we want the DSL design to provide clear directions how to add (hook-up or plug-in) new functionalities.

    Package and data loading

    This gets some test data (the Titanic dataset):

    Monad design

    The classifier contexts are Association objects. The pipeline values can have the form:
    The ClCon specific monad functions deposit or retrieve values from the context with the keys: "trainData", "testData", "classifier". The general idea is that if the current value of the pipeline cannot provide all arguments for a ClCon function, then the needed arguments are taken from the context. If that fails, then an message is issued.
    This is illustrated with the following pipeline with comments example.
    The pipeline and results above demonstrate polymorphic behaviour over the classifier variable in the context: different functions are used if that variable is a ClassifierFunction object or an association of named ClassifierFunction objects.

    Another usage example

    This monadic pipeline in this example goes through several stages: data summary, classifier training, evaluation, acceptance test, and if the results are rejected a new classifier is made with a different algorithm using the same data splitting. The context keeps track of the data and its splitting. That allows the conditional classifier switch to be concisely specified.
    First let us define a function that takes a Classify method as an argument and makes a classifier and calculates performance measures.
    Using the sub-pipeline function ClSubPipe we make the outlined pipeline.
    Tracing monad pipelines (case study)
    The primary reason for developing the package was the desire to have the ability to print a tabulated trace of code and comments using the usual monad pipeline notation. (I.e. without conversion to strings etc.)

    Package loading

    Usage example

    This generates a Maybe monad to be used in the example (for the prefix “Perhaps”):
    In following example we can see that pipeline functions of the Perhaps monad are interleaved with comment strings.
    Producing the grid of functions and comments happens “naturally” with the monad function TraceMonadEchoGrid.
    Note that :
    1. the tracing is initiated by just using TraceMonadUnit;
    2. pipeline functions (actual code) and comments are interleaved;
    3. putting a comment string after a pipeline function is optional.
    Another example is the ClCon pipeline in the sub-section “Monad design” in the previous section.
    Summary
    This document presents a style of using monadic programming in Wolfram Language (Mathematica). The style has some shortcomings, but it definitely provides convenient features for day-to-day programming and in coming up with architectural designs.
    The style is based on WL’s basic language features. As a consequence it is fairly concise and produces light overhead.
    Ideally, the packages for the code generation of the basic Maybe and State monads would serve as starting points for other more general or more specialized monadic programs.
    References

    Monadic programming

    R

    Mathematica / Wolfram Language

    MathematicaForPrediction

    © 2025 Wolfram. All rights reserved.

    • Legal & Privacy Policy
    • Contact Us
    • WolframAlpha.com
    • WolframCloud.com