SlideShare a Scribd company logo
1 of 42
Download to read offline
THE FUNCTIONAL 
WAY 
@NATASHATHEROBOT
"functional programming is a 
programming paradigm... that treats 
computation as the evaluation of 
mathematical functions and avoids 
changing-state and mutable data." 
Wikipedia
"A mathematical function is a function 
that when you give it the same 
argument, it will give you the same 
result" - Edx FP101x
▸ computation as the evaluation of mathematical functions 
▸ avoid changing state 
▸ avoid mutable data
Funcitonal Swift Conference: The Functional Way
NO SIDE EFFECTS
let numbers = Array(1...10) 
var total = 0 
func addNumbers() { 
for number in numbers { 
total += number 
} 
}
addNumbers() 
total // 55 
addNumbers() 
total // 110 
addNumbers() 
total // 165
let myNumbers = Array(1...10) 
var total = addNumbers(myNumbers) 
func addNumbers(numbers: [Int]) -> Int { 
// can also be written shorthand as 
// numbers.reduce(0,+) 
return numbers.reduce(0) { (sum, number) in sum + number } 
}
total = addNumbers(myNumbers) // 55 
total = addNumbers(myNumbers) // 55 
total = addNumbers(myNumbers) // 55
import Foundation 
class Gift { 
let recipient: String 
let item: String 
let budget: NSDecimalNumber 
let status: Status 
enum Status: String { 
case Purchased = "Purchased" 
case Wrapped = "Wrapped" 
case Delivered = "Delivered" 
} 
init(recipient: String, 
item: String, 
budget: NSDecimalNumber, 
status: Status) 
{ 
self.recipient = recipient 
self.item = item 
self.budget = budget 
self.status = status 
} 
}
extension Gift { 
func todo() -> String { 
switch status { 
case .Purchased: 
return "Wrap it!" 
case .Wrapped: 
return "Mail it!" 
case .Delivered: 
return "Relax and drink some eggnog :)" 
} 
} 
}
extension Gift { 
func todo(fromStatus status: Status) -> String { 
switch status { 
case .Purchased: 
return "Wrap it!" 
case .Wrapped: 
return "Mail it!" 
case .Delivered: 
return "Relax and drink some eggnog :)" 
} 
} 
}
class GiftTests: XCTestCase { 
func testTodo_Purchased() { 
let gift = Gift( 
recipient: "My Cousin Julie, 
item: "GoldieBlox", 
budget: NSDecimalNumber(double: 20.00), 
status: .Purchased) 
XCTAssertEqual(gift.todo(), "Wrap it!") 
} 
func testTodo_Wrapped() { 
let gift = Gift( 
recipient: "My Cousin Julie", 
item: "GoldieBlox", 
budget: NSDecimalNumber(double: 20.00), 
status: .Wrapped) 
XCTAssertEqual(gift.todo(), "Mail it!") 
} 
func testTodo_Delivered() { 
let gift = Gift( 
recipient: "My Cousin Julie", 
item: "GoldieBlox", 
budget: NSDecimalNumber(double: 20.00), 
status: .Delivered) 
XCTAssertEqual(gift.todo(), "Relax and drink some eggnog :)") 
} 
}
import XCTest 
class GiftTests: XCTestCase { 
let gift = Gift( 
recipient: "My Cousin Tommy", 
item: "Choo Choo Train", 
budget: NSDecimalNumber(double: 20.00), 
status: .Purchased) 
func testTodo_Purchased() { 
XCTAssertEqual(gift.todo(fromStatus: .Purchased), "Wrap it!") 
} 
func testTodo_Wrapped() { 
XCTAssertEqual(gift.todo(fromStatus: .Wrapped), "Mail it!") 
} 
func testTodo_Delivered() { 
XCTAssertEqual(gift.todo(fromStatus: .Delivered), "Relax and drink some eggnog :)") 
} 
}
import XCTest 
class GiftTests: XCTestCase { 
func testTodo_Purchased() { 
XCTAssertEqual(Gift.todo(fromStatus: .Purchased), "Wrap it!") 
} 
func testTodo_Wrapped() { 
XCTAssertEqual(Gift.todo(fromStatus: .Wrapped), "Mail it!") 
} 
func testTodo_Delivered() { 
XCTAssertEqual(Gift.todo(fromStatus: .Delivered), "Relax and drink some eggnog :)") 
} 
}
VALUE TYPES
"Almost all types in Swift are value 
types, including arrays, dictionaries, 
numbers, booleans, tuples, and enums. 
Classes are the exception rather than 
the rule." - Functional Swift Book
NSError *err = nil; 
CGFloat result = [MYArithmetic divide:2.5 by:3.0 error:&err]; 
if (err) { 
NSLog(@"%@", err) 
} else { 
[MYArithmetic doSomethingWithResult:result] 
} 
@nomothetis
enum Result { 
case Success(AnyObject) 
case Failure(NSError) 
} 
@nomothetis
let result = MYArithmetic.divide(2.5, by:3) 
switch result { 
case Success(let quotient): 
doSomethingWithResult(quotient) 
case Failure(let error): 
handleError(error) 
} 
@nomothetis
http://nomothetis.svbtle.com/error-handling-in-swift
CURRYING
func add(x: Int, y: Int) -> Int { 
return x + y 
} 
add(2, 3) // 5
func add(x: Int) -> Int -> Int { 
return { y in return x + y } 
} 
let partialAdd = add(2) 
// let addFunc: (Int -> Int) 
let sum = partialAdd(3) 
// 5 
let arr = [1,2,3] 
let incrementBy2 = arr.map(partialAdd) 
// [3,4,5] 
add(6)(4) 
// 10
func add(#x: Int)(y: Int) -> Int { 
return x + y 
} 
add(x: 2)(y: 3) 
// 5
struct Logger { 
/// Level of log message to aid in the filtering of logs 
enum Level: Int, Printable { 
/// Messages intended only for debug mode 
case Debug = 3 
/// Messages intended to warn of potential errors 
case Warn = 2 
/// Critical error messages 
case Error = 1 
/// Log level to turn off all logging 
case None = 0 
var description: String { 
switch(self) { 
case .Debug: 
return "Debug" 
case .Warn: 
return "Warning" 
case .Error: 
return "Error" 
case .None: 
return "" 
} 
} 
} 
} 
@drewag
extension Logger { 
/// What is the max level to be logged 
/// 
/// Any logs under the given log level will be ignored 
static var logLevel: Level = .Warn 
/// Log a message to the console 
static func log 
(#level: Level) 
(name: String) 
(message: String) -> String 
{ 
if level.rawValue <= Logger.logLevel.rawValue { 
return "(level.description): (name) - (message)" 
} 
return "" 
} 
} 
@drewag
Logger.log(level: .Debug)(name: "MyFunction")(message: "Is this being called?") 
// Debug: MyFunction - Is this being called?
extension Logger { 
/// Logger for debug messages 
static var debug = Logger.log(level: .Debug) 
// static var debug: (name: String) -> (message: String) -> String 
/// Logger for warnings 
static var warn = Logger.log(level: .Warn) 
/// Logger for errors 
static var error = Logger.log(level: .Error) 
} 
@drewag
Logger.logLevel = .Debug 
func myFunctionToDebug() { 
var x = 5 
// do something to x 
Logger.debug(name: "myFunctionToDebug")(message: "x: (x)") 
} 
myFunctionToDebug() 
// Prints: "Debug: myFunctionToDebug - x: 10" 
@drewag
func myFunctionToDebug() { 
var x = 5 
var y = 3 
// do something to x 
// do something to y 
let debugMyFunction = Logger.debug(name: "myFunctionToDebug") 
debugMyFunction(message: "x: (x)") 
debugMyFunction(message: "y: (y)") 
} 
myFunctionToDebug() 
// Prints: "Debug: myFunctionToDebug - x: 10" 
// Prints: "Debug: myFunctionToDebug - y: 13"
http://drewag.me/posts/practical-use-for-curried-functions-in-swift
TYPE-DRIVEN 
DESIGN
func credits(account: Account) -> Int { 
// ask data source for account credits 
return credits 
} 
@FunctionalSwift
typealias Credits = Int 
func credits(account: Account) -> Credits { 
// ask data source for amount of credits 
return amount 
} 
@FunctionalSwift
"One important lesson I've learned is 
that designing the right types for your 
problem is a great way to help the 
compiler debug your program." - 
@wouterswierstra
struct Credits { let amount: Int } 
func credits(account: Account) -> Credits { 
// ask data source for amount of credits 
return Credits(amount: amount) 
} 
@FunctionalSwift
let myCredits = credits(myAccount) 
myCredits + 1 // ERROR 
// Cannot invoke '+' with an argument of type 
// '(Credit, IntegerLiteralConvertable)'
http://www.objc.io/snippets/8.html 
http://www.swiftcast.tv/articles/the-design-of-types
RESOURCES 
▸ Functional Swift Book 
▸ Edx FP101x 
▸ Functional Snippets 
▸ An Introduction to Haskell - Skills Matter 
▸ swiftnews.curated.co
QUESTIONS? 
@NATASHATHEROBOT

More Related Content

What's hot

Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScriptKrisKowal2
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1Robert Pearce
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendSven Efftinge
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Queryitsarsalan
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with JasmineLeon van der Grient
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusTakeshi AKIMA
 

What's hot (20)

Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Javascript
JavascriptJavascript
Javascript
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Js types
Js typesJs types
Js types
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeus
 

Viewers also liked

Test security
Test securityTest security
Test securityrflan2
 
Nociones del derecho civil mapa mental Ana Luisa Linares
Nociones del derecho civil mapa mental Ana Luisa LinaresNociones del derecho civil mapa mental Ana Luisa Linares
Nociones del derecho civil mapa mental Ana Luisa Linaresanaluisalinares
 
Visual tools to design
Visual tools to designVisual tools to design
Visual tools to designRoberta Tassi
 
Coaching Digital Leaders Starts With Your Selfie
Coaching Digital Leaders Starts With Your SelfieCoaching Digital Leaders Starts With Your Selfie
Coaching Digital Leaders Starts With Your SelfiePaul Brown
 
Sales Planning like it’s 1999
Sales Planning like it’s 1999Sales Planning like it’s 1999
Sales Planning like it’s 1999accenture
 
How to Win on the Apple Watch
How to Win on the Apple WatchHow to Win on the Apple Watch
How to Win on the Apple WatchNatasha Murashev
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Natasha Murashev
 
Visual guide to selling software as a service by @prezly
Visual guide to selling software as a service by @prezlyVisual guide to selling software as a service by @prezly
Visual guide to selling software as a service by @prezlyPrezly
 
德國汽車製程
德國汽車製程德國汽車製程
德國汽車製程honan4108
 
Презентация компании ВМЛАБ
Презентация компании ВМЛАБПрезентация компании ВМЛАБ
Презентация компании ВМЛАБSaaS.ru Portal
 
Boost your-oop-with-fp
Boost your-oop-with-fpBoost your-oop-with-fp
Boost your-oop-with-fpUberto Barbini
 
Anticipatory Organization: Accounting and Finance Edition (AOAF)
Anticipatory Organization: Accounting and Finance Edition (AOAF)Anticipatory Organization: Accounting and Finance Edition (AOAF)
Anticipatory Organization: Accounting and Finance Edition (AOAF)Tom Hood, CPA,CITP,CGMA
 
gtFace: Business intelligence (BI - presentation)
gtFace: Business intelligence (BI - presentation)gtFace: Business intelligence (BI - presentation)
gtFace: Business intelligence (BI - presentation)kostienko2
 

Viewers also liked (17)

Test security
Test securityTest security
Test security
 
4033_acosta_lisandro_tp9
4033_acosta_lisandro_tp94033_acosta_lisandro_tp9
4033_acosta_lisandro_tp9
 
Nociones del derecho civil mapa mental Ana Luisa Linares
Nociones del derecho civil mapa mental Ana Luisa LinaresNociones del derecho civil mapa mental Ana Luisa Linares
Nociones del derecho civil mapa mental Ana Luisa Linares
 
Visual tools to design
Visual tools to designVisual tools to design
Visual tools to design
 
Coaching Digital Leaders Starts With Your Selfie
Coaching Digital Leaders Starts With Your SelfieCoaching Digital Leaders Starts With Your Selfie
Coaching Digital Leaders Starts With Your Selfie
 
Sales Planning like it’s 1999
Sales Planning like it’s 1999Sales Planning like it’s 1999
Sales Planning like it’s 1999
 
How to Win on the Apple Watch
How to Win on the Apple WatchHow to Win on the Apple Watch
How to Win on the Apple Watch
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
 
Visual guide to selling software as a service by @prezly
Visual guide to selling software as a service by @prezlyVisual guide to selling software as a service by @prezly
Visual guide to selling software as a service by @prezly
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 
德國汽車製程
德國汽車製程德國汽車製程
德國汽車製程
 
Презентация компании ВМЛАБ
Презентация компании ВМЛАБПрезентация компании ВМЛАБ
Презентация компании ВМЛАБ
 
Boost your-oop-with-fp
Boost your-oop-with-fpBoost your-oop-with-fp
Boost your-oop-with-fp
 
Simple School Lunch Ideas
Simple School Lunch IdeasSimple School Lunch Ideas
Simple School Lunch Ideas
 
Anticipatory Organization: Accounting and Finance Edition (AOAF)
Anticipatory Organization: Accounting and Finance Edition (AOAF)Anticipatory Organization: Accounting and Finance Edition (AOAF)
Anticipatory Organization: Accounting and Finance Edition (AOAF)
 
gtFace: Business intelligence (BI - presentation)
gtFace: Business intelligence (BI - presentation)gtFace: Business intelligence (BI - presentation)
gtFace: Business intelligence (BI - presentation)
 

Similar to Funcitonal Swift Conference: The Functional Way

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveJeff Smith
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 

Similar to Funcitonal Swift Conference: The Functional Way (20)

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Kotlin
KotlinKotlin
Kotlin
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 

More from Natasha Murashev

Digital Nomad: The New Normal
Digital Nomad: The New NormalDigital Nomad: The New Normal
Digital Nomad: The New NormalNatasha Murashev
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POPNatasha Murashev
 
Practical Protocols with Associated Types
Practical Protocols with Associated TypesPractical Protocols with Associated Types
Practical Protocols with Associated TypesNatasha Murashev
 
The Secret Life of a Digital Nomad
The Secret Life of a Digital NomadThe Secret Life of a Digital Nomad
The Secret Life of a Digital NomadNatasha Murashev
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingNatasha Murashev
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupNatasha Murashev
 
The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2Natasha Murashev
 
Unleash the Power of Playgrounds
Unleash the Power of PlaygroundsUnleash the Power of Playgrounds
Unleash the Power of PlaygroundsNatasha Murashev
 
AltConf 2015: Swift Thinking
AltConf 2015: Swift ThinkingAltConf 2015: Swift Thinking
AltConf 2015: Swift ThinkingNatasha Murashev
 
HealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New YearHealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New YearNatasha Murashev
 

More from Natasha Murashev (20)

Digital Nomad: The New Normal
Digital Nomad: The New NormalDigital Nomad: The New Normal
Digital Nomad: The New Normal
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
 
Build Features Not Apps
Build Features Not AppsBuild Features Not Apps
Build Features Not Apps
 
Build Features Not Apps
Build Features Not AppsBuild Features Not Apps
Build Features Not Apps
 
Practical Protocols with Associated Types
Practical Protocols with Associated TypesPractical Protocols with Associated Types
Practical Protocols with Associated Types
 
The Secret Life of a Digital Nomad
The Secret Life of a Digital NomadThe Secret Life of a Digital Nomad
The Secret Life of a Digital Nomad
 
Hello watchOS2
Hello watchOS2 Hello watchOS2
Hello watchOS2
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS Meetup
 
The Swift Architect
The Swift ArchitectThe Swift Architect
The Swift Architect
 
The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2The Zen Guide to WatchOS 2
The Zen Guide to WatchOS 2
 
HealthKit Deep Dive
HealthKit Deep DiveHealthKit Deep Dive
HealthKit Deep Dive
 
Using Parse in Hackathons
Using Parse in HackathonsUsing Parse in Hackathons
Using Parse in Hackathons
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
Hello, WatchKit
Hello, WatchKitHello, WatchKit
Hello, WatchKit
 
Unleash the Power of Playgrounds
Unleash the Power of PlaygroundsUnleash the Power of Playgrounds
Unleash the Power of Playgrounds
 
AltConf 2015: Swift Thinking
AltConf 2015: Swift ThinkingAltConf 2015: Swift Thinking
AltConf 2015: Swift Thinking
 
Swift Thinking
Swift ThinkingSwift Thinking
Swift Thinking
 
Intro To Swift
Intro To SwiftIntro To Swift
Intro To Swift
 
HealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New YearHealthKit: Getting Ready for the New Year
HealthKit: Getting Ready for the New Year
 

Recently uploaded

Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
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
 
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
 
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
 
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
 
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
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
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
 
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
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Incrobinwilliams8624
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
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
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.Sharon Liu
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorShane Coughlan
 

Recently uploaded (20)

Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
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
 
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
 
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
 
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
 
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
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
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
 
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
 
Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Inc
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
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
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS Calculator
 

Funcitonal Swift Conference: The Functional Way

  • 1. THE FUNCTIONAL WAY @NATASHATHEROBOT
  • 2. "functional programming is a programming paradigm... that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data." Wikipedia
  • 3. "A mathematical function is a function that when you give it the same argument, it will give you the same result" - Edx FP101x
  • 4. ▸ computation as the evaluation of mathematical functions ▸ avoid changing state ▸ avoid mutable data
  • 7. let numbers = Array(1...10) var total = 0 func addNumbers() { for number in numbers { total += number } }
  • 8. addNumbers() total // 55 addNumbers() total // 110 addNumbers() total // 165
  • 9. let myNumbers = Array(1...10) var total = addNumbers(myNumbers) func addNumbers(numbers: [Int]) -> Int { // can also be written shorthand as // numbers.reduce(0,+) return numbers.reduce(0) { (sum, number) in sum + number } }
  • 10. total = addNumbers(myNumbers) // 55 total = addNumbers(myNumbers) // 55 total = addNumbers(myNumbers) // 55
  • 11. import Foundation class Gift { let recipient: String let item: String let budget: NSDecimalNumber let status: Status enum Status: String { case Purchased = "Purchased" case Wrapped = "Wrapped" case Delivered = "Delivered" } init(recipient: String, item: String, budget: NSDecimalNumber, status: Status) { self.recipient = recipient self.item = item self.budget = budget self.status = status } }
  • 12. extension Gift { func todo() -> String { switch status { case .Purchased: return "Wrap it!" case .Wrapped: return "Mail it!" case .Delivered: return "Relax and drink some eggnog :)" } } }
  • 13. extension Gift { func todo(fromStatus status: Status) -> String { switch status { case .Purchased: return "Wrap it!" case .Wrapped: return "Mail it!" case .Delivered: return "Relax and drink some eggnog :)" } } }
  • 14. class GiftTests: XCTestCase { func testTodo_Purchased() { let gift = Gift( recipient: "My Cousin Julie, item: "GoldieBlox", budget: NSDecimalNumber(double: 20.00), status: .Purchased) XCTAssertEqual(gift.todo(), "Wrap it!") } func testTodo_Wrapped() { let gift = Gift( recipient: "My Cousin Julie", item: "GoldieBlox", budget: NSDecimalNumber(double: 20.00), status: .Wrapped) XCTAssertEqual(gift.todo(), "Mail it!") } func testTodo_Delivered() { let gift = Gift( recipient: "My Cousin Julie", item: "GoldieBlox", budget: NSDecimalNumber(double: 20.00), status: .Delivered) XCTAssertEqual(gift.todo(), "Relax and drink some eggnog :)") } }
  • 15. import XCTest class GiftTests: XCTestCase { let gift = Gift( recipient: "My Cousin Tommy", item: "Choo Choo Train", budget: NSDecimalNumber(double: 20.00), status: .Purchased) func testTodo_Purchased() { XCTAssertEqual(gift.todo(fromStatus: .Purchased), "Wrap it!") } func testTodo_Wrapped() { XCTAssertEqual(gift.todo(fromStatus: .Wrapped), "Mail it!") } func testTodo_Delivered() { XCTAssertEqual(gift.todo(fromStatus: .Delivered), "Relax and drink some eggnog :)") } }
  • 16. import XCTest class GiftTests: XCTestCase { func testTodo_Purchased() { XCTAssertEqual(Gift.todo(fromStatus: .Purchased), "Wrap it!") } func testTodo_Wrapped() { XCTAssertEqual(Gift.todo(fromStatus: .Wrapped), "Mail it!") } func testTodo_Delivered() { XCTAssertEqual(Gift.todo(fromStatus: .Delivered), "Relax and drink some eggnog :)") } }
  • 18. "Almost all types in Swift are value types, including arrays, dictionaries, numbers, booleans, tuples, and enums. Classes are the exception rather than the rule." - Functional Swift Book
  • 19. NSError *err = nil; CGFloat result = [MYArithmetic divide:2.5 by:3.0 error:&err]; if (err) { NSLog(@"%@", err) } else { [MYArithmetic doSomethingWithResult:result] } @nomothetis
  • 20. enum Result { case Success(AnyObject) case Failure(NSError) } @nomothetis
  • 21. let result = MYArithmetic.divide(2.5, by:3) switch result { case Success(let quotient): doSomethingWithResult(quotient) case Failure(let error): handleError(error) } @nomothetis
  • 24. func add(x: Int, y: Int) -> Int { return x + y } add(2, 3) // 5
  • 25. func add(x: Int) -> Int -> Int { return { y in return x + y } } let partialAdd = add(2) // let addFunc: (Int -> Int) let sum = partialAdd(3) // 5 let arr = [1,2,3] let incrementBy2 = arr.map(partialAdd) // [3,4,5] add(6)(4) // 10
  • 26. func add(#x: Int)(y: Int) -> Int { return x + y } add(x: 2)(y: 3) // 5
  • 27. struct Logger { /// Level of log message to aid in the filtering of logs enum Level: Int, Printable { /// Messages intended only for debug mode case Debug = 3 /// Messages intended to warn of potential errors case Warn = 2 /// Critical error messages case Error = 1 /// Log level to turn off all logging case None = 0 var description: String { switch(self) { case .Debug: return "Debug" case .Warn: return "Warning" case .Error: return "Error" case .None: return "" } } } } @drewag
  • 28. extension Logger { /// What is the max level to be logged /// /// Any logs under the given log level will be ignored static var logLevel: Level = .Warn /// Log a message to the console static func log (#level: Level) (name: String) (message: String) -> String { if level.rawValue <= Logger.logLevel.rawValue { return "(level.description): (name) - (message)" } return "" } } @drewag
  • 29. Logger.log(level: .Debug)(name: "MyFunction")(message: "Is this being called?") // Debug: MyFunction - Is this being called?
  • 30. extension Logger { /// Logger for debug messages static var debug = Logger.log(level: .Debug) // static var debug: (name: String) -> (message: String) -> String /// Logger for warnings static var warn = Logger.log(level: .Warn) /// Logger for errors static var error = Logger.log(level: .Error) } @drewag
  • 31. Logger.logLevel = .Debug func myFunctionToDebug() { var x = 5 // do something to x Logger.debug(name: "myFunctionToDebug")(message: "x: (x)") } myFunctionToDebug() // Prints: "Debug: myFunctionToDebug - x: 10" @drewag
  • 32. func myFunctionToDebug() { var x = 5 var y = 3 // do something to x // do something to y let debugMyFunction = Logger.debug(name: "myFunctionToDebug") debugMyFunction(message: "x: (x)") debugMyFunction(message: "y: (y)") } myFunctionToDebug() // Prints: "Debug: myFunctionToDebug - x: 10" // Prints: "Debug: myFunctionToDebug - y: 13"
  • 35. func credits(account: Account) -> Int { // ask data source for account credits return credits } @FunctionalSwift
  • 36. typealias Credits = Int func credits(account: Account) -> Credits { // ask data source for amount of credits return amount } @FunctionalSwift
  • 37. "One important lesson I've learned is that designing the right types for your problem is a great way to help the compiler debug your program." - @wouterswierstra
  • 38. struct Credits { let amount: Int } func credits(account: Account) -> Credits { // ask data source for amount of credits return Credits(amount: amount) } @FunctionalSwift
  • 39. let myCredits = credits(myAccount) myCredits + 1 // ERROR // Cannot invoke '+' with an argument of type // '(Credit, IntegerLiteralConvertable)'
  • 41. RESOURCES ▸ Functional Swift Book ▸ Edx FP101x ▸ Functional Snippets ▸ An Introduction to Haskell - Skills Matter ▸ swiftnews.curated.co