Monads: Difference between revisions
Content added Content deleted
m (→List Monad: verbage) |
(First draft of an alternative introduction - but better, I think, to break out into particular monads) |
||
Line 1: | Line 1: | ||
{{draft task}} |
{{draft task}} |
||
In functional programming, the [[wp:Monad_(functional_programming)|Monad]] pattern is a general solution to the problem of nesting (or 'composing') functions when the data which they apply to is contained in some kind of useful wrapping. It involves implementing two higher-order functions which, between them, can take care of ensuring that the nested (data-transforming) functions are not choked by being called on unexpected types of data. (Wrapped data, when they were expecting something raw and unwrapped). |
|||
Functional programming [[wp:Monad_(functional_programming)|Monads]] are a mechanism for building types which allow unified handling of more than one underlying type. (This use of this term implies and hides [[wp:Multiple_dispatch|multiple dispatch]], however for [[Rosetta_Code:Add_a_Task#Things_to_avoid|Rosetta Code]] we do not require that this be a feature of the language.) |
|||
The two-higher order functions which make up the monad pattern handle the details of: 1. wrapping and unwrapping data, and 2. Providing other functions with direct access to the unwrapped data contents. Delegating the mechanics to these to the two meta-functions allows the programmer to work with a simple and well-understood generic model, and to nest functions transparently. |
|||
The two monad functions are sometimes named as follows: |
|||
# 'Return' which wraps a piece of raw data, returning the wrapped 'monadic' form |
|||
# 'Bind' which applies some other function directly to the contents of a monadic wrapper, obtains a result, and returns a wrapped monadic form of that result. |
|||
Commonly used monads include the Maybe monad, (in which the wrapper encodes whether or not the raw content is a legal value for a particular type of function), and the List monad, in which raw data is simply contained in a list. When lists are used to represent a range of possible values for a variable name, nesting functions which act on these lists allows a convenenient encoding of cartesian products and set comprehensions. In this context, the two higher order monad functions ensure that each data-transforming function gets and returns the right kind of argument (Raw atomic values versus one or more values 'wrapped in' a list). |
|||
(Other frequently used monads are the IO monad and the State monad) |
|||
Demonstrate in your programming language the following: |
Demonstrate in your programming language the following: |
||