functional programming techniques in regular javascript
TRANSCRIPT
FUNCTIONAL PROGRAMMING TECHNIQUES
IN REGULAR JAVASCRIPT
ABOUT ME
Pavel KlimenkovSenior Software Developer @ Geotab Inc.Oakville, ON, Canada
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
AGENDA•Immutability
•Simple functions
•Not that simple functions
•Combining OOP and FP
•Functors
•Monads
WHAT IS FP?
It’s a declarative programming style where all functions have no side effects and data is readonly.
BTW, SQL is also declarative
1. IMMUTABILITYObjects don’t change their state
Values are constants
IMMUTABILITY
• Use only read-only data
• If something needs to be changed - create new instance instead
EXAMPLE
Convert GPS coordinates to screen points
EXAMPLE: SOURCE DATA
EXAMPLE: CONVERSION
EXAMPLE: MUTABLE DATA
EXAMPLE: IMMUTABLE DATA
EXAMPLE
Edit Entity
EXAMPLE: ENTITY CONSTRUCTOR
EXAMPLE: MUTABLE DATA
EXAMPLE: IMMUTABLE DATA
HOW TO REDUCE TEMPTATION
• Use const or let instead of var
• filter/map/reduce instead of for
• Object.freeze - to prevent object mutation
IMMUTABILITY: PROS• Simpler code
• Less bugs
• Atomic object construction (object is either fully initialised, or doesn’t exist)
• Less temporal coupling (when order of initialisation matters)
• Simpler caching
• Thread safety*
IMMUTABILITY: CONS
• Higher CPU impact (more things to do)
• Higher memory impact (and more GC)
• Higher brain impact (OOP often comes with state)
2. SIMPLE FUNCTIONSFirst class functions
Pure functions
FIRST CLASS FUNCTIONS
Can be passed as arguments
Can be assigned as values
PURE FUNCTIONS• No side-effects
• Depend on arguments only (deterministic)
EXAMPLE: SIDE-EFFECTS
EXAMPLE: NONDETERMINISTIC FUNCTION
EXAMPLE: DETERMINISTIC FUNCTION
SIMPLE FUNCTIONS: PROS• No side-effects
• Less bugs
• Simpler testing
• Simpler code
• Absolute thread safety
SIMPLE FUNCTIONS: CONS
• No side-effects
• Our job is to create side-effects
• IO and Cache are side-effects
3. NOT THAT SIMPLE FUNCTIONSFunctions composition
Functions currying
FUNCTIONS COMPOSITION
Composition - gluing functions together
EXAMPLE: COMPOSITION
EXAMPLE: COMPOSITION
EXAMPLE: COMPOSITION
Two temporary arrays. Oh, the horror!
EXAMPLE: COMPOSITION
One temporary array. Harmony restored.
EXAMPLE: MORE COMPOSITION
EXAMPLE: MORE COMPOSITION
FUNCTIONS CURRYING
Currying - partial application of a function.
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
NOT THAT SIMPLE FUNCTIONS: PROS• Flexibility in using and reusing functions
• Functions tend to be smaller
• Memoization (“Simple functions” PROS list was already too long)
NOT THAT SIMPLE FUNCTIONS: CONS• Sometimes code looks cryptic
• Might introduce negative performance impact
COMBINING OOP AND FPShell - OOP, IO, side-effects
Core - FP, logic, pure functions
Core
Shell
MAIN PRINCIPLES• Imperative shell
• Deals with IO
• Thin layer
MAIN PRINCIPLES• Functional core
• deals with immutable data and pure functions
• contains application logic
EXAMPLE: MOVING VEHICLES
EXAMPLE: MOVING VEHICLES
IO, shell
EXAMPLE: MOVING VEHICLES
Logic, pure functions,
core
SHELL/CORE: PROS
• Main bugs will come from the shell, which is small
• Core is easy to test. Unit tests should be enough
• Shell is the one that needs integration tests (shell is small!)
• Command query responsibility segregation out of the box
SHELL/CORE: CONS• Anything?
FUNCTORSSmart containers for values
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
??? 3.png ???
FUNCTOR• Is a container around some data,
• that knows how to apply functions to that data,
• keeping result in the container
FUNCTOR• Container - array, async, nullable - anything
• Some data - numbers, objects, other functors - anything
• Functions are applied through map()
ARRAY IS A FUNCTOR!
PROMISE IS ALMOST A FUNCTOR!
BACK TO EXAMPLE
.png
USEFUL FUNCTORS• Maybe
• Either
• IO
• Writer
• State
MAYBE - ALMOST LIKE NULLABLE
MAYBE - ALMOST LIKE NULLABLE*
MAYBE - ALMOST LIKE NULLABLE
MAYBE EXAMPLE
MAYBE EXAMPLE
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER ♥ RAILWAY ORIENTED
PROGRAMMING
Right
Left
f(x) g(x) h(x)
Picture and concept are shamelessly borrowed from here
TO BE HONEST…
Traditional Maybe = Just ♥ Nothing
OTHER FUNCTORS
• IO - for… IO
• Writer - for logs
• State - for… state
FUNCTORS: PROS• Convenient control over computation
• Logic and context separation
FUNCTORS: CONS• Steep learning curve
• Temptation to use functors for everything
SKIPPED CHAPTERS• Applicatives
• Monoids
MONADS
MONADS ARE CURSED: EITHER YOU DON’T GET THEM, OR YOU CANT EXPLAIN THEM
EXAMPLE: NESTED ARRAYS
EXAMPLE: NESTED MAYBE
EXAMPLE: NESTED MAYBE
MAYBE WILL BECOME A MONAD IF
MAYBE WILL BECOME A MONAD IF
MAYBE WILL BECOME A MONAD IF
NOW YOU KNOW KUNG FU MONADS
Whoa!
ARRAY WILL BECOME A MONAD IF
ECMAScript gets flatten or flatMap for arrays (soon)
BTW, PROMISE IS ALMOST A MONAD
SUMMARY• Immutability - everything is read-only, less bugs
• Pure functions - no side-effects, less bugs
• Composition, currying - reusing functions
• Functors - separating context and logic
• Monads - smart functors
THANK YOU!
DotsAndBrackets.com
/pasha.klimenkov
/in/pavelklimenkov
slideshare.com/pashaklimenkov
Questions?