You are looking at historical revision 26560 of this page. It may differ significantly from its current revision.

Monads

Monads for Scheme

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.

What's this about lazy evaluation?

Yes, this monad implementation is lazily evaluated.

Functions

(define-monad name unit-function bind-function)

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

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

(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

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)
      'Nothing
      (return <maybe> bar)))

Would be the same as:

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

Would be the same as:

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

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

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

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

Within the (do-using) body a special binding syntax is allowed, which can be understood by this example:

(do-using <maybe>
   (x <- (return <maybe> 1))
   x)
 
;Returns:
(Just 1)

Or, a more complex example:

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

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)))

List

 (define-monad
   <list>
   (lambda (a) (list a))
   (lambda (a f) (concatenate! (map! f a))))

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^)))))

Reader

  (define-monad
    <reader>
    (lambda (a) (lambda (v) a))
    (lambda (a f) (lambda (v) ((f (a v)) v))))

CPS

  (define-monad
    <cps>
    (lambda (a) (lambda (k) (k a)))
    (lambda (a f) (lambda (k) (a (lambda (a^) (let ((b (f a^))) (b k)))))))

Exception

  (define-monad
    <exception>
    (lambda (a) `(success ,a))
    (lambda (a f) (if (eq? (car a) 'success) (f (cadr a)) a)))

Writer

  (define-monad
    <writer>
    (lambda (a) `(,a . ()))
    (lambda (a f)
      (let ((b (f (car a))))
        `(,(car b) . ,(append (cdr a) (cdr b))))))

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

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.