際際滷

際際滷Share a Scribd company logo
Monads
Functional Programming
First-class and higher-order functions
let double: (Int) -> Int = { $0 * 2 }
func apply(value: Int, function: (Int) -> Int) -> Int {
return function(value)
}
let result = apply(value: 4, function: double)
// result == 8
Some properties
 A function is said to be pure if it produces no side-effects and its
return value only depends on its arguments
 An expression is said to be referentially transparent if it can be
replaced by its value without altering the programs behavior
Optionals
Some very familiar code
var data: [String]?
// ...
let result = data?.first?.uppercased()
Some very familiar code
var data: [String]?
// ...
let result = data?.first?.uppercased()
The operator ?. allows us to declare a work鍖ow that will be executed
in order, and will prematurely stop if a nil value is encountered
Lets try to write the code for ?.
extension Optional {
func ?.<U>(lhs: Wrapped?, rhs: (Wrapped) -> U) -> U? {
switch self {
case .some(let value):
return .some(rhs(value))
case .none:
return nil
}
}
}
Disclaimer : this is a simpli鍖ed
case for methods with no
arguments
Arrays
Lets manipulate an Array
let data: [Int] = [0, 1, 2]
let result = data.map { $0 * 2 }.map { $0 * $0 }
Lets manipulate an Array
let data: [Int] = [0, 1, 2]
let result = data.map { $0 * 2 }.map { $0 * $0 }
Same thing here: the function map allows us to declare a work鍖ow
A possible implementation for map
extension Array {
func map<U>(_ transform: (Element) -> U) -> [U] {
var result: [U] = []
for e in self {
result.append(transform(e))
}
return result
}
}
Functions
Lets compose functions
let double: (Int) -> Int = { x in x * 2 }
let square: (Int) -> Int = { x in x * x }
infix operator  : AdditionPrecedence
func <T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) ->
V) {
return { t in lhs(rhs(t)) }
}
let result = (double  square)(4) // result == 32
Disclaimer : @escaping
attributes have been omitted
Lets compose functions
let double: (Int) -> Int = { x in x * 2 }
let square: (Int) -> Int = { x in x * x }
infix operator  : AdditionPrecedence
func <T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) ->
V) {
return { t in lhs(rhs(t)) }
}
let result = (double  square)(4) // result == 32
We have three similar behaviors,
yet backed by very different
implementation
What are the common parts?
 They contain value(s) inside a context
 They add new features to existing types
 They provide an interface to transform/map the inner value
Monad: intuitive de鍖nition
 Wraps a type inside a context
 Provides a mechanism to create a work鍖ow of transforms
Minimal Monad
struct Monad<T> {
let value: T
// additional data
static func just(_ value: T) -> Monad<T> {
return self.init(value: value)
}
}
infix operator >>> : AdditionPrecedence
func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) -> Monad<V> {
// specific combination code
}
Some applications
Writer Monad
 We have an application that does a lot of numerical calculation
 Its hard to keep track of how values have been computed
 We would like to have a way to store a value along with a log of all
the transformation it went through
Writer Monad
struct Logged<T> {
let value: T
let logs: [String]
private init(value: T) {
self.value = value
self.logs = ["initialized with value: (self.value)"]
}
static func just(_ value: T) -> Logged<T> {
return Logged(value: value)
}
}
func >>> <U, V>(lhs: Logged<U>, rhs: (U) -> Logged<V>) -> Logged<V> {
let computation = rhs(lhs.value)
return Logged<V>(value: computation.value, logs: lhs.logs + computation.logs)
}
func square(_ value: Int) -> Logged<Int> {
let result = value * value
return Logged(value: result, log: "(value) was squared, result: (result)")
}
func halve(_ value: Int) -> Logged<Int> {
let result = value / 2
return Logged(value: result, log: "(value) was halved, result: (result)")
}
Writer Monad
let computation = .just(4) >>> square >>> halve
print(computation)
// Logged<Int>(value: 8, logs: ["initialized with value:
4", "4 was squared, result: 16", "16 was halved, result:
8"])
Reader Monad
 We have a function that require environment variables
 We dont want to hard code those variables, because it makes
testing impossible
 We would like to have a way to declare the operation we want to
perform, but they would be actually executed only when we provide
the environment variables
Reader Monad
struct Reader<E, A> {
let g: (E) -> A
init(g: @escaping (E) -> A) {
self.g = g
}
func apply(_ e: E) -> A {
return g(e)
}
func flatMap<B>(_ f: @escaping (A) -> Reader<E, B>) -> Reader<E, B> {
return Reader<E, B> { e in f(self.g(e)).g(e) }
}
}
func >>> <E, A, B>(a: Reader<E, A>, f: @autoclosure @escaping (A) -> Reader<E, B>) ->
Reader<E, B> {
return a.flatMap(f)
}
Reader Monad
struct Environment {
var dbPath: String
}
func delete(_ userName: String) -> Reader<Environment, Void> {
return Reader<Environment, Void> { env in
print("Delete (userName) at DB path: (env.dbPath)")
}
}
let testWorkflow = delete("Thor") >>> delete("Loki")
let productionWorkflow = delete("Odin")
testWorkflow.apply(Environment(dbPath: "path_to_test"))
productionWorkflow.apply(Environment(dbPath: "path_to_prod"))
IO Monad
 We like pure functional programs because they have no side-effects
 Unfortunately, programs also need to do I/O, which bears side-
effects by de鍖nition
 The IO Monad allows us to encapsulate those side effects, and use
them in a pure functional way
IO Monad
enum IO<T> {
case value(T)
case error
static func just(_ value: T) -> IO<T> {
return .value(value)
}
}
func wrightLine<T>(_ value: T) -> IO<Void> {
print(value as Any)
return IO<Void>.just(())
}
func getLine(_: Void) -> IO<String> {
switch readLine() {
case let value?:
return .value(value)
case nil:
return .error
}
}
@discardableResult func >>> <U, V>(lhs: IO<U>, rhs: (U) -> IO<V>) -> IO<V> {
switch lhs {
case .error:
return .error
case .value(let lhs):
return rhs(lhs)
}
}
IO Monad
.just(()) >>> getLine
>>> { IO<String>.just($0.uppercased()) }
>>> wrightLine
> Hello world!
// HELLO WORLD!
Formal de鍖nition
struct Monad<T> {
let value: T
static func just(_ value: T) -> Monad<T>
}
func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) ->
Monad<V>
The following API:
Is a Monad if
let x: T, (.just(x) >>> f) == f(x)
let m: (U) -> Monad(V), (m >>> just) == m
let f, g, h: (T) -> T, f >>> g >>> h == f >>> { x in f(x) >>> h(x)
Associativity
Neutral element
How about mobile apps?
Questions ?
Bibliography
 https://en.wikipedia.org/wiki/Monad_(functional_programming)
 https://www.youtube.com/watch?v=ZhuHCtR3xq8 (Brian Beckman:
Don't fear the Monad)
 https://academy.realm.io/posts/slug-raheel-ahmad-using-monads-
functional-paradigms-in-practice-functors-patterns-swift/ (Using
Monads and Other Functional Paradigms in Practice)
 https://github.com/orakaro/Swift-monad-Maybe-Reader-and-Try

More Related Content

Similar to Monads in Swift (20)

New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
Hermann Hueck
C# programming
C# programming C# programming
C# programming
umesh patil
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
GeeksLab Odessa
Array Cont
Array ContArray Cont
Array Cont
Ashutosh Srivasatava
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
senejug
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
Taisuke Oe
functions
functionsfunctions
functions
Makwana Bhavesh
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
David Galichet
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Olexandra Dmytrenko
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Madina Kamzina
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
Hermann Hueck
C# programming
C# programming C# programming
C# programming
umesh patil
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
Java/Scala Lab: 仆舒仂仍亳亶 仄亠ミ - Scala SubScript: 仍亞亠弍舒 亟仍 亠舒从亳于仆仂亞仂 仗...
GeeksLab Odessa
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
senejug
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
Taisuke Oe
Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
David Galichet
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Gdg almaty. 个仆从亳仂仆舒仍仆仂亠 仗仂亞舒仄仄亳仂于舒仆亳亠 于 Java 8
Madina Kamzina

More from Vincent Pradeilles (9)

On-Boarding New Engineers
On-Boarding New EngineersOn-Boarding New Engineers
On-Boarding New Engineers
Vincent Pradeilles
The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPaths
Vincent Pradeilles
Solving callback hell with good old function composition
Solving callback hell with good old function compositionSolving callback hell with good old function composition
Solving callback hell with good old function composition
Vincent Pradeilles
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
Vincent Pradeilles
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for free
Vincent Pradeilles
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional Programing
Vincent Pradeilles
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
Vincent Pradeilles
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPaths
Vincent Pradeilles
Solving callback hell with good old function composition
Solving callback hell with good old function compositionSolving callback hell with good old function composition
Solving callback hell with good old function composition
Vincent Pradeilles
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
Vincent Pradeilles
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for free
Vincent Pradeilles
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
Implementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional ProgramingImplementing pseudo-keywords through Functional Programing
Implementing pseudo-keywords through Functional Programing
Vincent Pradeilles
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
Vincent Pradeilles
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles

Recently uploaded (20)

AR/VR Company in India - Simulanis.com
AR/VR Company in India  -  Simulanis.comAR/VR Company in India  -  Simulanis.com
AR/VR Company in India - Simulanis.com
mdashraf329911
Adobe XD Crack Version 2025 Free Download
Adobe XD Crack Version 2025 Free DownloadAdobe XD Crack Version 2025 Free Download
Adobe XD Crack Version 2025 Free Download
mohsinrazakpa67
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
mohsinrazakpa28
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
jackalen173
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round UpEMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
BradBedford3
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know itWill Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Christian Dahlen
Typing Master Pro 12 Crack Updated Version [April-2025]
Typing Master Pro 12 Crack Updated Version [April-2025]Typing Master Pro 12 Crack Updated Version [April-2025]
Typing Master Pro 12 Crack Updated Version [April-2025]
jhonjosh91
Building-Your-Professional-Website-No-Coding-Required
Building-Your-Professional-Website-No-Coding-RequiredBuilding-Your-Professional-Website-No-Coding-Required
Building-Your-Professional-Website-No-Coding-Required
Ozias Rondon
Internet Download Manager Crack Latest version 2025
Internet Download Manager  Crack Latest version 2025Internet Download Manager  Crack Latest version 2025
Internet Download Manager Crack Latest version 2025
mohsinrazakpa26
Oracle Database administration Security PPT
Oracle Database administration Security PPTOracle Database administration Security PPT
Oracle Database administration Security PPT
pshankarnarayan
Microsoft Office Crack 2019 Free Download
Microsoft Office Crack 2019 Free DownloadMicrosoft Office Crack 2019 Free Download
Microsoft Office Crack 2019 Free Download
tayab01kp
Wondershare Filmora 14.3.2 Crack + License Key Free Download
Wondershare Filmora 14.3.2 Crack + License Key Free DownloadWondershare Filmora 14.3.2 Crack + License Key Free Download
Wondershare Filmora 14.3.2 Crack + License Key Free Download
anglekaan18
Driver Genius 24 Crack 2025 License Key Free Download
Driver Genius 24 Crack 2025 License Key Free DownloadDriver Genius 24 Crack 2025 License Key Free Download
Driver Genius 24 Crack 2025 License Key Free Download
umeerbinfaizan
IBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdfIBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdf
WILSON990330
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
blouch36kp
Movavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free DownloadMovavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free Download
imran03kr
Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]
l07307095
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025
farooq048kp
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: OverviewChoreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
WSO2
AR/VR Company in India - Simulanis.com
AR/VR Company in India  -  Simulanis.comAR/VR Company in India  -  Simulanis.com
AR/VR Company in India - Simulanis.com
mdashraf329911
Adobe XD Crack Version 2025 Free Download
Adobe XD Crack Version 2025 Free DownloadAdobe XD Crack Version 2025 Free Download
Adobe XD Crack Version 2025 Free Download
mohsinrazakpa67
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
mohsinrazakpa28
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
Bandicut Video Cutter v3.6.8.709 Crack [April-2025]
jackalen173
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round UpEMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
EMEA Virtual Marketo User Group - Adobe Summit 2025 Round Up
BradBedford3
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know itWill Ai Eat the Industrial World? The End of Engineering as We Know it
Will Ai Eat the Industrial World? The End of Engineering as We Know it
Christian Dahlen
Typing Master Pro 12 Crack Updated Version [April-2025]
Typing Master Pro 12 Crack Updated Version [April-2025]Typing Master Pro 12 Crack Updated Version [April-2025]
Typing Master Pro 12 Crack Updated Version [April-2025]
jhonjosh91
Building-Your-Professional-Website-No-Coding-Required
Building-Your-Professional-Website-No-Coding-RequiredBuilding-Your-Professional-Website-No-Coding-Required
Building-Your-Professional-Website-No-Coding-Required
Ozias Rondon
Internet Download Manager Crack Latest version 2025
Internet Download Manager  Crack Latest version 2025Internet Download Manager  Crack Latest version 2025
Internet Download Manager Crack Latest version 2025
mohsinrazakpa26
Oracle Database administration Security PPT
Oracle Database administration Security PPTOracle Database administration Security PPT
Oracle Database administration Security PPT
pshankarnarayan
Microsoft Office Crack 2019 Free Download
Microsoft Office Crack 2019 Free DownloadMicrosoft Office Crack 2019 Free Download
Microsoft Office Crack 2019 Free Download
tayab01kp
Wondershare Filmora 14.3.2 Crack + License Key Free Download
Wondershare Filmora 14.3.2 Crack + License Key Free DownloadWondershare Filmora 14.3.2 Crack + License Key Free Download
Wondershare Filmora 14.3.2 Crack + License Key Free Download
anglekaan18
Driver Genius 24 Crack 2025 License Key Free Download
Driver Genius 24 Crack 2025 License Key Free DownloadDriver Genius 24 Crack 2025 License Key Free Download
Driver Genius 24 Crack 2025 License Key Free Download
umeerbinfaizan
IBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdfIBM / MAINFRAME /RACF security-guide_pdf.pdf
IBM / MAINFRAME /RACF security-guide_pdf.pdf
WILSON990330
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
Internet Download Manager (IDM) Crack + Lisence key Latest version 2025
blouch36kp
Movavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free DownloadMovavi Screen Recorder Studio 2025 crack Free Download
Movavi Screen Recorder Studio 2025 crack Free Download
imran03kr
Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]Movavi Video Editor Crack + Activation Key [2025]
Movavi Video Editor Crack + Activation Key [2025]
l07307095
ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]ESET Smart Security Crack + Activation Key 2025 [Latest]
ESET Smart Security Crack + Activation Key 2025 [Latest]
umeerbinfaizan
Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025Coreldraw 2021 Crack Latest Version 2025
Coreldraw 2021 Crack Latest Version 2025
farooq048kp
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: OverviewChoreo - The AI-Native Internal Developer Platform as a Service: Overview
Choreo - The AI-Native Internal Developer Platform as a Service: Overview
WSO2

Monads in Swift

  • 3. First-class and higher-order functions let double: (Int) -> Int = { $0 * 2 } func apply(value: Int, function: (Int) -> Int) -> Int { return function(value) } let result = apply(value: 4, function: double) // result == 8
  • 4. Some properties A function is said to be pure if it produces no side-effects and its return value only depends on its arguments An expression is said to be referentially transparent if it can be replaced by its value without altering the programs behavior
  • 6. Some very familiar code var data: [String]? // ... let result = data?.first?.uppercased()
  • 7. Some very familiar code var data: [String]? // ... let result = data?.first?.uppercased() The operator ?. allows us to declare a work鍖ow that will be executed in order, and will prematurely stop if a nil value is encountered
  • 8. Lets try to write the code for ?. extension Optional { func ?.<U>(lhs: Wrapped?, rhs: (Wrapped) -> U) -> U? { switch self { case .some(let value): return .some(rhs(value)) case .none: return nil } } } Disclaimer : this is a simpli鍖ed case for methods with no arguments
  • 10. Lets manipulate an Array let data: [Int] = [0, 1, 2] let result = data.map { $0 * 2 }.map { $0 * $0 }
  • 11. Lets manipulate an Array let data: [Int] = [0, 1, 2] let result = data.map { $0 * 2 }.map { $0 * $0 } Same thing here: the function map allows us to declare a work鍖ow
  • 12. A possible implementation for map extension Array { func map<U>(_ transform: (Element) -> U) -> [U] { var result: [U] = [] for e in self { result.append(transform(e)) } return result } }
  • 14. Lets compose functions let double: (Int) -> Int = { x in x * 2 } let square: (Int) -> Int = { x in x * x } infix operator : AdditionPrecedence func <T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) { return { t in lhs(rhs(t)) } } let result = (double square)(4) // result == 32 Disclaimer : @escaping attributes have been omitted
  • 15. Lets compose functions let double: (Int) -> Int = { x in x * 2 } let square: (Int) -> Int = { x in x * x } infix operator : AdditionPrecedence func <T, U, V>(lhs: (U) -> V, rhs: (T) -> U) -> ((T) -> V) { return { t in lhs(rhs(t)) } } let result = (double square)(4) // result == 32
  • 16. We have three similar behaviors, yet backed by very different implementation
  • 17. What are the common parts? They contain value(s) inside a context They add new features to existing types They provide an interface to transform/map the inner value
  • 18. Monad: intuitive de鍖nition Wraps a type inside a context Provides a mechanism to create a work鍖ow of transforms
  • 19. Minimal Monad struct Monad<T> { let value: T // additional data static func just(_ value: T) -> Monad<T> { return self.init(value: value) } } infix operator >>> : AdditionPrecedence func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) -> Monad<V> { // specific combination code }
  • 21. Writer Monad We have an application that does a lot of numerical calculation Its hard to keep track of how values have been computed We would like to have a way to store a value along with a log of all the transformation it went through
  • 22. Writer Monad struct Logged<T> { let value: T let logs: [String] private init(value: T) { self.value = value self.logs = ["initialized with value: (self.value)"] } static func just(_ value: T) -> Logged<T> { return Logged(value: value) } } func >>> <U, V>(lhs: Logged<U>, rhs: (U) -> Logged<V>) -> Logged<V> { let computation = rhs(lhs.value) return Logged<V>(value: computation.value, logs: lhs.logs + computation.logs) } func square(_ value: Int) -> Logged<Int> { let result = value * value return Logged(value: result, log: "(value) was squared, result: (result)") } func halve(_ value: Int) -> Logged<Int> { let result = value / 2 return Logged(value: result, log: "(value) was halved, result: (result)") }
  • 23. Writer Monad let computation = .just(4) >>> square >>> halve print(computation) // Logged<Int>(value: 8, logs: ["initialized with value: 4", "4 was squared, result: 16", "16 was halved, result: 8"])
  • 24. Reader Monad We have a function that require environment variables We dont want to hard code those variables, because it makes testing impossible We would like to have a way to declare the operation we want to perform, but they would be actually executed only when we provide the environment variables
  • 25. Reader Monad struct Reader<E, A> { let g: (E) -> A init(g: @escaping (E) -> A) { self.g = g } func apply(_ e: E) -> A { return g(e) } func flatMap<B>(_ f: @escaping (A) -> Reader<E, B>) -> Reader<E, B> { return Reader<E, B> { e in f(self.g(e)).g(e) } } } func >>> <E, A, B>(a: Reader<E, A>, f: @autoclosure @escaping (A) -> Reader<E, B>) -> Reader<E, B> { return a.flatMap(f) }
  • 26. Reader Monad struct Environment { var dbPath: String } func delete(_ userName: String) -> Reader<Environment, Void> { return Reader<Environment, Void> { env in print("Delete (userName) at DB path: (env.dbPath)") } } let testWorkflow = delete("Thor") >>> delete("Loki") let productionWorkflow = delete("Odin") testWorkflow.apply(Environment(dbPath: "path_to_test")) productionWorkflow.apply(Environment(dbPath: "path_to_prod"))
  • 27. IO Monad We like pure functional programs because they have no side-effects Unfortunately, programs also need to do I/O, which bears side- effects by de鍖nition The IO Monad allows us to encapsulate those side effects, and use them in a pure functional way
  • 28. IO Monad enum IO<T> { case value(T) case error static func just(_ value: T) -> IO<T> { return .value(value) } } func wrightLine<T>(_ value: T) -> IO<Void> { print(value as Any) return IO<Void>.just(()) } func getLine(_: Void) -> IO<String> { switch readLine() { case let value?: return .value(value) case nil: return .error } } @discardableResult func >>> <U, V>(lhs: IO<U>, rhs: (U) -> IO<V>) -> IO<V> { switch lhs { case .error: return .error case .value(let lhs): return rhs(lhs) } }
  • 29. IO Monad .just(()) >>> getLine >>> { IO<String>.just($0.uppercased()) } >>> wrightLine > Hello world! // HELLO WORLD!
  • 30. Formal de鍖nition struct Monad<T> { let value: T static func just(_ value: T) -> Monad<T> } func >>> <U, V>(lhs: Monad<U>, rhs: (U) -> Monad<V>) -> Monad<V> The following API: Is a Monad if let x: T, (.just(x) >>> f) == f(x) let m: (U) -> Monad(V), (m >>> just) == m let f, g, h: (T) -> T, f >>> g >>> h == f >>> { x in f(x) >>> h(x) Associativity Neutral element
  • 33. Bibliography https://en.wikipedia.org/wiki/Monad_(functional_programming) https://www.youtube.com/watch?v=ZhuHCtR3xq8 (Brian Beckman: Don't fear the Monad) https://academy.realm.io/posts/slug-raheel-ahmad-using-monads- functional-paradigms-in-practice-functors-patterns-swift/ (Using Monads and Other Functional Paradigms in Practice) https://github.com/orakaro/Swift-monad-Maybe-Reader-and-Try