Monads

Monads for Scheme

  1. Monads
  2. Description
    1. What is a Monad?
    2. Why not use miscmacros:doto instead?
    3. Functions
      1. (define-monad name unit-function bind-function [fail-function])
      2. (using monad [body ...])
      3. (return monad value)
      4. (fail monad [body ...])
      5. (do-using monad [body ...])
        1. /m! Keyword
        2. /m Keyword
        3. <- Keyword
        4. General Example
      6. (do monad [body ...])
    4. Basic Monads
      1. Identity
      2. Maybe
        1. Example
      3. List
        1. Example
      4. State
        1. Extra Methods
          1. <state>-get
            1. Example
          2. <state>-gets
            1. Example
          3. <state>-modify
            1. Example
          4. <state>-put
            1. Example
      5. Reader
        1. Extra Methods
          1. <reader>-ask
            1. Example
          2. <reader>-asks
            1. Example
          3. <reader>-local
            1. Example
      6. CPS
        1. Extra Methods
          1. <cps>-call/cc
      7. Exception
        1. Extra Methods
          1. <exception>-throw
            1. Example
          2. <exception>-catch
            1. Example
      8. Writer
        1. Extra Methods
          1. <writer>-tell
            1. Example
          2. <writer>-listen
            1. Example
          3. <writer>-listens
            1. Example
          4. <writer>-pass
            1. Example
          5. <writer>-censor
            1. Example
    5. Contribution
    6. Authors
    7. Version History
    8. License

Description

What is a Monad?

Monads are like a burrito.

Ok, well not.

Monads are types that have:

1. A binding function of the form: a -> (a -> M b) -> M b

2. A unit function: a -> M a

That's it.

For instance, the identity monad is:

1. Bind: (lambda (a f) (f a))

2. Unit: (lambda (a) a)

Not too bad, eh?

Most of what we write that can be described as a "recipe list" or a "do to" list is a Monad. And, as you may have noticed, we write a lot of boiler plate code to handle the interim wrapping/unwrapping/error checking functionality that occurs between each step.

The Monad egg allows you to write that code once and remain focused on the task at hand.

Why not use miscmacros:doto instead?

Because you may want intermediary control and multiple usage of a unit function.

Monads aren't simply about iterating over a value or set of values and passing them to various functions; they're about removing recurring boilerplate related to constructing the desired values, and any intermediary steps that may be required between processing the values.

Yes, sometimes this isn't strictly a necessary set of functionality. But for when it is, save yourself some time and write a monad.

Functions

(define-monad name unit-function bind-function [fail-function])

[procedure] (define-monad name unit-function bind-function [fail-function])

Providing ‘fail-function’ is optional.

Defines a new monad of the given name. Also defines the following procedures:

Function Usage
name-unit Constructs a new monad from a value using the given unit function
name-bind Constructs a new monad from an existing monad and a function using the given bind function
name-fail Constructs a ‘failure’ case monad for the given monadic type. Defaults to throwing an assert

(using monad [body ...])

[procedure] (using monad [body ...])

Within the body the following procedures will be defined:

Function Usage
>>= Maps to bind
return Maps to unit
fail Maps to fail

Ie:

(using <id>
(>>= (return 1) (lambda (x) (+ x 1))))

Is the same as:

(<id>-bind (<id>-unit 1) (lambda  (x) (+ x 1)))

(return monad value)

[procedure] (return monad value)

Allows any function to lift a value into the monad provided. Ie,

(define (foo bar)
  (if (not bar)
      (fail <maybe>)
      (return <maybe> bar)))

Would be the same as:

(define (foo bar)
  (if (not bar)
      (<maybe>-fail)
      (<maybe>-unit bar)))

Would be the same as:

(define (foo bar)
  (if (not bar)
      'Nothing
      `(Just ,bar)))

(fail monad [body ...])

[procedure] (fail monad [body ...])

Creates the failure case for the given monad, optionally providing a body to the failure state constructor.

Defaults to throwing an assert for most monads.

(do-using monad [body ...])

[procedure] (do-using monad [body ...])

Similar to the (using) procedure, but allows for even more terseness.

Within do-using the following will be defined:

Function Usage
>>= Maps to bind
return Maps to unit
fail Maps to fail
/m Shorthand for calling monad-specific functions, details follow
/m! Shorthand for calling monad-specific functions, details follow
<- Shorthand for binding a symbol to a monadic value, details follow
/m! Keyword

The /m! keyword is used as a shortcut for referencing monad-specific procedures which are prefixed with the current monad name.

For example:

(do-using <writer> (/m! tell 1))

Is the same as:

(do-using <writer> (<writer>-tell 1))
/m Keyword

The /m keyword is like /m!, except that it references the procedure without executing it.

For example:

(do-using <state> (x <- (/m get)) (return x))

Is the same as:

(do-using <writer> (x <- <state>-get) (return x))
<- Keyword

The <- keyword is used as a shortcut for binding a value within a monad.

For example:

(do-using <maybe>
  (x <- (return 1))
  x)

Is the same as:

(do-using <maybe>
  (>>= (return 1)
    (lambda (x)
      (do-using <maybe>
        x))))
General Example

A simple example:

(do-using <maybe>
   (x <- (return <maybe> 1))
   x)

;Returns:
(Just 1)

Or, a more complex example:

(do-using <maybe> 
          (x <- (return 1))
          (if (eq? 2 (cadr x))
              (return 'Banana)
              (fail))
          (y <- (return 'Apple))
          y)

;Returns:
Nothing

(do monad [body ...])

[procedure] (do monad [body ...])

Alias for (do-using monad [body ...]).

Basic Monads

Simple monads pre-defined by this egg.

Identity

(define-monad
  <id>
  (lambda (a) a)
  (lambda (a f) (f a)))

Maybe

(define-monad
  <maybe>
  (lambda (a) a)
  (lambda (a f) (if a (f a) #f))
  (case-lambda (() 'Nothing)
               ((_ . _) 'Nothing)))
Example
> (do <maybe> 
      (if #t 
          'Nothing 
          '(Just First))
      '(Just Second))
Nothing

List

(define-monad
  <list>
  (lambda (a) (list a))
  (lambda (a f) (concatenate! (map! f a))))
Example
#;> (do <list> 
        (x <- '(1 2 3))
        (y <- '(a b c))
        (return `(,x ,y)))
((1 a) (1 b) (1 c) (2 a) (2 b) (2 c) (3 a) (3 b) (3 c))

State

(define-monad
  <state>
  (lambda (a) (lambda (s) `(,a . ,s)))
  (lambda (a f)
    (lambda (s)
      (let* ((p (a s))
             (a^ (car p))
             (s^ (cdr p)))
        ((f a^) s^)))))
Extra Methods
<state>-get
[procedure] (<state>-get s)

Retrieves the current state from a given <state> monad.

Example
#;> ((do <state> 
         (x <- (/m get))
         (return x))
     "Hi!")
("Hi!" . "Hi!")
<state>-gets
[procedure] (<state>-gets f)

Creates a monad that retrieves a given state after filtering it with the function provided.

Example
#;> ((do <state> 
         (x <- (/m! gets (lambda (s) (+ s 1))))
         (return x))
     1)
(2 . 1)
<state>-modify
[procedure] (<state>-modify f)

Creates a monad that modifies the current state with a given function.

Example
#;> ((do <state> 
         (/m! modify (lambda (v) 
                      (display (format "Received: ~S\n" v))
                      (+ v 1))))
     1)
Received: 1
(() . 2)
<state>-put
[procedure] (<state>-put v)

Creates a monad that forces a value into the current <state> monad.

Example
#;> ((do <state> 
         (/m! put 1))
     2)
(() . 1)

Reader

(define-monad
  <reader>
  (lambda (a) (lambda (v) a))
  (lambda (a f) (lambda (v) ((f (a v)) v))))
Extra Methods
<reader>-ask
[procedure] (<reader>-ask m)

Extracts the current value from the current reader monad.

Example
#;> ((do <reader> 
         (x <- (/m ask))
         (return (+ x 1)))
     1)
2
<reader>-asks
[procedure] (<reader>-asks f)

Creates a monad that filters the current value in the reader monad with the given function.

Example
#;> ((do <reader> 
         (/m! asks (lambda (v) 
                    (+ v 1))))
     1)
2
<reader>-local
[procedure] (<reader>-local f m)

Creats a monad that first filters the current reader monad value with the provided function, then passes that filtered value to the provided reader monad.

Example
#;> ((do <reader> 
         (/m! local 
             (lambda (v) (+ v 1))
             (do <reader> 
                 (x <- (/m ask))
                 (return x))))
     1)
2

CPS

(define-monad
  <cps>
  (lambda (a) (lambda (k) (k a)))
  (lambda (a f) (lambda (k) (a (lambda (a^) (let ((b (f a^))) (b k)))))))
Extra Methods
<cps>-call/cc

<procedure>(<cps>-call/cc f)</procedre>

Creates a monad that, when given a continuation, passes a monad to the provided function that applies the continuation to its input; then applies the continuation to the output of that function.

Exception

(define-monad
  <exception>
  (lambda (a) `(success ,a))
  (lambda (a f) (if (eq? (car a) 'success) (f (cadr a)) a))
  (case-lambda (() `(failure))
               ((a . b) `(failure ,a . ,b))))
Extra Methods
<exception>-throw
[procedure] (<exception-throw e)

Synonym for <exception>-fail.

Example
#;> (do <exception> (/m! throw "Error! No more cheerios!"))
(failure "Error! No more cheerios!")
<exception>-catch
[procedure] (<exception>-catch m f)

Creates a monad that examines an exception monad and passes the value to the provided function if it had failed.

Example
#;> (define some-monad 
            (do <exception> 
                (/m! throw "An error happened! Oh no!")))
#;> (do <exception> 
        (/m! catch some-monad 
                  (lambda (m) 
                    (display (format "Caught an exception: ~S" 
                                     (cadr m))))))
Caught an exception: "An error happened! Oh no!"

Writer

(define-monad
  <writer>
  (lambda (a) `(,a . ()))
  (lambda (a f)
    (let ((b (f (car a))))
      `(,(car b) . ,(append (cdr a) (cdr b))))))
Extra Methods
<writer>-tell
[procedure] (<writer>-tell v)

Creates a monad where the provided value is wrapped in a <writer>.

Example
#;> (do <writer> (/m! tell '(1 2 3)))
(() 1 2 3)
<writer>-listen
[procedure] (<writer>-listen a)

Creates a monad where the value has been extracted out of the writer.

Example
#;> (do <writer> 
        (x <- (/m! listen 
                  (/m! tell '(foo))))
        (return x))
((() foo) foo)
<writer>-listens
[procedure] (<writer>-listens f m)

Creates a monad that is the outcome of applying the provided function on the given writer monad.

Example
#;> (do <writer> 
        (x <- (return (/m! tell '(1 2 3))))
        (/m! listens 
            (lambda (l) (map (lambda (v) (+ v 1)) l))
            (return x)))
((() 2 3 4))
<writer>-pass
[procedure] (<writer>-pass m)

Creates a monad that is the outcome of mutating the provided writer monad with a given function. Expects to be provided a monad of the form: ((value . function) . rest-of-writer)

Not generally used much except by those that know what they're doing, you're likely after <writer>-censor for most cases.

Example
#;> (do <writer> 
        (x <- (/m! listen 
                  `((() . ,(lambda (l) 
                             (map (lambda (v) (+ v 1)) l)))
                    . (1 2 3))))
        (/m! pass x))
(() 1 2 3 2 3 4)
<writer>-censor
[procedure] (<writer>-censor f m)

Creates a monad resulting from the application of the provided function on the given monad, censoring the values that were in the given monad.

Example
#;> (do <writer> 
        (/m! censor (lambda (l) (map (lambda (v) (+ v 1)) l))
                   (/m! tell '(1 2 3))))
(() 2 3 4)

Contribution

Contributions are welcome provided you accept the license I have chosen for this egg for the contributions themselves.

The github repository is at: https://github.com/dleslie/monad-egg

Authors

Original Egg by Daniel J. Leslie dan@ironoxide.ca

State, Reader, Writer, CPS and Exception monads contributed by Cameron Swords.

Version History

3.0
Renamed :! to /m! and : to /m due to : already being used for explicit specialization (oops)
2.4
Added :! keyword, fixed : keyword
2.3
Added fail function for all monads which defaults to assert, but is definied appropriately for the &lt;exception&gt; and &lt;maybe&gt; monads. Added : keyword to using and do-using. Added &gt;&gt;=, return and fail bindings to do-using syntax.
2.2
Added failure states for monads
2.1
Rewrote API to allow for terser execution and a simpler interface. Removed use of promises completely. Removed doto-using, run-chain, and run from the API completely. Added do-using syntax. Maybe monad is now self-defined for it's value or no-value states.
2.0
Internal rewrite that broke the API, immediately followed by 2.1.
1.1
Added Cameron Swords' State, Reader, Writer, CPS and Exception monads
1.0
Initial release

License

 Copyright 2012 Daniel J. Leslie. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
 
    1. Redistributions of source code must retain the above copyright notice, this list of
       conditions and the following disclaimer.
 
    2. Redistributions in binary form must reproduce the above copyright notice, this list
       of conditions and the following disclaimer in the documentation and/or other materials
       provided with the distribution.
 
 THIS SOFTWARE IS PROVIDED BY DANIEL J. LESLIE ''AS IS'' AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DANIEL J. LESLIE OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 The views and conclusions contained in the software and documentation are those of the
 authors and should not be interpreted as representing official policies, either expressed
 or implied, of Daniel J. Leslie.