Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Monad (functional programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Techniques == Monads present opportunities for interesting techniques beyond just organizing program logic. Monads can lay the groundwork for useful syntactic features while their high-level and mathematical nature enable significant abstraction. === Syntactic sugar {{visible anchor|do-notation}} === Although using {{mvar|bind}} openly often makes sense, many programmers prefer a syntax that mimics imperative statements (called ''do-notation'' in Haskell, ''perform-notation'' in [[OCaml]], ''computation expressions'' in [[F Sharp (programming language)|F#]],<ref name="F#Expressions">{{cite web | url = https://blogs.msdn.microsoft.com/dsyme/2007/09/21/some-details-on-f-computation-expressions/ | title = Some Details on F# Computation Expressions | date = 21 September 2007 | access-date = 9 October 2018}}</ref> and ''for comprehension'' in [[Scala (programming language)|Scala]]). This is only [[syntactic sugar]] that disguises a monadic pipeline as a [[code block]]; the compiler will then quietly translate these expressions into underlying functional code. Translating the <code>add</code> function from the <code>Maybe</code> into Haskell can show this feature in action. A non-monadic version of <code>add</code> in Haskell looks like this: <syntaxhighlight lang="haskell"> add mx my = case mx of Nothing -> Nothing Just x -> case my of Nothing -> Nothing Just y -> Just (x + y) </syntaxhighlight> In monadic Haskell, <code>return</code> is the standard name for {{mvar|unit}}, plus lambda expressions must be handled explicitly, but even with these technicalities, the <code>Maybe</code> monad makes for a cleaner definition: <syntaxhighlight lang="haskell"> add mx my = mx >>= (\x -> my >>= (\y -> return (x + y))) </syntaxhighlight> With do-notation though, this can be distilled even further into a very intuitive sequence: <syntaxhighlight lang="haskell"> add mx my = do x <- mx y <- my return (x + y) </syntaxhighlight> A second example shows how <code>Maybe</code> can be used in an entirely different language: F#. With computation expressions, a "safe division" function that returns <code>None</code> for an undefined operand ''or'' division by zero can be written as: <syntaxhighlight lang="ocaml"> let readNum () = let s = Console.ReadLine() let succ,v = Int32.TryParse(s) if (succ) then Some(v) else None let secure_div = maybe { let! x = readNum() let! y = readNum() if (y = 0) then None else return (x / y) } </syntaxhighlight> At build-time, the compiler will internally "de-sugar" this function into a denser chain of {{mvar|bind}} calls: <syntaxhighlight lang="ocaml"> maybe.Delay(fun () -> maybe.Bind(readNum(), fun x -> maybe.Bind(readNum(), fun y -> if (y=0) then None else maybe.Return(x / y)))) </syntaxhighlight> For a last example, even the general monad laws themselves can be expressed in do-notation: <syntaxhighlight lang="haskell"> do { x <- return v; f x } == do { f v } do { x <- m; return x } == do { m } do { y <- do { x <- m; f x }; g y } == do { x <- m; y <- f x; g y } </syntaxhighlight> === General interface === Every monad needs a specific implementation that meets the monad laws, but other aspects like the relation to other structures or standard idioms within a language are shared by all monads. As a result, a language or library may provide a general <code>Monad</code> interface with [[function prototype]]s, subtyping relationships, and other general facts. Besides providing a head-start to development and guaranteeing a new monad inherits features from a supertype (such as functors), checking a monad's design against the interface adds another layer of quality control.{{citation needed|reason=Not sure of a good general source, but both Gentle Intro to Haskell and Real World Haskell discuss type classes|date=November 2018}} === Operators <span id="Lift"></span><span id="Compose"></span> === Monadic code can often be simplified even further through the judicious use of operators. The {{mvar|map}} functional can be especially helpful since it works on more than just ad-hoc monadic functions; so long as a monadic function should work analogously to a predefined operator, {{mvar|map}} can be used to instantly "[[lift (mathematics)|lift]]" the simpler operator into a monadic one.{{efn|Some languages like Haskell even provide a pseudonym for {{mvar|map}} in other contexts called <code>lift</code>, along with multiple versions for different parameter counts, a detail ignored here.}} With this technique, the definition of <code>add</code> from the <code>Maybe</code> example could be distilled into: add(mx,my) = map (+) The process could be taken even one step further by defining <code>add</code> not just for <code>Maybe</code>, but for the whole <code>Monad</code> interface. By doing this, any new monad that matches the structure interface and implements its own {{mvar|map}} will immediately inherit a lifted version of <code>add</code> too. The only change to the function needed is generalizing the type signature: add : (Monad Number, Monad Number) β Monad Number<ref name="Lifting">{{cite web | last = Giles | first = Brett | title = Lifting | url = https://wiki.haskell.org/Lifting | date = 12 August 2013 | website = HaskellWiki | publisher = Haskell.org | archive-url = https://web.archive.org/web/20180129230953/https://wiki.haskell.org/Lifting | archive-date = 29 January 2018 | url-status = live | access-date = 25 November 2018}}</ref> Another monadic operator that is also useful for analysis is monadic composition (represented as infix <code>>=></code> here), which allows chaining monadic functions in a more mathematical style: (f >=> g)(x) = f(x) >>= g With this operator, the monad laws can be written in terms of functions alone, highlighting the correspondence to associativity and existence of an identity: (unit >=> g) β g (f >=> unit) β f (f >=> g) >=> h β f >=> (g >=> h)<ref name="RealWorldHaskell" /> In turn, the above shows the meaning of the "do" block in Haskell: do _p <- f(x) _q <- g(_p) h(_q) β ( f >=> g >=> h )(x)
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)