Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming for Rubyst's

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Functional Programming for Rubyst's

Avatar for Oscar Rendón

Oscar Rendón

September 09, 2015
Tweet

More Decks by Oscar Rendón

Other Decks in Programming

Transcript

  1. - Concepts - Immutability/ Side effects - Referential Transparency -

    Concurrency/Parallelism - High Order Functions - Currying - Tail Call/Recursion - more... Agenda
  2. History - Lambda Calculus, 30’s - LISP, 50’s - ML’s,

    70’s - Haskell, 80’s - Elixir, Erlang, Clojure, Scala, Elm, Idris, etc... https://en.wikipedia.org/wiki/Functional_programming
  3. Functional Programming “Functional programming is a programming paradigm that treats

    computation as the evaluation of mathematical functions and avoids state and mutable data” https://en.wikipedia.org/wiki/Functional_programming
  4. State result = func_a(x) + func_b(y) - func_c(z) - No

    State? - Hidden State - Explicit State
  5. Concurrency / Parallelism Just Simpler: - No locks - No

    semaphores - No race conditions - No dead-locks
  6. Currying apply_math = lambda do |fn, a, b| a.send(fn, b)

    end add = apply_math.curry.(:+) subtract = apply_math.curry.(:-) multiply = apply_math.curry.(:*) divide = apply_math.curry.(:/) add.(1, 2)
  7. Recursion - Loops - Recursion - Call Stack - Tail

    Call - Tail Recursion - Tail Call Optimization (TCO)
  8. Factorial def fact(n) factorial = 1 while n > 1

    factorial *= n n -= 1 end factorial end - How vs What - Holding State - Readable?
  9. Factorial def fact(n) return 1 if (0..1).include?(n) n * fact(n-1)

    end - Recursive - Call Stack Error - Not Tail Recursive
  10. Factorial def fact(n, acc=1) return acc if n <= 1

    fact(n-1, n*acc) end - Recursive - Call Stack Error - Tail Recursive
  11. Benchmark require 'benchmark' Benchmark.bm do |x| x.report("eager") do (1..100_000_000).map{ |x|

    x*2 }.take(10) end x.report("lazy") do (1..100_000_000).lazy.map{ |x| x*2 }.take(10).to_a end end