SlideShare a Scribd company logo
Functional Programming
in Swift
Presented by: Saugat Gautam
What is functional
programming?
Functional Programming
• A programming paradigm that treats computations
as the evaluation of mathematical functions and
avoids changing-state and mutable data. It is
declarative programming paradigm, which means
programming is done with expressions.
Why Functional
Programming?
Why?
• Maintainable code.
• Easier and complete testing.
• Easier parallel and concurrent programming.
Aspects of Functional
Programming
Aspects
• Immutable Data(Values)
• Pure functions
• Higher Order Functions
• Functions as arguments and as return values.
Immutable Data?
Immutable Values benefits
• Values can’t change unexpectedly
• Can be shared without worrying
• Thread safe - Values play well with observers
Example
let firstName = "Saugat"
let lastName = “Gautam"
var middleName = "Kumar"
let numbers = Array(1…10)
firstName.append("D") // Compiler Error
middleName.append("atunga") // All good
//—————————————————————————————————————
struct PersonalInfo {
var firstName: String
var lastName: String
var middleName: String
}
let emp1 = PersonalInfo(firstName: "Saugat", lastName: "Gautam", middleName:
More Benefits
• The Value of Values - Rich Hickey
http://www.infoq.com/presentations/Value-Values
• Controlling Complexity in Swift or Making Friends
with Value- Andy Matuschak
http://realm.io/news/andy-matuschak-controlling-
complexity/
http://www.objc.io/issue-16/swift-classes-vs-
structs.html
Why functional swift?
Why Functional Swift?
• Generics.
• Functional Programming Concept.
• Nice consistent syntax for functions and closures.
Can’t Objective-C do
it?
It can but we probably don’t want to.
Swift Value Types vs
Reference Types
• Value Types:
• Numbers, strings, arrays, dictionaries, enums, tuples, and
structs.
• Reference Types:
• Classes
Value Types
• Single owner
• Copied on assign
• Example
var a = 10
var b = a
// a = 10, b = 5
b = 5
// a = 10, b = 5
Reference Types
• Multiple owners
• Shared on assignment
var a = UIView()
var b = a
// a.alpha = 1, b.alpha = 1
b.alpha = 0
// a.alpha = 0; b.alpha = 0
Pure Functions
Pure Functions
• Same input always results in same output
(Referential Transparency)
• Evaluation of result does not cause any side effect
• eg. No change in database or to I/O devices
• Result value need not depend on all arguments but
it must depend on nothing other than the arguments
Pure Function
func factorial(number: Int) -> Int {
if (number == 1) {
return 1
} else {
return number * factorial(number - 1)
}
}
factorial(6)
Not Pure!!
func naturalSum(numbers:[Int]) -> Int{
var total = 0
for num in numbers {
total = total + num
}
return total
}
func sayHelloTo(name: String) {
println("Hello (name)")
}
Higher Order Functions
• Function as parameter
• Function as return value
Function as Parameter
func average(x: Int, y: Int, f:(Int -> Int)) -> Int{
return (f(x) + f(y))/2
}
let square = {(x: Int) -> Int in return x * x}
average(2, 3, f:square)
Function as Parameter
func average(x: Int, y: Int, f:(Int -> Int) = {x in return x}) -> Int{
return (f(x) + f(y))/2
}
let square = {(x: Int) -> Int in return x * x}
average(2, 3, f:square)
Function as Return
Value
func add(a: Int) -> (Int -> Int) {
return {b in a + b}
}
// partial application
let addThree = add(3)
//
let x3 = xs2.map(addThree)
Functional Tool Box
• Map
• Reduce
• Filter
Functional Tool Box
• Laziness
• Flatmap
• Currying
Functional Toolbox
• Functors, Applicative Functors
• Monads
References:
Functional Programming in Swift
http://www.objc.io/books/
Why is a Monad like a writing desk?
http:www.infoq.com/presentations/Why-is-a-Monad-Like-a-Writing-Desk
Map
Map
• Transforming data
• Normally number of output collections is equal to
input
Map Example for Array<T>
• Produce a list of the squares of the first 10 positive
numbers.
Imperative Approach
let firstTenPositiveIntegers = [Int](1…10)
var firstTenSquares = [Int]()
for number in firstTenPositiveIntegers {
firstTenSquares.append(number*number)
}
println(firstTenSquares)
// [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Problems with Imperative
Approach
• Mixes looping with transformation
• Not declarative
• What if ..
firstTenSquares.append(23)
// [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 23]
Functional Approach
let firstTenPositiveIntegers = [Int](1...10)
let firstTenSquares = firstTenPositiveIntegers.map {$0 * $0}
println(firstTenSquares)
// [1, 4, … , 100]
Benefits of Functional
Approach
• Declarative. States what we want to do. Not how we
want to do it.
• Separates the mechanism(step through and select
each item) from the transformation logic
Filter
Filter
• Transforms the initial collection to some final
collection applying some condition
• Final size may not be equal to initial size
Filter Example for Array<T>
• Requirement:
• Produce a list of even squares of the first 10
positive numbers.
Imperative Approach:
let firstTenPositiveIntegers = [Int](1...10)
var evenSquaresInFirstTen = [Int]()
for number in firstTenPositiveIntegers {
let square = number * number
if (square % 2) == 0 {
evenSquaresInFirstTen.append(square)
}
}
println(evenSquaresInFirstTen)
// [4, 16, 36, 64, 100]
Functional Approach
let firstTenPositiveIntegers = [Int](1…10)
let evenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 * $0}).filter({($0%2) == 0})
println(evenSquaresInFirstTen)
// [4, 16, 36, 64, 100]
Reduce
Reduce
• Transform a collection to a single value
Reduce Example for
Array<T>
• Sum of the even squares in the first 10 positive
numbers?
Imperative Approach
let firstTenPositiveIntegers = [Int](1…10)
var sumOfEvenSquaresInFirstTen = 0
for number in firstTenPositiveIntegers {
let square = number * number
if (square % 2) == 0 {
sumOfEvenSquaresInFirstTen += square
}
}
println(sumOfEvenSquaresInFirstTen)
// 220
Functional Approach
let firstTenPositiveIntegers = [Int](1…10)
let sumOfEvenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 *
.filter({$0 %2 == 0})
.reduce(0, combine: {$0 + $1})
println(sumOfEvenSquaresInFirstTen)
// 220
Functional Approach
let firstTenPositiveIntegers = [Int](1...10)
let sumOfEvenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 * $0}).reduce
println(sumOfEvenSquaresInFirstTen)
// 220
Currying
Currying
• Translating the evaluation of a function that takes
multiple arguments into evaluating a sequence of
functions each with a single argument(partial
application)
Currying example
• Say we have a method that takes two inputs and
add them
func add(a: Int, b: Int) -> Int {
return a + b
}
let sum = add(2, 3) // sum = 5
Currying Example
• Now we want to add 2 to a list of numbers
• Drawbacks
• creating a closure just for passing add with default
value
• difficulty arises in case multiple default values are
needed
let xs = 1...100
let x = xs.map { add($0, 2) } // x = [3, 4, 5, 6, etc]
Currying Example
• Use currying
• Drawbacks
• need of wrapper functions for each integer
func addTwo(a: Int) -> Int {
return add(a, 2)
}
let xs = 1...100
let x = xs2.map(addTwo)
Currying Example
• Use another currying method
func add(a: Int) -> (Int -> Int) {
return {b in a + b}
}
// Using method as a whole;
add(2)(3)
// partial application
let addThree = add(3)
//
let x3 = xs2.map(addThree)
Application
Architecture
How does functional fit in?
Application Architecture
• Cocoa and Cocoa Touch are inherently imperative
• Don’t fight the framework
Infusing functional thinking
into our Cocoa applications?
• Functional Core / Imperative Shell approach
• References
• https://www.destroyallsoftware.com/screencasts/catalog/functional-core-
imperative-shell
• https://speakerdeck.com/jspahrsummers/enemy-of-the-state
Functional Core / Imperative
Shell
• Place application’s core data and logic in immutable
constructs (value types).
• Push state out to the ‘edges’. Represent state as
objects with mutable references to immutable core
constructs.
Benefits
• Allows isolated testing
• Leads to an imperative shell with few conditionals,
making reasoning about the program’s state over
time much easier
UI - Can We Functionalize
the Imperative Shell?
• Not quite there.
Some references worth mentioning.
• Reactive Cocoa
https://github.com/ReactiveCocoa/ReactiveCocoa
• React Native
http://www.reactnative.com
• Functional View Controllers
http://chris.eidhof.nl/posts/functinal-view-controllers.html
Thank You

More Related Content

What's hot (20)

Appium & Robot Framework
Appium & Robot FrameworkAppium & Robot Framework
Appium & Robot Framework
Furkan Ertürk
 
Flutter workshop
Flutter workshopFlutter workshop
Flutter workshop
Vishnu Suresh
 
Native mobile application development with Flutter (Dart)
Native mobile application development with Flutter (Dart)Native mobile application development with Flutter (Dart)
Native mobile application development with Flutter (Dart)
Randal Schwartz
 
introduction to flutter ppt - free download
introduction to flutter ppt - free downloadintroduction to flutter ppt - free download
introduction to flutter ppt - free download
RajatPalankar2
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
Vladimir Parfenov
 
Php ppt
Php pptPhp ppt
Php ppt
Sanmuga Nathan
 
i Operating system
i Operating systemi Operating system
i Operating system
Akhil Kumar
 
Flutter for web
Flutter for web Flutter for web
Flutter for web
rihannakedy
 
Flutter
FlutterFlutter
Flutter
Mohit Sharma
 
Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101
Arif Amirani
 
Introdução ao AngularJS
Introdução ao AngularJSIntrodução ao AngularJS
Introdução ao AngularJS
Rodrigo Branas
 
Flutter introduction
Flutter introductionFlutter introduction
Flutter introduction
Võ Duy Tuấn
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Introduction to flutter's basic concepts
Introduction to flutter's basic conceptsIntroduction to flutter's basic concepts
Introduction to flutter's basic concepts
Kumaresh Chandra Baruri
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
Sergi Martínez
 
Building beautiful apps using google flutter
Building beautiful apps using google flutterBuilding beautiful apps using google flutter
Building beautiful apps using google flutter
Ahmed Abu Eldahab
 
INTRODUCTION TO FLUTTER BASICS.pptx
INTRODUCTION TO FLUTTER BASICS.pptxINTRODUCTION TO FLUTTER BASICS.pptx
INTRODUCTION TO FLUTTER BASICS.pptx
20TUCS033DHAMODHARAK
 
Flutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter applicationFlutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter application
Apoorv Pandey
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
Rajathi-QA
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
Google Developer Students Club NIT Silchar
 
Appium & Robot Framework
Appium & Robot FrameworkAppium & Robot Framework
Appium & Robot Framework
Furkan Ertürk
 
Native mobile application development with Flutter (Dart)
Native mobile application development with Flutter (Dart)Native mobile application development with Flutter (Dart)
Native mobile application development with Flutter (Dart)
Randal Schwartz
 
introduction to flutter ppt - free download
introduction to flutter ppt - free downloadintroduction to flutter ppt - free download
introduction to flutter ppt - free download
RajatPalankar2
 
i Operating system
i Operating systemi Operating system
i Operating system
Akhil Kumar
 
Flutter for web
Flutter for web Flutter for web
Flutter for web
rihannakedy
 
Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101Pune Flutter Presents - Flutter 101
Pune Flutter Presents - Flutter 101
Arif Amirani
 
Introdução ao AngularJS
Introdução ao AngularJSIntrodução ao AngularJS
Introdução ao AngularJS
Rodrigo Branas
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Introduction to flutter's basic concepts
Introduction to flutter's basic conceptsIntroduction to flutter's basic concepts
Introduction to flutter's basic concepts
Kumaresh Chandra Baruri
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
Sergi Martínez
 
Building beautiful apps using google flutter
Building beautiful apps using google flutterBuilding beautiful apps using google flutter
Building beautiful apps using google flutter
Ahmed Abu Eldahab
 
INTRODUCTION TO FLUTTER BASICS.pptx
INTRODUCTION TO FLUTTER BASICS.pptxINTRODUCTION TO FLUTTER BASICS.pptx
INTRODUCTION TO FLUTTER BASICS.pptx
20TUCS033DHAMODHARAK
 
Flutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter applicationFlutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter application
Apoorv Pandey
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
Rajathi-QA
 

Similar to Functional Programming in Swift (20)

Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
Functional go
Functional goFunctional go
Functional go
Geison Goes
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
Tech in Asia ID
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
Functional Paradigm.pptx
Functional Paradigm.pptxFunctional Paradigm.pptx
Functional Paradigm.pptx
FurretMaster
 
Functional programming
Functional programmingFunctional programming
Functional programming
S M Asaduzzaman
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
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
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
Jason Larsen
 
Functional Go
Functional GoFunctional Go
Functional Go
Geison Goes
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
Diego Freniche Brito
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Introductory func prog
Introductory func progIntroductory func prog
Introductory func prog
Oleksandr Khomenko
 
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
Luis Atencio
 
Functional Programming Principles & Patterns
Functional Programming Principles & PatternsFunctional Programming Principles & Patterns
Functional Programming Principles & Patterns
zupzup.org
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
Tech in Asia ID
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
Functional Paradigm.pptx
Functional Paradigm.pptxFunctional Paradigm.pptx
Functional Paradigm.pptx
FurretMaster
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
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
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
Jason Larsen
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
Diego Freniche Brito
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
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
Luis Atencio
 
Functional Programming Principles & Patterns
Functional Programming Principles & PatternsFunctional Programming Principles & Patterns
Functional Programming Principles & Patterns
zupzup.org
 
Ad

Recently uploaded (20)

MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Ad

Functional Programming in Swift

  • 3. Functional Programming • A programming paradigm that treats computations as the evaluation of mathematical functions and avoids changing-state and mutable data. It is declarative programming paradigm, which means programming is done with expressions.
  • 5. Why? • Maintainable code. • Easier and complete testing. • Easier parallel and concurrent programming.
  • 7. Aspects • Immutable Data(Values) • Pure functions • Higher Order Functions • Functions as arguments and as return values.
  • 9. Immutable Values benefits • Values can’t change unexpectedly • Can be shared without worrying • Thread safe - Values play well with observers
  • 10. Example let firstName = "Saugat" let lastName = “Gautam" var middleName = "Kumar" let numbers = Array(1…10) firstName.append("D") // Compiler Error middleName.append("atunga") // All good //————————————————————————————————————— struct PersonalInfo { var firstName: String var lastName: String var middleName: String } let emp1 = PersonalInfo(firstName: "Saugat", lastName: "Gautam", middleName:
  • 11. More Benefits • The Value of Values - Rich Hickey http://www.infoq.com/presentations/Value-Values • Controlling Complexity in Swift or Making Friends with Value- Andy Matuschak http://realm.io/news/andy-matuschak-controlling- complexity/ http://www.objc.io/issue-16/swift-classes-vs- structs.html
  • 13. Why Functional Swift? • Generics. • Functional Programming Concept. • Nice consistent syntax for functions and closures.
  • 14. Can’t Objective-C do it? It can but we probably don’t want to.
  • 15. Swift Value Types vs Reference Types • Value Types: • Numbers, strings, arrays, dictionaries, enums, tuples, and structs. • Reference Types: • Classes
  • 16. Value Types • Single owner • Copied on assign • Example var a = 10 var b = a // a = 10, b = 5 b = 5 // a = 10, b = 5
  • 17. Reference Types • Multiple owners • Shared on assignment var a = UIView() var b = a // a.alpha = 1, b.alpha = 1 b.alpha = 0 // a.alpha = 0; b.alpha = 0
  • 19. Pure Functions • Same input always results in same output (Referential Transparency) • Evaluation of result does not cause any side effect • eg. No change in database or to I/O devices • Result value need not depend on all arguments but it must depend on nothing other than the arguments
  • 20. Pure Function func factorial(number: Int) -> Int { if (number == 1) { return 1 } else { return number * factorial(number - 1) } } factorial(6)
  • 21. Not Pure!! func naturalSum(numbers:[Int]) -> Int{ var total = 0 for num in numbers { total = total + num } return total } func sayHelloTo(name: String) { println("Hello (name)") }
  • 22. Higher Order Functions • Function as parameter • Function as return value
  • 23. Function as Parameter func average(x: Int, y: Int, f:(Int -> Int)) -> Int{ return (f(x) + f(y))/2 } let square = {(x: Int) -> Int in return x * x} average(2, 3, f:square)
  • 24. Function as Parameter func average(x: Int, y: Int, f:(Int -> Int) = {x in return x}) -> Int{ return (f(x) + f(y))/2 } let square = {(x: Int) -> Int in return x * x} average(2, 3, f:square)
  • 25. Function as Return Value func add(a: Int) -> (Int -> Int) { return {b in a + b} } // partial application let addThree = add(3) // let x3 = xs2.map(addThree)
  • 26. Functional Tool Box • Map • Reduce • Filter
  • 27. Functional Tool Box • Laziness • Flatmap • Currying
  • 28. Functional Toolbox • Functors, Applicative Functors • Monads References: Functional Programming in Swift http://www.objc.io/books/ Why is a Monad like a writing desk? http:www.infoq.com/presentations/Why-is-a-Monad-Like-a-Writing-Desk
  • 29. Map
  • 30. Map • Transforming data • Normally number of output collections is equal to input
  • 31. Map Example for Array<T> • Produce a list of the squares of the first 10 positive numbers.
  • 32. Imperative Approach let firstTenPositiveIntegers = [Int](1…10) var firstTenSquares = [Int]() for number in firstTenPositiveIntegers { firstTenSquares.append(number*number) } println(firstTenSquares) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 33. Problems with Imperative Approach • Mixes looping with transformation • Not declarative • What if .. firstTenSquares.append(23) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 23]
  • 34. Functional Approach let firstTenPositiveIntegers = [Int](1...10) let firstTenSquares = firstTenPositiveIntegers.map {$0 * $0} println(firstTenSquares) // [1, 4, … , 100]
  • 35. Benefits of Functional Approach • Declarative. States what we want to do. Not how we want to do it. • Separates the mechanism(step through and select each item) from the transformation logic
  • 37. Filter • Transforms the initial collection to some final collection applying some condition • Final size may not be equal to initial size
  • 38. Filter Example for Array<T> • Requirement: • Produce a list of even squares of the first 10 positive numbers.
  • 39. Imperative Approach: let firstTenPositiveIntegers = [Int](1...10) var evenSquaresInFirstTen = [Int]() for number in firstTenPositiveIntegers { let square = number * number if (square % 2) == 0 { evenSquaresInFirstTen.append(square) } } println(evenSquaresInFirstTen) // [4, 16, 36, 64, 100]
  • 40. Functional Approach let firstTenPositiveIntegers = [Int](1…10) let evenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 * $0}).filter({($0%2) == 0}) println(evenSquaresInFirstTen) // [4, 16, 36, 64, 100]
  • 42. Reduce • Transform a collection to a single value
  • 43. Reduce Example for Array<T> • Sum of the even squares in the first 10 positive numbers?
  • 44. Imperative Approach let firstTenPositiveIntegers = [Int](1…10) var sumOfEvenSquaresInFirstTen = 0 for number in firstTenPositiveIntegers { let square = number * number if (square % 2) == 0 { sumOfEvenSquaresInFirstTen += square } } println(sumOfEvenSquaresInFirstTen) // 220
  • 45. Functional Approach let firstTenPositiveIntegers = [Int](1…10) let sumOfEvenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 * .filter({$0 %2 == 0}) .reduce(0, combine: {$0 + $1}) println(sumOfEvenSquaresInFirstTen) // 220
  • 46. Functional Approach let firstTenPositiveIntegers = [Int](1...10) let sumOfEvenSquaresInFirstTen = firstTenPositiveIntegers.map({$0 * $0}).reduce println(sumOfEvenSquaresInFirstTen) // 220
  • 48. Currying • Translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions each with a single argument(partial application)
  • 49. Currying example • Say we have a method that takes two inputs and add them func add(a: Int, b: Int) -> Int { return a + b } let sum = add(2, 3) // sum = 5
  • 50. Currying Example • Now we want to add 2 to a list of numbers • Drawbacks • creating a closure just for passing add with default value • difficulty arises in case multiple default values are needed let xs = 1...100 let x = xs.map { add($0, 2) } // x = [3, 4, 5, 6, etc]
  • 51. Currying Example • Use currying • Drawbacks • need of wrapper functions for each integer func addTwo(a: Int) -> Int { return add(a, 2) } let xs = 1...100 let x = xs2.map(addTwo)
  • 52. Currying Example • Use another currying method func add(a: Int) -> (Int -> Int) { return {b in a + b} } // Using method as a whole; add(2)(3) // partial application let addThree = add(3) // let x3 = xs2.map(addThree)
  • 54. Application Architecture • Cocoa and Cocoa Touch are inherently imperative • Don’t fight the framework
  • 55. Infusing functional thinking into our Cocoa applications? • Functional Core / Imperative Shell approach • References • https://www.destroyallsoftware.com/screencasts/catalog/functional-core- imperative-shell • https://speakerdeck.com/jspahrsummers/enemy-of-the-state
  • 56. Functional Core / Imperative Shell • Place application’s core data and logic in immutable constructs (value types). • Push state out to the ‘edges’. Represent state as objects with mutable references to immutable core constructs.
  • 57. Benefits • Allows isolated testing • Leads to an imperative shell with few conditionals, making reasoning about the program’s state over time much easier
  • 58. UI - Can We Functionalize the Imperative Shell? • Not quite there. Some references worth mentioning. • Reactive Cocoa https://github.com/ReactiveCocoa/ReactiveCocoa • React Native http://www.reactnative.com • Functional View Controllers http://chris.eidhof.nl/posts/functinal-view-controllers.html