SlideShare una empresa de Scribd logo
1 de 59
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

Más contenido relacionado

La actualidad más candente

TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
Patrick John Pacaña
 

La actualidad más candente (20)

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Adding geospatial features to a java web app
Adding geospatial features to a java web appAdding geospatial features to a java web app
Adding geospatial features to a java web app
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
for loop in java
for loop in java for loop in java
for loop in java
 
CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)CSS_Day_Three (W3schools)
CSS_Day_Three (W3schools)
 
Php
PhpPhp
Php
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Design Pattern Cheatsheet
Design Pattern CheatsheetDesign Pattern Cheatsheet
Design Pattern Cheatsheet
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java Developers
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 

Similar a Functional Programming in Swift

Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 

Similar a Functional Programming in Swift (20)

Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java introduction
Java introductionJava introduction
Java introduction
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Functions
FunctionsFunctions
Functions
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
c-programming
c-programmingc-programming
c-programming
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 

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