SlideShare a Scribd company logo
{ FP in }
Fatih Nayebi | 2016-04-06 18:00 | Tour CGI
Swift Montréal Meetup
Agenda
• Introduction
• First-class, Higher-order and Pure Functions
• Closures
• Generics and Associated Type Protocols
• Enumerations and Pattern Matching
• Optionals
• Functors, Applicative Functors and Monads
Introduction
• Why Swift?
• Hybrid Language (FP, OOP and POP)
• Type Safety and Type Inference
• Immutability and Value Types
• Playground and REPL
• Automatic Reference Counting (ARC)
• Why Functional Programming matters?
Functional Programming
• A style of programming that models computations as
the evaluation of expressions
• Avoiding mutable states
• Declarative vs. Imperative
• Lazy evaluation
• Pattern matching
An introduction to functional programming with Swift
Declarative vs. Imperative
let numbers = [9, 29, 19, 79]
// Imperative example
var tripledNumbers:[Int] = []
for number in numbers {
tripledNumbers.append(number * 3)
}
print(tripledNumbers)
// Declarative example
let tripledIntNumbers = numbers.map({
number in 3 * number
})
print(tripledIntNumbers)
Shorter syntax
let tripledIntNumbers = numbers.map({
number in 3 * number
})
let tripledIntNumbers = numbers.map { $0 * 3 }
Lazy Evaluation
let oneToFour = [1, 2, 3, 4]
let firstNumber = oneToFour.lazy.map({ $0 * 3}).first!
print(firstNumber) // 3
Functions
• First-class citizens
• Functions are treated like any other values and can be passed to other
functions or returned as a result of a function
• Higher-order functions
• Functions that take other functions as their arguments
• Pure functions
• Functions that do not depend on any data outside of themselves and they
do not change any data outside of themselves
• They provide the same result each time they are executed (Referential
transparency makes it possible to conduct equational reasoning)
Nested Functions
func returnTwenty() -> Int {
var y = 10
func add() {
y += 10
}
add()
return y
}
returnTwenty()
Higher-order Functions
func calcualte(a: Int,
b: Int,
funcA: AddSubtractOperator,
funcB: SquareTripleOperator) -> Int
{
return funcA(funcB(a), funcB(b))
}
Returning Functions
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
Function Types
let mathOperator: (Double, Double) -> Double
typealias operator = (Double, Double) -> Double
var operator: SimpleOperator
func addTwoNumbers(a: Double, b: Double) -> Double
{ return a + b }
mathOperator = addTwoNumbers
let result = mathOperator(3.5, 5.5)
First-class Citizens
let name: String = "John Doe"
func sayHello(name: String) {
print("Hello (name)")
}
// we pass a String type with its respective
value
sayHello("John Doe") // or
sayHello(name)
// store a function in a variable to be able to
pass it around
let sayHelloFunc = sayHello
Function Composition
let content = "10,20,40,30,60"
func extractElements(content: String) -> [String] {
return content.characters.split(“,").map { String($0) }
}
let elements = extractElements(content)
func formatWithCurrency(content: [String]) -> [String] {
return content.map {"($0)$"}
}
let contentArray = ["10", "20", "40", "30", "60"]
let formattedElements = formatWithCurrency(contentArray)
Function Composition
let composedFunction = { data in
formatWithCurrency(extractElements(data))
}
composedFunction(content)
Custom Operators
infix operator |> { associativity left }
func |> <T, V>(f: T -> V, g: V -> V ) -> T -> V {
return { x in g(f(x)) }
}
let composedFn = extractElements |> formatWithCurrency
composedFn("10,20,40,30,80,60")
Closures
• Functions without the func keyword
• Closures are self-contained blocks of code that
provide a specific functionality, can be stored, passed
around and used in code.
• Closures are reference types
Closure Syntax
{ (parameters) -> ReturnType in
// body of closure
}
Closures as function parameters/arguments:
func({(Int) -> (Int) in
//statements
})
Closure Syntax (Cntd.)
let anArray = [10, 20, 40, 30, 80, 60]
anArray.sort({ (param1: Int, param2: Int) -> Bool in
return param1 < param2
})
anArray.sort({ (param1, param2) in
return param1 < param2
})
anArray.sort { (param1, param2) in
return param1 < param2
}
anArray.sort { return $0 < $1 }
anArray.sort { $0 < $1 }
Types
• Value vs. reference types
• Type inference and Casting
• Value type characteristics
• Behaviour - Value types do not behave
• Isolation - Value types have no implicit dependencies on the behaviour of
any external system
• Interchangeability - Because a value type is copied when it is assigned to a
new variable, all of those copies are completely interchangeable.
• Testability - There is no need for a mocking framework to write unit tests
that deal with value types.
struct vs. class
struct ourStruct {
var data: Int = 3
}
var valueA = ourStruct()
var valueB = valueA // valueA is copied to valueB
valueA.data = 5 // Changes valueA, not valueB
class ourClass {
var data: Int = 3
}
var referenceA = ourClass()
var referenceB = referenceA // referenceA is copied
to referenceB
referenceA.data = 5 // changes the instance
referred to by referenceA and referenceB
Type Casting (is and as)
• A way to check type of an instance, and/or to treat that
instance as if it is a different superclass or subclass from
somewhere else in its own class hierarchy.
• Type check operator - is - to check wether an instance is
of a certain subclass type
• Type cast operator - as and as? - A constant or variable
of a certain class type may actually refer to an instance of a
subclass behind the scenes. Where you believe this is the
case, you can try to downcast to the subclass type with
the as.
Enumerations
• Common type for related values to be used in a type-safe way
• Value provided for each enumeration member can be a string,
character, integer or any floating-point type.
• Associated Values - Can define Swift enumerations to store
Associated Values of any given type, and the value types can be
different for each member of the enumeration if needed
(discriminated unions, tagged unions, or variants).
• Raw Values - Enumeration members can come pre-populated with
default values, which are all of the same type.
• Algebraic data types
Enum & Pattern Matching
enum MLSTeam {
case Montreal
case Toronto
case NewYork
}
let theTeam = MLSTeam.Montreal
switch theTeam {
case .Montreal:
print("Montreal Impact")
case .Toronto:
print("Toronto FC")
case .NewYork:
print("Newyork Redbulls")
}
Algebraic Data Types
enum NHLTeam { case Canadiens, Senators, Rangers,
Penguins, BlackHawks, Capitals}
enum Team {
case Hockey(NHLTeam)
case Soccer(MLSTeam)
}
struct HockeyAndSoccerTeams {
var hockey: NHLTeam
var soccer: MLSTeam
}
enum HockeyAndSoccerTeams {
case Value(hockey: NHLTeam, soccer: MLSTeam)
}
Generics
• Generics enable us to write flexible and reusable functions and
types that can work with any type, subject to requirements that
we define.
func swapTwoIntegers(inout a: Int, inout b: Int) {
let tempA = a
a = b
b = tempA
}
func swapTwoValues<T>(inout a: T, inout b: T) {
let tempA = a
a = b
b = tempA
}
Functional Data Structures
enum Tree <T> {
case Leaf(T)
indirect case Node(Tree, Tree)
}
let ourGenericTree =
Tree.Node(Tree.Leaf("First"),
Tree.Node(Tree.Leaf("Second"),
Tree.Leaf("Third")))
Associated Type Protocols
protocol Container {
associatedtype ItemType
func append(item: ItemType)
}
Optionals!?
enum Optional<T> {
case None
case Some(T)
}
func mapOptionals<T, V>(transform: T -> V, input:
T?) -> V? {
switch input {
case .Some(let value): return transform(value)
case .None: return .None
}
}
Optionals!? (Cntd.)
class User {
var name: String?
}
func extractUserName(name: String) -> String {
return "(name)"
}
var nonOptionalUserName: String {
let user = User()
user.name = "John Doe"
let someUserName = mapOptionals(extractUserName, input:
user.name)
return someUserName ?? ""
}
fmap
infix operator <^> { associativity left }
func <^><T, V>(transform: T -> V, input: T?) -> V? {
switch input {
case .Some(let value): return transform(value)
case .None: return .None
}
}
var nonOptionalUserName: String {
let user = User()
user.name = "John Doe"
let someUserName = extractUserName <^> user.name
return someUserName ?? ""
}
apply
infix operator <*> { associativity left }
func <*><T, V>(transform: (T -> V)?, input: T?) -> V? {
switch transform {
case .Some(let fx): return fx <^> input
case .None: return .None
}
}
func extractFullUserName(firstName: String)(lastName: String) -> String {
return "(firstName) (lastName)"
}
var fullName: String {
let user = User()
user.firstName = "John"
user.lastName = "Doe"
let fullUserName = extractFullUserName <^> user.firstName <*> user.lastName
return fullUserName ?? ""
}
Monad
• Optional type is a Monad so it implements map and
flatMap
let optArr: [String?] = ["First", nil, "Third"]
let nonOptionalArray = optArr.flatMap { $0 }
Functor, Applicative Functor &
Monad
• Category Theory
• Functor: Any type that implements map function
• Applicative Functor: Functor + apply()
• Monad: Functor + flatMap()
Immutability
• Swift makes it easy to define immutables
• Powerful value types (struct, enum and tuple)
References
• The Swift Programming Language by Apple (swift.org)
• Addison Wesley - The Swift Developer’s Cookbook by
Erica Sadun
• Packt Publishing - Swift 2 Functional Programming by
Fatih Nayebi
Ad

More Related Content

What's hot (20)

Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
Martin Ockajak
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
Jared Roesch
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
nkpart
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
strikr .
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
Chinedu Ekwunife
 
Templates
TemplatesTemplates
Templates
Pranali Chaudhari
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Jorge Vásquez
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
Ganesh Samarthyam
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
Ralph Johnson
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
Remik Koczapski
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
Ruslan Shevchenko
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
Martin Ockajak
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
Jared Roesch
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
nkpart
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
strikr .
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Jorge Vásquez
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
Ralph Johnson
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
Remik Koczapski
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 

Similar to An introduction to functional programming with Swift (20)

10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
LOVELY PROFESSIONAL UNIVERSITY
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golang
www.ixxo.io
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
Kazunobu Tasaka
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
Brendan Eich
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
MLG College of Learning, Inc
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
Unit_I-Introduction python programming (1).pptx
Unit_I-Introduction python programming (1).pptxUnit_I-Introduction python programming (1).pptx
Unit_I-Introduction python programming (1).pptx
arunbalaji707
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Introduction of function in c programming.pptx
Introduction of function in c programming.pptxIntroduction of function in c programming.pptx
Introduction of function in c programming.pptx
abhajgude
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
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
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
Frank Müller
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golang
www.ixxo.io
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
Brendan Eich
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Unit_I-Introduction python programming (1).pptx
Unit_I-Introduction python programming (1).pptxUnit_I-Introduction python programming (1).pptx
Unit_I-Introduction python programming (1).pptx
arunbalaji707
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Introduction of function in c programming.pptx
Introduction of function in c programming.pptxIntroduction of function in c programming.pptx
Introduction of function in c programming.pptx
abhajgude
 
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
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Ad

Recently uploaded (20)

Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Ad

An introduction to functional programming with Swift

  • 1. { FP in } Fatih Nayebi | 2016-04-06 18:00 | Tour CGI Swift Montréal Meetup
  • 2. Agenda • Introduction • First-class, Higher-order and Pure Functions • Closures • Generics and Associated Type Protocols • Enumerations and Pattern Matching • Optionals • Functors, Applicative Functors and Monads
  • 3. Introduction • Why Swift? • Hybrid Language (FP, OOP and POP) • Type Safety and Type Inference • Immutability and Value Types • Playground and REPL • Automatic Reference Counting (ARC) • Why Functional Programming matters?
  • 4. Functional Programming • A style of programming that models computations as the evaluation of expressions • Avoiding mutable states • Declarative vs. Imperative • Lazy evaluation • Pattern matching
  • 6. Declarative vs. Imperative let numbers = [9, 29, 19, 79] // Imperative example var tripledNumbers:[Int] = [] for number in numbers { tripledNumbers.append(number * 3) } print(tripledNumbers) // Declarative example let tripledIntNumbers = numbers.map({ number in 3 * number }) print(tripledIntNumbers)
  • 7. Shorter syntax let tripledIntNumbers = numbers.map({ number in 3 * number }) let tripledIntNumbers = numbers.map { $0 * 3 }
  • 8. Lazy Evaluation let oneToFour = [1, 2, 3, 4] let firstNumber = oneToFour.lazy.map({ $0 * 3}).first! print(firstNumber) // 3
  • 9. Functions • First-class citizens • Functions are treated like any other values and can be passed to other functions or returned as a result of a function • Higher-order functions • Functions that take other functions as their arguments • Pure functions • Functions that do not depend on any data outside of themselves and they do not change any data outside of themselves • They provide the same result each time they are executed (Referential transparency makes it possible to conduct equational reasoning)
  • 10. Nested Functions func returnTwenty() -> Int { var y = 10 func add() { y += 10 } add() return y } returnTwenty()
  • 11. Higher-order Functions func calcualte(a: Int, b: Int, funcA: AddSubtractOperator, funcB: SquareTripleOperator) -> Int { return funcA(funcB(a), funcB(b)) }
  • 12. Returning Functions func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7)
  • 13. Function Types let mathOperator: (Double, Double) -> Double typealias operator = (Double, Double) -> Double var operator: SimpleOperator func addTwoNumbers(a: Double, b: Double) -> Double { return a + b } mathOperator = addTwoNumbers let result = mathOperator(3.5, 5.5)
  • 14. First-class Citizens let name: String = "John Doe" func sayHello(name: String) { print("Hello (name)") } // we pass a String type with its respective value sayHello("John Doe") // or sayHello(name) // store a function in a variable to be able to pass it around let sayHelloFunc = sayHello
  • 15. Function Composition let content = "10,20,40,30,60" func extractElements(content: String) -> [String] { return content.characters.split(“,").map { String($0) } } let elements = extractElements(content) func formatWithCurrency(content: [String]) -> [String] { return content.map {"($0)$"} } let contentArray = ["10", "20", "40", "30", "60"] let formattedElements = formatWithCurrency(contentArray)
  • 16. Function Composition let composedFunction = { data in formatWithCurrency(extractElements(data)) } composedFunction(content)
  • 17. Custom Operators infix operator |> { associativity left } func |> <T, V>(f: T -> V, g: V -> V ) -> T -> V { return { x in g(f(x)) } } let composedFn = extractElements |> formatWithCurrency composedFn("10,20,40,30,80,60")
  • 18. Closures • Functions without the func keyword • Closures are self-contained blocks of code that provide a specific functionality, can be stored, passed around and used in code. • Closures are reference types
  • 19. Closure Syntax { (parameters) -> ReturnType in // body of closure } Closures as function parameters/arguments: func({(Int) -> (Int) in //statements })
  • 20. Closure Syntax (Cntd.) let anArray = [10, 20, 40, 30, 80, 60] anArray.sort({ (param1: Int, param2: Int) -> Bool in return param1 < param2 }) anArray.sort({ (param1, param2) in return param1 < param2 }) anArray.sort { (param1, param2) in return param1 < param2 } anArray.sort { return $0 < $1 } anArray.sort { $0 < $1 }
  • 21. Types • Value vs. reference types • Type inference and Casting • Value type characteristics • Behaviour - Value types do not behave • Isolation - Value types have no implicit dependencies on the behaviour of any external system • Interchangeability - Because a value type is copied when it is assigned to a new variable, all of those copies are completely interchangeable. • Testability - There is no need for a mocking framework to write unit tests that deal with value types.
  • 22. struct vs. class struct ourStruct { var data: Int = 3 } var valueA = ourStruct() var valueB = valueA // valueA is copied to valueB valueA.data = 5 // Changes valueA, not valueB class ourClass { var data: Int = 3 } var referenceA = ourClass() var referenceB = referenceA // referenceA is copied to referenceB referenceA.data = 5 // changes the instance referred to by referenceA and referenceB
  • 23. Type Casting (is and as) • A way to check type of an instance, and/or to treat that instance as if it is a different superclass or subclass from somewhere else in its own class hierarchy. • Type check operator - is - to check wether an instance is of a certain subclass type • Type cast operator - as and as? - A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with the as.
  • 24. Enumerations • Common type for related values to be used in a type-safe way • Value provided for each enumeration member can be a string, character, integer or any floating-point type. • Associated Values - Can define Swift enumerations to store Associated Values of any given type, and the value types can be different for each member of the enumeration if needed (discriminated unions, tagged unions, or variants). • Raw Values - Enumeration members can come pre-populated with default values, which are all of the same type. • Algebraic data types
  • 25. Enum & Pattern Matching enum MLSTeam { case Montreal case Toronto case NewYork } let theTeam = MLSTeam.Montreal switch theTeam { case .Montreal: print("Montreal Impact") case .Toronto: print("Toronto FC") case .NewYork: print("Newyork Redbulls") }
  • 26. Algebraic Data Types enum NHLTeam { case Canadiens, Senators, Rangers, Penguins, BlackHawks, Capitals} enum Team { case Hockey(NHLTeam) case Soccer(MLSTeam) } struct HockeyAndSoccerTeams { var hockey: NHLTeam var soccer: MLSTeam } enum HockeyAndSoccerTeams { case Value(hockey: NHLTeam, soccer: MLSTeam) }
  • 27. Generics • Generics enable us to write flexible and reusable functions and types that can work with any type, subject to requirements that we define. func swapTwoIntegers(inout a: Int, inout b: Int) { let tempA = a a = b b = tempA } func swapTwoValues<T>(inout a: T, inout b: T) { let tempA = a a = b b = tempA }
  • 28. Functional Data Structures enum Tree <T> { case Leaf(T) indirect case Node(Tree, Tree) } let ourGenericTree = Tree.Node(Tree.Leaf("First"), Tree.Node(Tree.Leaf("Second"), Tree.Leaf("Third")))
  • 29. Associated Type Protocols protocol Container { associatedtype ItemType func append(item: ItemType) }
  • 30. Optionals!? enum Optional<T> { case None case Some(T) } func mapOptionals<T, V>(transform: T -> V, input: T?) -> V? { switch input { case .Some(let value): return transform(value) case .None: return .None } }
  • 31. Optionals!? (Cntd.) class User { var name: String? } func extractUserName(name: String) -> String { return "(name)" } var nonOptionalUserName: String { let user = User() user.name = "John Doe" let someUserName = mapOptionals(extractUserName, input: user.name) return someUserName ?? "" }
  • 32. fmap infix operator <^> { associativity left } func <^><T, V>(transform: T -> V, input: T?) -> V? { switch input { case .Some(let value): return transform(value) case .None: return .None } } var nonOptionalUserName: String { let user = User() user.name = "John Doe" let someUserName = extractUserName <^> user.name return someUserName ?? "" }
  • 33. apply infix operator <*> { associativity left } func <*><T, V>(transform: (T -> V)?, input: T?) -> V? { switch transform { case .Some(let fx): return fx <^> input case .None: return .None } } func extractFullUserName(firstName: String)(lastName: String) -> String { return "(firstName) (lastName)" } var fullName: String { let user = User() user.firstName = "John" user.lastName = "Doe" let fullUserName = extractFullUserName <^> user.firstName <*> user.lastName return fullUserName ?? "" }
  • 34. Monad • Optional type is a Monad so it implements map and flatMap let optArr: [String?] = ["First", nil, "Third"] let nonOptionalArray = optArr.flatMap { $0 }
  • 35. Functor, Applicative Functor & Monad • Category Theory • Functor: Any type that implements map function • Applicative Functor: Functor + apply() • Monad: Functor + flatMap()
  • 36. Immutability • Swift makes it easy to define immutables • Powerful value types (struct, enum and tuple)
  • 37. References • The Swift Programming Language by Apple (swift.org) • Addison Wesley - The Swift Developer’s Cookbook by Erica Sadun • Packt Publishing - Swift 2 Functional Programming by Fatih Nayebi