CE theoretical basements
CE: the Swiss army knife â¨
The computation expressions serve different purposes:
CâŻ
yield return
â FâŻseq {}
CâŻ
async/await
â FâŻasync {}
C⯠LINQ expressions
from... select
â FâŻquery {}
...
Underlying theoretical foundations :
Monoid
Monad
Applicative
Monoid
â Type T
defining a set with:
Operation
(+): T -> T -> T
To combine sets and keep the same "type"
Associative:
a + (b + c)
âĄ(a + b) + c
Neutral element (aka identity) â empty set
Combinable with any set without effect
a + e
âĄe + a
âĄa
CE monoidal
The builder of a monoidal CE (such as seq
) has at least :
Yield
to build the set element by elementCombine
âĄ(+)
(Seq.append
)Zero
⥠neutral element (
Seq.empty`)
Generally added (among others):
For
to supportfor x in xs do ...
YieldFrom
to supportyield!
Monad
â Generic type M<'T>
with:
return
construction functionSignature :
(value: 'T) -> M<'T>
â Wrap a value
Link function
bind
(aka>>=
operator)Signature :
(f: 'T -> M<'U>) -> M<'T> -> M<'U>
Use wrapped value, map with
f
function to a value of another type and re-wrap the result
Monad laws
return
⥠neutral element for bind
Left:
return x |> bind f
âĄf x
Right:
m |> bind return
âĄm
bind
is associative
m |> bind f |> bind g
âĄm |> bind (fun x -> f x |> bind g)
Monads and languages
Haskell
Monads used a lot. Common ones:
IO
,Maybe
,State
,Reader
.Monad
is a type class for easily creating your own monads.
FâŻ
Some CEs allow monadic operations.
More rarely used directly (except by Haskellers, OCamlers...)
CâŻ
Monad implicit in LINQ
Monadic CE
The builder of a monadic CE has Return
and Bind
methods.
The Option
and Result
types are monadic.
â We can create their own CE :
Monadic and generic CE
Example with Option
type:
Option
type:Limits
â ď¸ Several monadic types cannot be mixed!
Specific monadic CE
â Recommended as it is more explicit than monad
CE.
Applicative (a.k.a Applicative Functor)
â Generic type M<'T>
-- 3 styles:
Style B: Applications with mapN
⢠map2
, map3
... map5
combines 2 to 5 wrapped values
â Tip: Styles B and C are equally recommended.
Applicative CE
Type
Validation<'Ok, 'Err>
âĄResult<'Ok, 'Err list>
CE
validation {}
supportinglet!...and!...
syntax.
Allows errors to be accumulated â Uses:
Parsing external inputs
Smart constructor (Example code slide next...)
Example:
Applicative vs Monad
The Result
type is "monadic": on the 1st error, we "unplug".
There is another type called Validation
that is "applicative": it allows to accumulate errors.
â
Result<'ok, 'error list>
\Handy for validating user input and reporting all errors
Example: Validation.map2
to combine 2 results and get the list of their eventual errors.
đ Ressources
Other CE
We've seen 2 libraries that extend F⯠and offer their CEs:
FSharpPlus â
monad
FsToolkit.ErrorHandling â
option
,result
,validation
Many libraries have their own DSL (Domain Specific Language.) Some are based on CE:
Last updated
Was this helpful?