From 0660fe3b1de9f651b5b278c952c9aaabbe8325f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20=C4=8C=C3=AD=C5=BE?= Date: Fri, 19 Nov 2021 19:57:37 +0100 Subject: [PATCH] Update --- monad.md | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/monad.md b/monad.md index e8714b5..a30b9ca 100644 --- a/monad.md +++ b/monad.md @@ -12,7 +12,37 @@ A typical example is a **maybe** monad which wraps a type such as integer to han 2. A special function *return(X)* that converts value of given type into this maybe type, e.g. *return(3)* will return *just(3)* 3. A special combinator *X >>= f* which takes a monadic (*maybe*) values *X* and a function *f* and does the following: - if *X* is *nothing*, gives back *nothing* - - if *X* is a value *just(N)*, gives back the value *f(N)* + - if *X* is a value *just(N)*, gives back the value *f(N)* (i.e. unwraps the value and hand it over to the function) +Let's look at a pseudocode example of writing a safe division function. Without using the combinator it's kind of ugly: -TODO: example in some lang, e.g. haskell +``` +divSafe(x,y) = // takes two maybe values, returns a maybe value + if x == nothing + nothing else + if y == nothing + nothing else + if y == 0 + nothing else + just(x / y) +``` + +With the combinator it gets much nicer (note the use of [lambda expression](lambda.md)): + +``` +divSafe(x,y) = + x >>= { a: y >== { b: if b == 0 nothing else a / b } } +``` + +Languages will typicall make this even nicer with a [syntax sugar](syntax_sugar.md) such as: + +``` +divSafe(x,y) = do + a <- x, + b <- y, + if y == 0 nothing else return(a / b) +``` + +TODO: I/O monad +TODO: general monad +TODO: example in real lang, e.g. haskell