SlideShare a Scribd company logo
1 of 52
Download to read offline
Functional
Programming for
busy OOP
Now with obligatory kitten!
Hello, World!
• Diego Freniche 1
• @dfreniche
• 100% remote dev (iOS / Android)
• writing new bugs @ Mobile Jazz
1
CV: git clone http://www.github.com/dfreniche/cv
BASIC days
• What I've already learnt at
iOSDevUK'16:
• I'm a dinosaur
• We're getting older
• Nostalgia is in the air
GLORY days
• self taught PASCAL before starting
College
• just to find C was the language of choice
• saw several languages: Ada, C, C++
• fell in love with C++ (pre-STL times...)
Wait, am I an imperative
programmer?
• Cursed for life !
• Spoiled by BASIC, C++
• will never get a job in CS. Ever.
Well maybe I can call
myself a REAL OOP
developer
• this book is really hard to read
• I mean, like really hard
• that's only imperative++
Wait, I was taught LISP in
College
• You know:
• Lost In Stupid Parentheses
• Lots of Irritating Superfluous
Parentheses
• ...
F.P.: a new thing, right? !
• invented in the late 50's (1958)
• only ALGOL is older
• derived from the Lambda Calculi
(developed in the 30's)
A word (or two) on LISP
• simplest syntax in ANY programming language
• Code:
(+ 3 2)
• List of data:
'("hello", "world")
A word (or two) on LISP
• homoiconicity: "the structure of
program code is represented faithfully
and directly in a standard data
structure"
• we have direct access to the compiler's
AST
• Much power. So cool. Such compiler.
Wow
• homoiconicity == less syntax to learn
• turn all your fancy { } and [ ] into ( ) and
you get LISP again!
• because I've never used http://
goshdarnblocksyntax.com
Eval: treat data like code, code like data
• Eval: treat data like code, code like data
CL-USER> '(+ 3 4)
(+ 3 4)
CL-USER> (+ 3 4)
7
CL-USER> (eval '(+ 3 4))
7
! https://repl.it/languages/scheme
Ideas piooneered by LISP
• tree data structures
• automatic storage management
• dynamic typing
• conditionals
• higher-order functions
• recursion
• the self-hosting compiler
• REPL: Read Eval Print Loop interpreter
Greenspun's tenth rule 2
Any sufficiently complicated C or Fortran program contains an ad
hoc, informally-specified, bug-ridden, slow implementation of half of
Common Lisp.
2
maybe the NSA, Santa Claus, Zuck and your peers who hate F.P.
F.P. is back!
• Closures & High Order Funcions in Swift. Inmutability. Optionals.
• Blocks in Objective-C to mimic Closures.
• Scala
• C# / F#
• JavaScript?
Being a Functional Language vs. having Functional
Constructs
There's no accepted definition of functional programming language.
_
If you define functional language as the language that supports first class
functions and lambdas, then yes, JavaScript is a functional language.3
3
http://stackoverflow.com/questions/3962604/is-javascript-a-functional-programming-language
Functional Programming
... functional programming is a programming paradigm ... that treats
computation as the evaluation of mathematical functions and
avoids changing-state and mutable data. It is a declarative
programming paradigm,
Functional Programming
... the output value of a function depends only on the arguments
that are input to the function, so calling a function f twice with the
same value for an argument x will produce the same result f(x) each
time eliminating side effects
https://en.wikipedia.org/wiki/Functional_programming
All the talks I've been
before
• Me: "Hi, I'm Diego, need to lose some
weight"
• Someone at the Gym: "No problem, you
can start doing this Arnold lift weigthing
routines from his training to became
Mister Olympia"
• Me: !
All the talks I've been
before
• I know nothing about it, but want to
learn! ☝
• Functors, Monads, Functional purity, etc.
"
• Talks like "Type Check Removal Using Lazy
Interprocedural Code Versioning" #
Why you hate FP?
• Functional programming is declarative
• we were born as imperative
programmers!
• say what you want, not micromanage how
to do it
• you're already doing it! (hating)
• SQL
• CSS
• Regular expressions
OK, Something practical, please?
Inmutability, avoiding state, don't shoot yourself in the
foot
• Value types and immutability
• compiler can optimize your code !
• eats more memory "
• also CPU (making all those copies) "
• this can be optimized
• optimizes programmer's time #
Inmutability
• Diego's constants dumb rule
Declare everything as a constant, let compiler warn you when you're
changing something. That's a variable.
// Java: final everything
final String s = "";
s = "other thing"; // nope
// Swift
let s: String = ""
Inmutability: nice to avoid mistakes
- (void)printAStringReallyStupidBug:(NSString *)aString {
aString = nil; // stupid mistake
// really clever code
// trust me, I know what I'm doing
// in this 300 lines method
NSLog(@"Printing: %@", aString);
}
Inmutability
func removeFromString( _ s: inout String, Character c:Character) -> Int {
var nRemoved = 0
while let ix = s.characters.index(of: c) {
s.removeSubrange(ix...ix)
nRemoved += 1
}
return nRemoved
}
Inmutability: a clear example
- (void)version1 {
NSString *myString = @"iOSDevUK 16";
NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16
[self printAStringAllGood:myString];
NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16
NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16
[self printAStringReallyStupidBug:myString];
NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16
NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16
[self printAStringEvilBug:&myString];
NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16
}
- (void)printAStringAllGood:(NSString *)aString {
NSLog(@"Printing: %@", aString);
}
- (void)printAStringReallyStupidBug:(NSString *)aString {
aString = nil; // stupid mistake
NSLog(@"Printing: %@", aString);
}
- (void)printAStringEvilBug:(NSString **)aString {
*aString = @"HaHa";
NSLog(@"Printing: %@", *aString);
}
Inmutability lessons
• learn to use debug breakpoints
• change your code to call that function
• we can use blocks, function pointers, Swift closures...
• a little tradegy in that backward language
NSString const *myString = @"iOSDevUK 16";
⚠ Sending 'const NSString *__strong' to parameter
of type 'NSString *' discards qualifiers
Inmutability: don't use ++
var i = 0
print("( ++i )")
• direct translation from assembler INC
• does several things at once
• hard to reason about
• nice syntax !
Optionals are not a new thing
• non-optionals are the new thing!
class Person {
var name: String
// compiler ERROR: you can't fool me!
}
Optionals are not a new thing
class Politician: Hyena {
// still compiler ERROR
}
High order functions
• Functions that take functions as
parameters
• Map, Filter, Reduce, Flatmap
• Let's do something with these fruits
Map
• "Do THIS to every single element in the list"
• add 1 to every element in this list
• takes a function (add one) & a list
• returns a list
• with a basket of fruit: peel every fruit in this basket
• think of SQL update
Map example
let basket = ["!", """, "#", "$", "%"]
basket.map { (e: String) -> String in
return "&" + e
}
Map Benefits
• map is a level of indirection
• can be run in parallel (applying a function on element n doesn't
depend on element n+1)
Filter
• "I only want oranges from that basket"
• SQL select WHERE clause
Filter example
• "I only want Apples"
let basket = ["!", """, "#", "$", "%", "&"]
let newBasket = basket.filter { $0 == "!" || $0 == "&"
}
Reduce
• takes a function (add) & a list
• returns just one element
• make multi-fruit juice
• think of AVG function in SQL
Reduce example
let numbers = [1, 2, 3, 4, 5, 6]
numbers.reduce(0, combine: +) --> 21
Flatmap
• Like map, but also "flattens" the list
• some of the fruits in the basket are wrapped with paper
Flatmap example
// how do you add 2 to all the numbers in this array?
let fa2 = [[1,2],[3],[4,5,6]]
let fa2m = fa2.flatMap({$0}).map({$0 + 2})
fa2m
This is from Clean Coding... or not
• Functions should be:
• Small
• Smaller than that
• < 150 chars per line
• < 20 lines
Inject all your parameters
• even if you're using properties from your own class
• makes everything inmediately testable
• no side effects: everything is clear when calling
• you get your own Domain Specific Language to express your
problem
So what?
• you don't need to be an athlete to run
and be healthier
• you don't need to be pure to benefit from
some FP goodness
So what?
• use inmutable structures where possible
• in Java, for example, final everything
• in Swift, prefer structs (value types) vs classes (reference types)
So what?
• map / filter / reduce helps sometimes
• think of it as having SQL at your fingertips
• not everything is a for loop
Use the best of OOP + the best of FP.
Nobody will ever know. 2
2
maybe the NSA, Santa Claus, Zuck and your peers who hate F.P.
Thanks!
• No Trademarks were hurt during the
making of this talk.
• all trademarks belong to their owners, so
please don't sue me.
Additional reading
• A really good post on what F.P. is (with Swift examples!) http://
five.agency/functional-programming-in-swift/
• A parallel map implementation: http://
moreindirection.blogspot.com.es/2015/07/gcd-and-parallel-
collections-in-swift.html

More Related Content

What's hot

Ruby, the language of devops
Ruby, the language of devopsRuby, the language of devops
Ruby, the language of devopsRob Kinyon
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Metosin Oy
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Tim Bunce
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understandingmametter
 
DanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIDanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIPaul Withers
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressiveMilad Arabi
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoMarcus Denker
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with GoSteven Francia
 
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Robert Nelson
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotClouddaoswald
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::Cdaoswald
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noiseNeeraj Bhusare
 
Engage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesEngage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesPaul Withers
 
OpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionOpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionPaul Withers
 

What's hot (20)

Ruby, the language of devops
Ruby, the language of devopsRuby, the language of devops
Ruby, the language of devops
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Clojure in real life 17.10.2014
Clojure in real life 17.10.2014
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understanding
 
DanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIDanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino API
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend Expressive
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
 
Composer Helpdesk
Composer HelpdeskComposer Helpdesk
Composer Helpdesk
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotCloud
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::C
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Engage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesEngage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API Slides
 
OpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview IntroductionOpenNTF Domino API - Overview Introduction
OpenNTF Domino API - Overview Introduction
 

Viewers also liked

Функциональное программирование: мифы и реальность
Функциональное программирование: мифы и реальностьФункциональное программирование: мифы и реальность
Функциональное программирование: мифы и реальностьCUSTIS
 
Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013ScalaNsk
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingJordan Parmer
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Quantum computing - Introduction
Quantum computing - IntroductionQuantum computing - Introduction
Quantum computing - Introductionrushmila
 

Viewers also liked (6)

Функциональное программирование: мифы и реальность
Функциональное программирование: мифы и реальностьФункциональное программирование: мифы и реальность
Функциональное программирование: мифы и реальность
 
Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Quantum computing - Introduction
Quantum computing - IntroductionQuantum computing - Introduction
Quantum computing - Introduction
 

Similar to Functional Programming for Busy Object Oriented Programmers

Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talkReuven Lerner
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
The Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneThe Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneJames Long
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanshipbokonen
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmersamiable_indian
 

Similar to Functional Programming for Busy Object Oriented Programmers (20)

Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
The Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhoneThe Scheme Language -- Using it on the iPhone
The Scheme Language -- Using it on the iPhone
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Lua pitfalls
Lua pitfallsLua pitfalls
Lua pitfalls
 
Linux Shell Scripting Craftsmanship
Linux Shell Scripting CraftsmanshipLinux Shell Scripting Craftsmanship
Linux Shell Scripting Craftsmanship
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt18
ppt18ppt18
ppt18
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
ppt9
ppt9ppt9
ppt9
 

More from Diego Freniche Brito

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfDiego Freniche Brito
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmDiego Freniche Brito
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesDiego Freniche Brito
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkDiego Freniche Brito
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickDiego Freniche Brito
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Diego Freniche Brito
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Diego Freniche Brito
 
Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Diego Freniche Brito
 

More from Diego Freniche Brito (8)

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using Realm
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your libraries
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talk
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013
 
Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013
 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Functional Programming for Busy Object Oriented Programmers

  • 1. Functional Programming for busy OOP Now with obligatory kitten!
  • 2. Hello, World! • Diego Freniche 1 • @dfreniche • 100% remote dev (iOS / Android) • writing new bugs @ Mobile Jazz 1 CV: git clone http://www.github.com/dfreniche/cv
  • 3. BASIC days • What I've already learnt at iOSDevUK'16: • I'm a dinosaur • We're getting older • Nostalgia is in the air
  • 4.
  • 5. GLORY days • self taught PASCAL before starting College • just to find C was the language of choice • saw several languages: Ada, C, C++ • fell in love with C++ (pre-STL times...)
  • 6.
  • 7. Wait, am I an imperative programmer? • Cursed for life ! • Spoiled by BASIC, C++ • will never get a job in CS. Ever.
  • 8. Well maybe I can call myself a REAL OOP developer • this book is really hard to read • I mean, like really hard • that's only imperative++
  • 9. Wait, I was taught LISP in College • You know: • Lost In Stupid Parentheses • Lots of Irritating Superfluous Parentheses • ...
  • 10. F.P.: a new thing, right? ! • invented in the late 50's (1958) • only ALGOL is older • derived from the Lambda Calculi (developed in the 30's)
  • 11. A word (or two) on LISP • simplest syntax in ANY programming language • Code: (+ 3 2) • List of data: '("hello", "world")
  • 12. A word (or two) on LISP • homoiconicity: "the structure of program code is represented faithfully and directly in a standard data structure" • we have direct access to the compiler's AST • Much power. So cool. Such compiler. Wow
  • 13. • homoiconicity == less syntax to learn • turn all your fancy { } and [ ] into ( ) and you get LISP again! • because I've never used http:// goshdarnblocksyntax.com
  • 14. Eval: treat data like code, code like data • Eval: treat data like code, code like data CL-USER> '(+ 3 4) (+ 3 4) CL-USER> (+ 3 4) 7 CL-USER> (eval '(+ 3 4)) 7 ! https://repl.it/languages/scheme
  • 15. Ideas piooneered by LISP • tree data structures • automatic storage management • dynamic typing • conditionals • higher-order functions • recursion • the self-hosting compiler • REPL: Read Eval Print Loop interpreter
  • 16. Greenspun's tenth rule 2 Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. 2 maybe the NSA, Santa Claus, Zuck and your peers who hate F.P.
  • 17. F.P. is back! • Closures & High Order Funcions in Swift. Inmutability. Optionals. • Blocks in Objective-C to mimic Closures. • Scala • C# / F# • JavaScript?
  • 18. Being a Functional Language vs. having Functional Constructs There's no accepted definition of functional programming language. _ If you define functional language as the language that supports first class functions and lambdas, then yes, JavaScript is a functional language.3 3 http://stackoverflow.com/questions/3962604/is-javascript-a-functional-programming-language
  • 19. Functional Programming ... functional programming is a programming paradigm ... that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm,
  • 20. Functional Programming ... the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time eliminating side effects https://en.wikipedia.org/wiki/Functional_programming
  • 21.
  • 22. All the talks I've been before • Me: "Hi, I'm Diego, need to lose some weight" • Someone at the Gym: "No problem, you can start doing this Arnold lift weigthing routines from his training to became Mister Olympia" • Me: !
  • 23. All the talks I've been before • I know nothing about it, but want to learn! ☝ • Functors, Monads, Functional purity, etc. " • Talks like "Type Check Removal Using Lazy Interprocedural Code Versioning" #
  • 24. Why you hate FP? • Functional programming is declarative • we were born as imperative programmers! • say what you want, not micromanage how to do it • you're already doing it! (hating) • SQL • CSS • Regular expressions
  • 26. Inmutability, avoiding state, don't shoot yourself in the foot • Value types and immutability • compiler can optimize your code ! • eats more memory " • also CPU (making all those copies) " • this can be optimized • optimizes programmer's time #
  • 27. Inmutability • Diego's constants dumb rule Declare everything as a constant, let compiler warn you when you're changing something. That's a variable. // Java: final everything final String s = ""; s = "other thing"; // nope // Swift let s: String = ""
  • 28. Inmutability: nice to avoid mistakes - (void)printAStringReallyStupidBug:(NSString *)aString { aString = nil; // stupid mistake // really clever code // trust me, I know what I'm doing // in this 300 lines method NSLog(@"Printing: %@", aString); }
  • 29. Inmutability func removeFromString( _ s: inout String, Character c:Character) -> Int { var nRemoved = 0 while let ix = s.characters.index(of: c) { s.removeSubrange(ix...ix) nRemoved += 1 } return nRemoved }
  • 30. Inmutability: a clear example - (void)version1 { NSString *myString = @"iOSDevUK 16"; NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16 [self printAStringAllGood:myString]; NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16 NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16 [self printAStringReallyStupidBug:myString]; NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16 NSLog(@"myString BEFORE: %@", myString); // BEFORE: iOSDevUK 16 [self printAStringEvilBug:&myString]; NSLog(@"myString AFTER: %@", myString); // AFTER: iOSDevUK 16 } - (void)printAStringAllGood:(NSString *)aString { NSLog(@"Printing: %@", aString); } - (void)printAStringReallyStupidBug:(NSString *)aString { aString = nil; // stupid mistake NSLog(@"Printing: %@", aString); } - (void)printAStringEvilBug:(NSString **)aString { *aString = @"HaHa"; NSLog(@"Printing: %@", *aString); }
  • 31. Inmutability lessons • learn to use debug breakpoints • change your code to call that function • we can use blocks, function pointers, Swift closures... • a little tradegy in that backward language NSString const *myString = @"iOSDevUK 16"; ⚠ Sending 'const NSString *__strong' to parameter of type 'NSString *' discards qualifiers
  • 32. Inmutability: don't use ++ var i = 0 print("( ++i )") • direct translation from assembler INC • does several things at once • hard to reason about • nice syntax !
  • 33. Optionals are not a new thing • non-optionals are the new thing! class Person { var name: String // compiler ERROR: you can't fool me! }
  • 34. Optionals are not a new thing class Politician: Hyena { // still compiler ERROR }
  • 35. High order functions • Functions that take functions as parameters • Map, Filter, Reduce, Flatmap • Let's do something with these fruits
  • 36. Map • "Do THIS to every single element in the list" • add 1 to every element in this list • takes a function (add one) & a list • returns a list • with a basket of fruit: peel every fruit in this basket • think of SQL update
  • 37. Map example let basket = ["!", """, "#", "$", "%"] basket.map { (e: String) -> String in return "&" + e }
  • 38. Map Benefits • map is a level of indirection • can be run in parallel (applying a function on element n doesn't depend on element n+1)
  • 39. Filter • "I only want oranges from that basket" • SQL select WHERE clause
  • 40. Filter example • "I only want Apples" let basket = ["!", """, "#", "$", "%", "&"] let newBasket = basket.filter { $0 == "!" || $0 == "&" }
  • 41. Reduce • takes a function (add) & a list • returns just one element • make multi-fruit juice • think of AVG function in SQL
  • 42. Reduce example let numbers = [1, 2, 3, 4, 5, 6] numbers.reduce(0, combine: +) --> 21
  • 43. Flatmap • Like map, but also "flattens" the list • some of the fruits in the basket are wrapped with paper
  • 44. Flatmap example // how do you add 2 to all the numbers in this array? let fa2 = [[1,2],[3],[4,5,6]] let fa2m = fa2.flatMap({$0}).map({$0 + 2}) fa2m
  • 45. This is from Clean Coding... or not • Functions should be: • Small • Smaller than that • < 150 chars per line • < 20 lines
  • 46. Inject all your parameters • even if you're using properties from your own class • makes everything inmediately testable • no side effects: everything is clear when calling • you get your own Domain Specific Language to express your problem
  • 47. So what? • you don't need to be an athlete to run and be healthier • you don't need to be pure to benefit from some FP goodness
  • 48. So what? • use inmutable structures where possible • in Java, for example, final everything • in Swift, prefer structs (value types) vs classes (reference types)
  • 49. So what? • map / filter / reduce helps sometimes • think of it as having SQL at your fingertips • not everything is a for loop
  • 50. Use the best of OOP + the best of FP. Nobody will ever know. 2 2 maybe the NSA, Santa Claus, Zuck and your peers who hate F.P.
  • 51. Thanks! • No Trademarks were hurt during the making of this talk. • all trademarks belong to their owners, so please don't sue me.
  • 52. Additional reading • A really good post on what F.P. is (with Swift examples!) http:// five.agency/functional-programming-in-swift/ • A parallel map implementation: http:// moreindirection.blogspot.com.es/2015/07/gcd-and-parallel- collections-in-swift.html