Monads without talking about Monads

Functions

mul3 x = 3 * x add2 x = 2 + xdiv ( x, y ) = x / y

Composition

result ( x, y ) = add2 (mul3 (div ( x, y )))
result ( x, y ) =
( x, y )
|> div
|> mul3
|> add2

Failures

div: ( Float, Float ) -> Float
type Maybe a = Just a | Nothing
Just : a -> Maybe aNothing : Maybe a
divM ( x, y ) =
if y == 0 then
Nothing
else
Just <| x / y

Composition II

result ( x, y ) =
( x, y )
|> divM
|> mul3
|> add2
This `divM` call produces:    Maybe FloatBut `mul3` needs the 1st argument to be:    Float
mul3MM maybe =
case maybe of
Just x ->
Just <| 3 * x
Nothing ->
Nothing
add2MM maybe =
case maybe of
Just x ->
Just <| 2 + x
Nothing ->
Nothing
result ( x, y ) =
( x, y )
|> divM
|> mul3MM
|> add2MM

Binding

andThen callback maybe =
case maybe of
Just value ->
callback value
Nothing ->
Nothing
mul3M x = Just <| 3 * xadd2M x = Just <| 2 + x
mul3MM = andThen mul3Madd2MM = andThen mul3M
result ( x, y ) =
( x, y )
|> divM
|> andThen mul3M
|> andThen add2M
# Haskell(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
(>>=) maybe callback =
case maybe of
Just value ->
callback value
Nothing ->
Nothing
# ElmandThen : (a -> Maybe b) -> Maybe a -> Maybe b
andThen callback maybe =
case maybe of
Just value ->
callback value

Nothing ->
Nothing
type Result error value = Ok value | Err error

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Script Flakiness (Reasons & Resolution)

Configure FreeRADIUS to use MySql on Linux.

ITILv4 Foundation — Complete Course

A Guide to Using ScreenSize In Flutter — A More Readable Approach

Simple roles and permissions package for Laravel

Deep Dive into Delta Lake via Apache Zeppelin

Want to help us test the network ahead of the launch?

What does it take to become an iOS Developer? 👩‍💻📲

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lucamug

Lucamug

Bio

More from Medium

Using Elm pipelines with andThen to decode a multi-object type

Using TypeScript to write compile-time-safe enumeration type handlers

Two people wearing safety helmets

Pnpm and Nx monorepo. Part 1

The Power of Pissing Code, and its Place in Answering the Age-Old Question: “TypeScript, or…