Mercurial > dylan
view categorical/monad.org @ 11:1f112b4f9e8f tip
Fixed what was baroque.
author | Dylan Holmes <ocsenave@gmail.com> |
---|---|
date | Tue, 01 Nov 2011 02:30:49 -0500 |
parents | b4de894a1e2e |
children |
line wrap: on
line source
1 #+TITLE: Monads in CS and Math2 #+BEGIN_HTML3 <h1>4 {{{TITLE}}}5 </h1>6 #+END_HTML8 The purpose of a /monad/ is to introduce a new data type into your9 language and to integrate it with existing types; a monad augments a10 pre-existing data type $A$, creating a new type $B$.12 When describing monads, I will use the following terminology:13 - Values of type $A$ are called *ordinary values*, because they belong14 to the pre-existing data type.15 - Values of type $B$ are called *monadic values*, because they16 belong to the type introduced by the monad.17 - A function $A\rightarrow B$ is called a *monadic function*; such18 functions accept regular values as input and return monadic values.22 A monad consists of23 two components for achieving this purpose:25 - A function that converts ordinary values into monadic values ::26 First, in order to create a new data type, each monad has an27 /upgrade function/ which systematically adds structure to values of28 the existing data type, $A$. Because the upgrade function produces29 enhanced values in a systematic way, the enhanced values constitute30 a sort of new data type, $B$.32 #+begin_quote33 $\text{upgrade}:A\rightarrow B$34 #+end_quote36 - A function that enables monadic functions to accept monadic values :: Second, each monad has a /pipe function/ which is a37 protocol for combining a monadic function and a monadic value to38 produce a monadic value. The pipe function facilitates composition:39 notice that a collection of monadic functions $A\rightarrow B$ is composable only if they have been modified by the40 pipe function to become functions of type $B\rightarrow B$, otherwise their input and output types do not match.41 #+begin_quote42 $\text{pipe}:B\times B^A\rightarrow B$43 #+end_quote45 #+srcname: intro46 #+begin_src clojure :results silent47 (ns categorical.monad)48 (use 'clojure.contrib.monads)49 #+end_src52 * Examples of monads53 ** The nondeterministic monad55 We'll implement nondeterministic programming by defining a monad =amb=56 that transforms ordinary deterministic functions into functions that ``ambiguously'' return zero or more57 values.59 #+srcname: stuff60 #+begin_src clojure :results silent61 (in-ns 'categorical.monad)63 ;; To implement nondeterministic programs, we'll use a lazy seq to represent a value which may be any one of the members of seq.65 (defmonad amb66 [67 m-result (fn[& vals] (cons 'amb vals))68 m-bind (fn[amb-seq f] (cons 'amb (map f (rest amb-seq))))69 ]70 )71 #+end_src73 #+begin_src clojure :results silent :tangle monad.clj :noweb yes74 <<intro>>75 <<stuff>>76 #+end_src