2. Agenda
• What is functional programming?
• Swift 101
• Examples of unfunctional to functional code
3. Functional Programming
is a programming paradigm—a style of building the
structure and elements of computer programs—that
treats computation as the evaluation of mathematical
functions and avoids changing-state and mutable
data.
http://en.wikipedia.org/wiki/Functional_programming
5. Key concepts
• First-class and higher-order functions
• Pure functions
• Recursion
• Functional programming in non-functional
languages
http://en.wikipedia.org/wiki/Functional_programming
11. Map
func map<U>(transform: T -> U) -> Array<U>
Return an Array containing the results of calling
`transform(x)` on each element x of self
12. Map on collections
let list = ["c", "d", "a", "b"]
var uppercasedList = [String]()
for char in list {
uppercasedList.append(char.uppercaseString)
}
13. Map on collections
let list = ["c", "d", "a", "b"]
let uppercasedList = list.map ({
(char: String) -> String in
char.uppercaseString
})
14. Map on collections
let list = ["c", "d", "a", "b"]
let uppercasedList = list.map
({$0.uppercaseString})
15. Map on collections
let list = ["c", "d", "a", "b"]
let uppercasedList = list.map
{$0.uppercaseString}
16. FlatMap
func flatMap(transform: T -> [U]) ->[U]
Return an Array containing the results of calling
`transform(x)` on each element x of flattening self
17. FlatMap
let multiList = [["c", "d"], ["a"], ["b"]]
var uppercasedMultiList = multiList
.flatMap{ $0 }
.map {$0.uppercaseString}
18. Map on optionals
func increment(oNumber: Int?) -> Int? {
if let number = oNumber {
return number + 1
} else {
return nil
}
}
increment(10) //11
increment(nil) // nil
19. Map on optionals
func increment(oNumber: Int?) -> Int? {
return oNumber.map { number in number + 1 }
}
increment(10) //11
increment(nil) // nil
21. Reduce
func reduce(initial: U, combine: (U, T) -> U)
-> U
Return the result of repeatedly calling `combine` with
an accumulated value initialised to `initial` and each
element of self
22. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in numbers {
sum += i
}
23. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0, combine: {
(total, number) in
return total + number
})
24. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) {
(total, number) in
return total + number
}
25. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) {
(total, number) in
total + number
}
26. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) { $0 + $1 }
27. Reduce
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0, +}