SlideShare a Scribd company logo
1 of 53
Download to read offline
+ =f(x)
???
Geison Goes
● Senior Consultant na Thoughtworks
● Software Engineer for 12 years
● Husband
● Father
● Dog trainer
● Read more at about.me/geisonfgf
Functional Swift
Functional Programming by Wikipidia:
“Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions and avoids state and mutable data". In other
words, functional programming promotes code with no side effects, no change of
value in variables. It oposes to imperative programming, which emphasizes change of
state”.
What this means?
Functional Swift
What this means?
● No mutable data (no side effect).
Functional Swift
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
Functional Swift
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional Swift
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers
want it to be).
Functional Swift
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers
want it to be).
● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is
not “environment”.
Functional Swift
What this means?
● No mutable data (no side effect).
● No state (no implicit, hidden state).
Once assigned (value binding), a variable (a symbol) does not change its value.
All state is bad? No, hidden, implicit state is bad.
Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers
want it to be).
● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is
not “environment”.
● Same result returned by functions called with the same inputs.
Functional Swift
What are the advantages?
Functional Swift
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state
to comprehend what a function, a, method, a class, a whole project works.
Functional Swift
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state
to comprehend what a function, a, method, a class, a whole project works.
● Referential transparency: Expressions can be replaced by its values. If we call a function with the same
parameters, we know for sure the output will be the same (there is no state anywhere that would
change it).
Functional Swift
What are the advantages?
● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state
to comprehend what a function, a, method, a class, a whole project works.
● Referential transparency: Expressions can be replaced by its values. If we call a function with the same
parameters, we know for sure the output will be the same (there is no state anywhere that would
change it).
There is a reason for which Einstein defined insanity as "doing the same thing over and over again and
expecting different results".
Functional Swift
Advantages enabled by referential transparency
Functional Swift
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
Functional Swift
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
Functional Swift
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
● Modularization
○ We have no state that pervades the whole code, so we build our project with small, black boxes
that we tie together, so it promotes bottom-up programming.
Functional Swift
Advantages enabled by referential transparency
● Memoization
○ Cache results for previous function calls.
● Idempotence
○ Same results regardless how many times you call a function.
● Modularization
○ We have no state that pervades the whole code, so we build our project with small, black boxes
that we tie together, so it promotes bottom-up programming.
● Ease of debugging
○ Functions are isolated, they only depend on their input and their output, so they are very easy to
debug.
Functional Swift
Advantages enabled by referential transparency
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
Functional Swift
Advantages enabled by referential transparency
● Parallelization
○ Functions calls are independent.
○ We can parallelize in different process/CPUs/computers/…
We can execute func1 and func2 in parallel because a won’t be modified.
let result = func1(a, b) + func2(a, c)
Functional Swift
Advantages enabled by referential transparency
● Concurrence
a. With no shared data, concurrence gets a lot simpler:
i. No semaphores.
ii. No monitors.
iii. No locks.
iv. No race-conditions.
v. No dead-locks.
Functional Swift
Immutable Objects
Functional Swift
Immutable Objects
● An OO pattern that was originated in FP world.
Functional Swift
Immutable Objects
● An OO pattern that was originated in FP world.
● When changing a data structure, don’t modify in place but create a new object.
Functional Swift
Immutable Objects
● An OO pattern that was originated in FP world.
● When changing a data structure, don’t modify in place but create a new object.
● Name Mutating/nonmutating method pairs consistently. A mutating method will often have a
nonmutating variant with similar semantics, but that returns a new value rather than updating an
instance in-place.
Functional Swift
Immutable Objects
● An OO pattern that was originated in FP world.
● When changing a data structure, don’t modify in place but create a new object.
● Name Mutating/nonmutating method pairs consistently. A mutating method will often have a
nonmutating variant with similar semantics, but that returns a new value rather than updating an
instance in-place.
○ When the operation is naturally described by a verb, use the verb’s imperative for the mutating
method and apply the “ed” or “ing” suffix to name its nonmutating counterpart.
Functional Swift
Functional Swift
Ok so let's play a little with functional programming?
Don’t Update, Create - String
var name = "Geison"
var name = name + " Flores"
Functional Swift
Don’t Update, Create - String
var name = "Geison"
var name = name + " Flores"
let firstname = "Geison"
let lastname = "Flores"
let name = firstname + " " + lastname
Functional Swift
Don’t Update, Create - Arrays
var years: [Int] = [2001, 2002]
years.append(2003)
years.append(2004)
print(years) // [2001, 2002, 2003, 2004]
Functional Swift
Don’t Update, Create - Arrays
var years: [Int] = [2001, 2002]
years.append(2003)
years.append(2004)
print(years) // [2001, 2002, 2003, 2004]
let years: [Int] = [2001, 2001]
let allYears = years + [2003] + [2004, 2005]
print(allYears) // [2001, 2002, 2003, 2004, 2005]
Functional Swift
Don’t Update, Create - Dictionaries
var ages = ["John": 30]
ages["Mary"] = 28
print(ages) // ["Mary": 28, "John": 30]
Functional Swift
Don’t Update, Create - Dictionaries
var ages = ["John": 30]
ages["Mary"] = 28
print(ages) // ["Mary": 28, "John": 30]
Functional Swift
let johnAges = ["John": 30]
let maryAges = ["Mary": 28]
func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach{ result[$0] = $1 }
return result
}
let ages = johnAges + maryAges
print(ages) // ["Mary": 28, "John": 30]
Higher Order Functions
Functions and methods are first-class objects in Swift, so if you want to pass a function to another function,
you can just treat it as any other object.
typealias callerType = (String, String) -> String
func caller(function: callerType) -> Void {
let result = function("Hello", "David")
print(result)
}
caller(function: { $0 + " " + $1 })
Functional Swift
Higher Order Functions - Map
let names = ["milu", "rantanplan"]
let namesInUppercase = names.map { $0.uppercased() }
print(namesInUppercase) //["MILU", "RANTANPLAN"]
Functional Swift
Higher Order Functions - Filter
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let oddNumbers = numbers.filter { $0 % 2 != 0 }
print(oddNumbers) //[1, 3, 5, 9]
Functional Swift
Higher Order Functions - Reduce
let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(0, +)
print(total) //15
Functional Swift
Higher Order Functions - Closure
Functional Swift
func add_x(_ x: Int) -> ((Int) -> Int) {
func add_y(_ y: Int) -> Int {
return x + y
}
return add_y
}
let add_5 = add_x(5)
let add_7 = add_x(7)
print(add_5(10)) // result 15
print(add_7(10)) // result 17
print(add_x(2)(3)) // result 5
Currying and Partial Functions
Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a
composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a
function that accepts n parameters then you can generate from it one of more functions with some parameter values already
filled in.
Functional Swift
func plus(_ x: Int, _ y: Int) -> Int {
return x + y
}
func partialPlus(_ x: Int) -> ((Int) -> Int) {
func partial(_ y: Int) -> Int {
return plus(x, y)
}
return partial
}
let plus_one = partialPlus(1)
print(plus_one(5)) // 6
Eager vs Lazy Evaluation
Functional Swift
Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is assined, function called...
Functional Swift
Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell).
Functional Swift
Eager vs Lazy Evaluation
● Eager evaluation: expressions are calculated at the moment that variables is assined, function called...
● Lazy evaluation: delays the evaluation of the expression until it is needed.
○ Memory efficient: no memory used to store complete structures.
○ CPU efficient: no need to calculate the complete result before returning.
○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell).
Swift have lazy properties and lazy collections.
Functional Swift
Recursion
Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build
up and chain data construction. This is because looping is not a functional concept, as it requires variables to be
passed around to store the state of the loop at a given time.
● Purely functional languages have no imperative for-loops, so they use recursion a lot.
● If every recursion created an stack, it would blow up very soon.
● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself.
Functional Swift
Recursion
Imperative: Functional:
Functional Swift
func fibs(_ n: Int) -> Int {
guard n != 0, n != 1 else { return n }
return fibs(n - 1) + fibs(n - 2)
}
print(fibs(6)) //8
func fibs(_ n: Int) -> Int {
var tmp = 0
var current = 0
var prev = 1
for i in 1...n {
tmp = current
current = prev
prev = tmp + current
}
return current
}
print(fibs(6)) //8
A Pratical Example
Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?"
Imperative: Functional:
Functional Swift
print(
Array(1...100)
.filter({$0 * $0 % 5 == 0})
.prefix(10)
.reduce(0, +)
) //275
func main() -> Void {
var n: Int = 1
var numElements: Int = 0
var sum: Int = 0
while numElements < 10 {
if n * n % 5 == 0 {
sum += n
numElements += 1
}
n += 1
}
print(sum) //275
}
main()
Conclusion
Functional Swift
Conclusion
● As you can see, Swift helps you write in functional style but it doesn’t force you to it.
Functional Swift
Conclusion
● As you can see, Swift helps you write in functional style but it doesn’t force you to it.
● Writing in functional style enhances your code and makes it more self documented. Actually it will make
it more thread-safe also.
Functional Swift
Conclusion
● As you can see, Swift helps you write in functional style but it doesn’t force you to it.
● Writing in functional style enhances your code and makes it more self documented. Actually it will make
it more thread-safe also.
● The main support for FP in Swift comes from the use of closures, pattern matching, lazy evaluation and
generics.
Functional Swift
The last advice
Learn at least one functional language, it will open your mind to a new paradigm becoming you a better
programmer.
Some Functional Languages:
● Haskell
● ML (Standard ML, Objective Caml, ...)
● Scheme
● Erlang
● Scala
● Closure
● F# learnyouahaskell.com
Functional Swift
Functional Swift
OBRIGADO!
Email: geisonfgf@gmail.com
Skype: geisonfgf
Facebook: http://www.facebook.com/geisonfgf
Twitter: http://www.twitter.com/geisonfgf

More Related Content

What's hot

Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingKonrad Szydlo
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartChen Fisher
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional styleNiranjan Sarade
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
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 ProgrammingAdam Getchell
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mindSander Mak (@Sander_Mak)
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 

What's hot (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
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
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Scala qq
Scala qqScala qq
Scala qq
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 

Similar to Functional Swift

DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsJoshua Erney
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdfPuneetChaturvedi23
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Calvin Cheng
 
The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)Scott Wlaschin
 
Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsManjuKumara GH
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
 
Functional programing jargon
Functional programing jargonFunctional programing jargon
Functional programing jargonRemo Jansen
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#Riccardo Terrell
 
Pure functions and usage in Angular
Pure functions and usage in AngularPure functions and usage in Angular
Pure functions and usage in AngularMA Jiangfan
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmerShawn Button
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwMayankSinghRawat6
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#Tadeusz Balcer
 
Introduction to Erlang Programming Language
Introduction to Erlang Programming LanguageIntroduction to Erlang Programming Language
Introduction to Erlang Programming LanguageYasas Gunarathne
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programmingsamthemonad
 
Knowledge of Javascript
Knowledge of JavascriptKnowledge of Javascript
Knowledge of JavascriptSamuel Abraham
 

Similar to Functional Swift (20)

DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language Fundamentals
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)The Functional Programming Toolkit (NDC Oslo 2019)
The Functional Programming Toolkit (NDC Oslo 2019)
 
Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentals
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Functional programing jargon
Functional programing jargonFunctional programing jargon
Functional programing jargon
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Pure functions and usage in Angular
Pure functions and usage in AngularPure functions and usage in Angular
Pure functions and usage in Angular
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Introduction to Erlang Programming Language
Introduction to Erlang Programming LanguageIntroduction to Erlang Programming Language
Introduction to Erlang Programming Language
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
 
Knowledge of Javascript
Knowledge of JavascriptKnowledge of Javascript
Knowledge of Javascript
 
Introduction to Functional programming
Introduction to Functional programmingIntroduction to Functional programming
Introduction to Functional programming
 

More from Geison Goes

Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataformaGeison Goes
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterGeison Goes
 
Restful design principles
Restful design principlesRestful design principles
Restful design principlesGeison Goes
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasGeison Goes
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGeison Goes
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystemGeison Goes
 

More from Geison Goes (7)

Kotlin multiplataforma
Kotlin multiplataformaKotlin multiplataforma
Kotlin multiplataforma
 
Why companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose FlutterWhy companies like Google, Alibaba and UOL choose Flutter
Why companies like Google, Alibaba and UOL choose Flutter
 
Restful design principles
Restful design principlesRestful design principles
Restful design principles
 
Cucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criteriasCucumber - use it to describe user stories and acceptance criterias
Cucumber - use it to describe user stories and acceptance criterias
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellism
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
 
Python Flavors
Python FlavorsPython Flavors
Python Flavors
 

Recently uploaded

Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilVICTOR MAESTRE RAMIREZ
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLAlluxio, Inc.
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Incrobinwilliams8624
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 

Recently uploaded (20)

Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in Trivandrum
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-Council
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Inc
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 

Functional Swift

  • 2. Geison Goes ● Senior Consultant na Thoughtworks ● Software Engineer for 12 years ● Husband ● Father ● Dog trainer ● Read more at about.me/geisonfgf
  • 3. Functional Swift Functional Programming by Wikipidia: “Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data". In other words, functional programming promotes code with no side effects, no change of value in variables. It oposes to imperative programming, which emphasizes change of state”.
  • 5. What this means? ● No mutable data (no side effect). Functional Swift
  • 6. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. Functional Swift
  • 7. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional Swift
  • 8. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). Functional Swift
  • 9. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”. Functional Swift
  • 10. What this means? ● No mutable data (no side effect). ● No state (no implicit, hidden state). Once assigned (value binding), a variable (a symbol) does not change its value. All state is bad? No, hidden, implicit state is bad. Functional programming do not eliminate state, it just make it visible and explicit (at least when programmers want it to be). ● Functions are pure functions in the mathematical sense: their output depend only in their inputs, there is not “environment”. ● Same result returned by functions called with the same inputs. Functional Swift
  • 11. What are the advantages? Functional Swift
  • 12. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. Functional Swift
  • 13. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it). Functional Swift
  • 14. What are the advantages? ● Cleaner code: "variables" are not modified once defined, so we don't have to follow the change of state to comprehend what a function, a, method, a class, a whole project works. ● Referential transparency: Expressions can be replaced by its values. If we call a function with the same parameters, we know for sure the output will be the same (there is no state anywhere that would change it). There is a reason for which Einstein defined insanity as "doing the same thing over and over again and expecting different results". Functional Swift
  • 15. Advantages enabled by referential transparency Functional Swift
  • 16. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. Functional Swift
  • 17. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. Functional Swift
  • 18. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming. Functional Swift
  • 19. Advantages enabled by referential transparency ● Memoization ○ Cache results for previous function calls. ● Idempotence ○ Same results regardless how many times you call a function. ● Modularization ○ We have no state that pervades the whole code, so we build our project with small, black boxes that we tie together, so it promotes bottom-up programming. ● Ease of debugging ○ Functions are isolated, they only depend on their input and their output, so they are very easy to debug. Functional Swift
  • 20. Advantages enabled by referential transparency ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… Functional Swift
  • 21. Advantages enabled by referential transparency ● Parallelization ○ Functions calls are independent. ○ We can parallelize in different process/CPUs/computers/… We can execute func1 and func2 in parallel because a won’t be modified. let result = func1(a, b) + func2(a, c) Functional Swift
  • 22. Advantages enabled by referential transparency ● Concurrence a. With no shared data, concurrence gets a lot simpler: i. No semaphores. ii. No monitors. iii. No locks. iv. No race-conditions. v. No dead-locks. Functional Swift
  • 24. Immutable Objects ● An OO pattern that was originated in FP world. Functional Swift
  • 25. Immutable Objects ● An OO pattern that was originated in FP world. ● When changing a data structure, don’t modify in place but create a new object. Functional Swift
  • 26. Immutable Objects ● An OO pattern that was originated in FP world. ● When changing a data structure, don’t modify in place but create a new object. ● Name Mutating/nonmutating method pairs consistently. A mutating method will often have a nonmutating variant with similar semantics, but that returns a new value rather than updating an instance in-place. Functional Swift
  • 27. Immutable Objects ● An OO pattern that was originated in FP world. ● When changing a data structure, don’t modify in place but create a new object. ● Name Mutating/nonmutating method pairs consistently. A mutating method will often have a nonmutating variant with similar semantics, but that returns a new value rather than updating an instance in-place. ○ When the operation is naturally described by a verb, use the verb’s imperative for the mutating method and apply the “ed” or “ing” suffix to name its nonmutating counterpart. Functional Swift
  • 28. Functional Swift Ok so let's play a little with functional programming?
  • 29. Don’t Update, Create - String var name = "Geison" var name = name + " Flores" Functional Swift
  • 30. Don’t Update, Create - String var name = "Geison" var name = name + " Flores" let firstname = "Geison" let lastname = "Flores" let name = firstname + " " + lastname Functional Swift
  • 31. Don’t Update, Create - Arrays var years: [Int] = [2001, 2002] years.append(2003) years.append(2004) print(years) // [2001, 2002, 2003, 2004] Functional Swift
  • 32. Don’t Update, Create - Arrays var years: [Int] = [2001, 2002] years.append(2003) years.append(2004) print(years) // [2001, 2002, 2003, 2004] let years: [Int] = [2001, 2001] let allYears = years + [2003] + [2004, 2005] print(allYears) // [2001, 2002, 2003, 2004, 2005] Functional Swift
  • 33. Don’t Update, Create - Dictionaries var ages = ["John": 30] ages["Mary"] = 28 print(ages) // ["Mary": 28, "John": 30] Functional Swift
  • 34. Don’t Update, Create - Dictionaries var ages = ["John": 30] ages["Mary"] = 28 print(ages) // ["Mary": 28, "John": 30] Functional Swift let johnAges = ["John": 30] let maryAges = ["Mary": 28] func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] { var result = lhs rhs.forEach{ result[$0] = $1 } return result } let ages = johnAges + maryAges print(ages) // ["Mary": 28, "John": 30]
  • 35. Higher Order Functions Functions and methods are first-class objects in Swift, so if you want to pass a function to another function, you can just treat it as any other object. typealias callerType = (String, String) -> String func caller(function: callerType) -> Void { let result = function("Hello", "David") print(result) } caller(function: { $0 + " " + $1 }) Functional Swift
  • 36. Higher Order Functions - Map let names = ["milu", "rantanplan"] let namesInUppercase = names.map { $0.uppercased() } print(namesInUppercase) //["MILU", "RANTANPLAN"] Functional Swift
  • 37. Higher Order Functions - Filter let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let oddNumbers = numbers.filter { $0 % 2 != 0 } print(oddNumbers) //[1, 3, 5, 9] Functional Swift
  • 38. Higher Order Functions - Reduce let numbers = [1, 2, 3, 4, 5] let total = numbers.reduce(0, +) print(total) //15 Functional Swift
  • 39. Higher Order Functions - Closure Functional Swift func add_x(_ x: Int) -> ((Int) -> Int) { func add_y(_ y: Int) -> Int { return x + y } return add_y } let add_5 = add_x(5) let add_7 = add_x(7) print(add_5(10)) // result 15 print(add_7(10)) // result 17 print(add_x(2)(3)) // result 5
  • 40. Currying and Partial Functions Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Functional Swift func plus(_ x: Int, _ y: Int) -> Int { return x + y } func partialPlus(_ x: Int) -> ((Int) -> Int) { func partial(_ y: Int) -> Int { return plus(x, y) } return partial } let plus_one = partialPlus(1) print(plus_one(5)) // 6
  • 41. Eager vs Lazy Evaluation Functional Swift
  • 42. Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... Functional Swift
  • 43. Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Functional Swift
  • 44. Eager vs Lazy Evaluation ● Eager evaluation: expressions are calculated at the moment that variables is assined, function called... ● Lazy evaluation: delays the evaluation of the expression until it is needed. ○ Memory efficient: no memory used to store complete structures. ○ CPU efficient: no need to calculate the complete result before returning. ○ Laziness is not a requisite for FP, but it is a strategy that fits nicely on the paradigm(Haskell). Swift have lazy properties and lazy collections. Functional Swift
  • 45. Recursion Looping by calling a function from within itself. When you don’t have access to mutable data, recursion is used to build up and chain data construction. This is because looping is not a functional concept, as it requires variables to be passed around to store the state of the loop at a given time. ● Purely functional languages have no imperative for-loops, so they use recursion a lot. ● If every recursion created an stack, it would blow up very soon. ● Tail-call optimization (TCO) avoids creating a new stack when the last call in a recursion is the function itself. Functional Swift
  • 46. Recursion Imperative: Functional: Functional Swift func fibs(_ n: Int) -> Int { guard n != 0, n != 1 else { return n } return fibs(n - 1) + fibs(n - 2) } print(fibs(6)) //8 func fibs(_ n: Int) -> Int { var tmp = 0 var current = 0 var prev = 1 for i in 1...n { tmp = current current = prev prev = tmp + current } return current } print(fibs(6)) //8
  • 47. A Pratical Example Exercise: "What's the sum of the first 10 natural number whose square value is divisible by 5?" Imperative: Functional: Functional Swift print( Array(1...100) .filter({$0 * $0 % 5 == 0}) .prefix(10) .reduce(0, +) ) //275 func main() -> Void { var n: Int = 1 var numElements: Int = 0 var sum: Int = 0 while numElements < 10 { if n * n % 5 == 0 { sum += n numElements += 1 } n += 1 } print(sum) //275 } main()
  • 49. Conclusion ● As you can see, Swift helps you write in functional style but it doesn’t force you to it. Functional Swift
  • 50. Conclusion ● As you can see, Swift helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. Functional Swift
  • 51. Conclusion ● As you can see, Swift helps you write in functional style but it doesn’t force you to it. ● Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also. ● The main support for FP in Swift comes from the use of closures, pattern matching, lazy evaluation and generics. Functional Swift
  • 52. The last advice Learn at least one functional language, it will open your mind to a new paradigm becoming you a better programmer. Some Functional Languages: ● Haskell ● ML (Standard ML, Objective Caml, ...) ● Scheme ● Erlang ● Scala ● Closure ● F# learnyouahaskell.com Functional Swift
  • 53. Functional Swift OBRIGADO! Email: geisonfgf@gmail.com Skype: geisonfgf Facebook: http://www.facebook.com/geisonfgf Twitter: http://www.twitter.com/geisonfgf