Functional programming principles like higher order functions, immutability and avoiding side effects can help write simpler and more robust programs. Map, filter and reduce are common higher order functions that are useful for transforming collections. Monads are helpful for chaining operations that can fail. Functional programming concepts like these can be applied in languages like Swift to make code more declarative, testable and avoid bugs from side effects. Learning functional programming ideas can provide new perspectives even when not using a purely functional language.
15. Who should get a car upgrade?
4 Angus (27 MPG Cavalier) wants 2014 Ford Fusion
Hybrid [44 MPG]
4 Jessie (17 MPG MDX) wants 2012 Hyundai Santa Fe
[21 MPG]
Who saves more gas?
16. Who is right?
4 (Angus 27->44) 11 MPG difference
4 (Jessie 17->21) 4 MPG difference
17. Who is right?
4 (Angus 27->44)
4 (Jessie 17->21) <- She's right
18. WHY CAN'T YOU TELL?
The math is presented poorly on car dealership stickers
to make larger, more expensive cars seem cheaper than
they are.
20. Why?
Then the number you're counting fits with your intuition,
your mental model of how to think about things
(Angus 3.7 -> 2.4 gal/100) Saving 13 gallons a month
(Jessie 5.9 -> 4.3 gal/100) Saving 16 gallons a month
Jessie was right: The really low MPG of her old SUV
meant there was a lot of low hanging fruit there.
21. Why this car talk in a functional
programming presentation?
Similar to the big number on car stickers, functional
programming presents useful truth, but practioners
bury it beneath unhelpful math presentations
Similar to Jessica's old 17 MPG SUV, if you aren't using
any functional techniques yet, even small
improvements will give you large returns
22. Functional Programming Principles:
4 Be Declarative: Say what you want to do, not how to
do it
4 Be Composable: Make function calls easy to chain
4 Isolate side-effect causing code: Separate out code
that does't change things, often by copying data
instead of changing
23. There are two main flavors of
functional programming
1. Lisp (Clojure, Racket, Scheme, Common Lisp)
2. Typed (Haskell, OCaml, ML)
24. WHERE IS SWIFT! YOU MUST HAVE
LEFT OFF SWIFT?
It's a hybrid language, like Javascript, Objective-C,
Ruby, Scala, Java, etc
It doesn't yet support the full power of all functional
techniques but it does support some of them, which is
why it's even more important to understand the
principles.
25. Because we do not work in a language
that supports full functional style, we
need to know when to stop trying
Discretion: Know when to get the gains and when to not
worry it's not doing what you want and just be
imperative
26. And while some people are
doing some things that are
functional in Swift, many
many people are just doing
rando things
27. 35 different "MAH NEW CUSTUM
OPERATARS!1!!! >>>> #$ !??=="
Not trying to make fun of people's joy...but that's
4 Not drawing on the rich history of the ideas that
swift brings to the table...most of which are from
somewhere else
4 Of questionable longterm utility: you're not going to
have 35 custom operators in a iOS app
28. Go somewhere where
functional is the default
way to program and learn
Spanish immersion program for
programming languages
32. What does a lisp look like:
(defn gal-per-100-mi [mpg]
(->> mpg (/ 1.0) (* 100)))
(println (str (gal-per-100-mi 17) " gal/100"))
Clojure
33. What does Clojure (a Lisp) taste like
4 Extremely small syntax
4 Good imperative language to write functional code in
4 Composition is easy
4 Optional typing (annotations)
4 Productive to code in
4 Superb interoperability with the hosting language
34. What does Clojure taste like
4 Everything is very similar to everything else
4 Easy deployment, easy interop
4 Great happy community
4 Declare what you want, half the time you have to
write only a few lines to get it
4 Great deployment story
4 It's the Caribbean Adventure of programming
35. Important Clojure (or any Lisp) lesson
4 Programs that are little more than interpreters for
data structures made up arrays and dictionaries are
extremely easy to write and maintain and are pretty
compact
4 That is: Data is more important than code
36. Important Clojure lesson
4 You can orthoganalize a program far far far further
than people attempt to in typical iOS developement
37. Important Clojure lesson
4 By making parts of a program self similar
(homoiconic is the math term), you can easily use any
part of the system with any other part
(composability)
38. Important Clojure lesson
4 Clearly separate code that changes state from code
that doesn't (side-effect free functions)
4 Side-effect free functions are criminally easy to test
39. Important Clojure lesson
4 The tools of functional programming require you to
think in a far more stack based, stateless way.
4 Almost all programmers will write better code with a
few weeks to a month of using it
40. Important Clojure lessons
4 Object Oriented code has a lot of boilerplate and
marshalling of data you don't realize until it's not
there
43. Purely Functional TV
4 "I dunno nuthin" to data-
driven programming x
4 Teaches higher order functions
just like Swift's
4 http://purelyfunctional.tv/
langford
4 Intro Course: $48 $36 (25% off)
4 Intro Course + Web Dev
Course: $72 $54 (25% off)
45. 4 'It eschews "real-world" examples in favor of more
interesting exercises like "assaulting hobbits" and
"tracking glittery vampires"'
4 http://www.braveclojure.com
4 '_why's guide to Clojure'
46. _why brought a playful,
fun tone to Ruby in 2005
Right now, the Clojure community is very welcoming and
positive in a similar vein.
Looking for that sparkle, go take a vacation to Clojure
48. What does a typed language look like:
import Text.Printf
gallonsPer100mi :: Float -> Float
gallonsPer100mi x = (1.0 / x) * 100
main = do
let value = gallonsPer100mi 17.0 ;
printf "%f gal/100n" value
Haskell
49. What does Haskell taste like
4 Very strange
4 Statements have no guarantee of sequence
4 Execution is typically lazy
4 Side-effects "not possible" in most parts of the code
4 Requires some pretty esoteric control structures at
times to do "normal" things (this is where monads
come in)
50. What does Haskell taste like
4 Community loves Modern Algebra, sometimes bad at
explaining without it
4 Powerful type system (GADT)
4 Dependency problems
4 Deployment is getting easier
(https://haskellonheroku.com/tutorial/)
51. Lesson from Haskell
4 You can write invalid state out of your application if
you apply strong enough types that model your
domain well enough. (The provably correct ideal)
52. Lesson from Haskell
4 Exhaustive pattern matching is really really really
worth it (use that swift switch statement folks! [but
not the Objective-C one])
53. Lesson from Haskell
4 Objective C is not the language with the longest time
to profiency
54. Lesson from Haskell
4 Monads are really useful in normal programming
languages to manage failable processess (Monads
are how to import some procedural parts into
Haskell...while still satisfying all the functional
guarantees)
57. College Course [CIS
194]:
4 It's decent and clear
4 Taught over and over and over
again so mature materials for
learning
4 It's just as hard as many
advanced programming classes
though
4 Free on the web
65. Map is a higher order function
//swift
["Bob","Lisa","Meeti"].map({$0.uppercaseString})
//ObjC using robb/Underscore.m on github
@[@"Bob",@"Lisa",@"Meeti"].map(^NSString *(NSString *name){
return name.uppercaseString;
}).unwrap;
becomes ["BOB","LISA","MEETI"]
66. We are mapping all words
to words in the set of all
uppercase letters
Note how I'm declaring what I'm doing
here, not saying how I'm doing it
67. Map replaces:
NSMutableArray* caps = [NSMutableArray new];
for(NSString* name in @[@"Bob",@"Lisa",@"Meeti"]){
[caps addObject:[name uppercaseString]];
}
4 Why is map better than this loop? Because you're not
writing out all the ritualistic boilerplate each time.
4 We're doing only one thing at a time. Later
programmers will be able to follow it better.
68. 4 Using a loop might also be otherwise displaying it on
the screen or calling methods on objects which might
be changing state on the screen. (Bad Us)
NSMutableArray* caps = [NSMutableArray new];
for(NSString* name in @[@"Bob",@"Lisa",@"Meeti"]){
NSString* allCaps = [name uppercaseString];
[caps addObject:allCaps];
[myButtons[name] setTitle:allCaps forControlState: UIControlStateNormal];
}
4 Makes leaky abstractions (this code may behave
unpredictably off the main thread)
69. Without map and the other higher order functions, we are
living in a Portlandia of Code, where all mappings are
artisanally woven with hand-typed loops, on cherry blue
switches, under the influence of 100% pure honduran
Aeropressed coffee. This imbues our code with charming
imperfections
70. That was sarcasm in case that is
unclear.
Doing things like this by hand is very
error prone
71. Just like we didn't build things quickly
until we started using interchangable
parts, we don't make code very reliable
or understandable until we make code
that using repeatable very well
controlled higher order functions that
do our everyday tasks for us
74. Reduce is a higher order function
Obtain a value from a collection according to the passed
in function (think of reducing broth to make a sauce)
["Bob","Lisa","Meeti"].reduce(""){$0 + ", " + $1} // -> "Bob, Lisa, Meeti"`
//again, underscorem
@["Bob",@"Lisa",@"Meeti"].reduce(@"", ^(NSString* x, NSString* y) {
return [NSString stringWithFormat@"%@, %@",x,y];
}).unwrap;
75. Reduce
Turn a collection into a value using the passed in
function
[5, 10, 15].reduce(25){$0+$1} // -> 55`
//again, underscorem
@[@(5),@(10),@(15)].reduce(25, ^(NSNumber* x, NSNumber* y) {
return @(x.integerValue + y.integerValue));
}).unwrap; -> @(55)
77. Filter is a higher order function
Return items which pass the test
[5, 10, 15].filter{($0 % 2)==0}
@[@(5),@(10),@(15)].filter(^BOOL(NSNumber* n) {
return (n.integerValue % 2)==0;
};
These both return an array with just a single 10 in it
78. There are a LOT of general
purpose higher order
functions
But the fun doesn't end with HOFs
80. Monads
4 Are often horribly explained by people who "just got
it they're sure"
4 Are a big poorly understood thing looming over you
when you start Haskell
4 Are not needed in languages (Like ObjC and Swift
(and Clojure)) which have mutable state
81. Monads
4 Are often horribly explained by people who "just got
it they're sure"
4 Are a big poorly understood thing looming over you
when you start Haskell
4 Are not needed in languages (Like ObjC and Swift
(and Clojure)) which have mutable state
82. Monads
4 Monads are a common reasonable way to chain a
certain type of failable event in Haskell
-Remember, Haskell is the moon. Moon has a different
definition of reasonable
4 But they're incredibly useful in non-Haskell
languages too, and worth learning
83. https://github.com/svoisen/SVMaybe
4 Implementation of the "Maybe" monad from Haskell.
Optionals in Swift are related to the Maybe concept.
4 Useful when nil just isn't cutting it...but you're not in
Swift, so no optionals
NSDictionary *person = @{@"name":@"Homer Simpson", @"address":@{@"street":@"123 Fake St", @"city":@"Springfield"}};
NSString *cityString = [[[Maybe(person) whenNothing:Maybe(@"No person.") else:MapMaybe(person, [person objectForKey:@"address"])]
whenNothing:Maybe(@"No address.")] else:MapMaybe(address, [address objectForKey:@"city"])]
whenNothing:Maybe(@"No city.")] justValue];
84. SVMaybe
4 Very wonderful for writing declarative code in
initialization methods
4 Very nice for handling json validation
4 Some of the new swift "if let" functionality also
does this
4 More on this part http://nomothetis.svbtle.com/the-
culmination-part-ii
86. Cyclomatic Complexity
Cyclomatic Complexity is a count of how many code
paths a function has.
It's important because human short term memory only
has 5-8 things it remembers at any one time
You can automatically measure the cyclomatic
complexity of your project by using https://github.com/
terryyin/lizard (Doesn't support Swift yet)
87. Cyclomatic Complexity is a very useful
number
4 It's the lower bound on the number of test data
points required to test the function completely
4 Number of if statements + 1 basically
4 Good number? Lizard says 15
4 Cory Bohon (http://objdev.com/2014/03/measuring-
complexity) says 10.
88. What does CC have to do with FP?
4 Turns out you tend to write really low CC code when
you're using a functional style
4 Most of this falls out of the fact your execution of
actions and specification of which actions to do are
very separated
90. Links of Interest
Clojure Videos: http://purelyfunctional.tv/langford
Clojure Koans: http://clojurekoans.com
Clojure Brave: http://www.braveclojure.com
Haskell Book (Whim.): http://amzn.to/1z33h0q
Haskell Book (Serious): http://amzn.to/1z33aCc
Haskell Course: http://www.seas.upenn.edu/~cis194/
fall14/
91. Sources and References
Every resource recommended in here, and all included
links and these:
Thinking in Clojure (Book)
What is a Monad
Introduction to Haskell
92. Sources and References
Why Functional Programming Matters
Don't be scared of functional programming
The Functional Way Video
You could have invented monads
Functional Principles for OO Development