SlideShare a Scribd company logo
@jleo3
The Functional Rubyist
A primer
@jleo3
joe leo (lucy’s daddy)
twitter/github/linkedin: @jleo3
@jleo3
def
method()
TOGETHER WE WILL BUILD SOMETHING GREAT
@jleo3
@jleo3
DAVID A BLACK
@jleo3
@jleo3
(RUBYISTS / FRIENDS)
@jleo3
@jleo3
a note on purity
Ruby
Java 7
PHP
Lisp
@jleo3
a purely functional language...
...guarantees referential transparency
RUBY DOES NOT
@jleo3
A purely functional
language...
...guarantees immutability
RUBY DOES NOT
@jleo3
{ haskell bullies }
@jleo3
side effects are necessary to do interesting things
● I/O
● raising exceptions
● outputting data to the terminal
● updating a record in a database
● anything else that changes state
@jleo3
what do most people mean when they fp?
Remove side effects!
Curry! Generics! Lazy Evaluation!
Recurse! Tail-call optimize!
@jleo3
where to begin?
@jleo3
let ruby be your guide!
@jleo3
side-effect-free ruby
● String.upcase
● Enumerable.map
● Array.filter
@jleo3
bang! a side effect
● “my string”.upcase!
● [1, 2, 3, 4] << 5
● { x: “ruby” }.fetch(:y)
@jleo3
an example
Student#calculate_grade
def calculate_grade(scores, student)
case scores.sum / scores.size
when 90..100
student.update_grade("A")
when 80...90
student.update_grade("B")
when 70...80
student.update_grade("C")
when 60...70
student.update_grade("D")
else
student.update_grade("F")
end
end
Student#calculate_grade
def calculate_grade(scores)
case scores.sum / scores.size
when 90..100
"A"
when 80...90
"B"
when 70...80
"C"
when 60...70
"D"
else
"F"
end
end
@jleo3
what is currying?
breaking down…
● 1 function with many arguments…
● ...into many functions, each with 1
argument
@jleo3
what is currying?
simple example: add
add = -> (a, b) { a + b } #(1 function, 2 arguments)
curried_add = -> (a) { -> (b){ a + b } } #(2 functions, each with 1 argument)
@jleo3
what is partial function application?
● Pass in a number of arguments less than the function’s arity
● Result: a new function with all of the passed-in arguments
applied
add = -> (a, b) { a + b }
add = -> (5, b) { 5 + b } # partially applied; NOT VALID SYNTAX
@jleo3
but I’m lazy! i don’t want to have to think about
all of that!
● You don’t have to!
● curry handles both currying and
partial function application.
● add.curry
@jleo3
into action with curry and partial function
application
find_multiples = -> (x, arr) {
arr.select { |el| el % x == 0 }
}
@jleo3
Unique IRL; Generic in code
● Functions that return functions
● Building blocks for more
specific functions
● Generics are to FP what
Objects are to OOP
@jleo3
into action with curry and partial function
application
Generic:
find_multiples_of = find_multiples.curry
Individuated:
find_multiples_of_3 = find_multiples_of.call(3)
find_multiples_of_5 = find_multiples_of.call(5)
@jleo3
thinking in streams
Find infinite multiples!
find_first_multiples = -> (num, mult)
{
(1..).lazy.select {
|x| x % mult == 0
}.first(num)
}
@jleo3
recurse!
Writing recursive functions is all about determining the “terminal
clause.”
Popular recursive functions:
● Factorial (terminal clause: x <= 1)
● Fibonacci (terminal clause: x <= 1)
● Sum Squares (terminal clause: x == 0)
@jleo3
VM, optimize thyself!
RubyVM::InstructionSequence.compile_option =
{
tailcall_optimization: true,
trace_instruction: false
}
demystifying tail-call optimization
@jleo3
demystifying tail-call optimization
def factorial(x)
return x if x == 2
x * factorial(x - 1)
end
def factorial(x, acc=1)
return acc if x <= 1
factorial(x - 1, x * acc)
end
(RECURSIVE) (TAIL RECURSIVE)
@jleo3
Where can I learn more?
You guessed it!
@jleo3
Where can I learn more?
But also...
@jleo3
Thank you! Also, get @ me!
- joe leo
- twitter/github/linkedin: @jleo3
- defmethod.com
Thank you to…
- everyone at Rubyconf
- Matz
- Abby and the Program
Committee
- David A. Black

More Related Content

PDF
Дмитрий Щадей "Что помогает нам писать качественный JavaScript-код?"
PDF
How to herd cat statues and make awesome things
PPT
Perl from the ground up: variables and data types
PPT
Perl from the ground up: objects and testing
PDF
Slicing, Dicing, And Linting OpenAPI
PDF
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
PPTX
Peek at PHP 7
PDF
4.2 PHP Function
Дмитрий Щадей "Что помогает нам писать качественный JavaScript-код?"
How to herd cat statues and make awesome things
Perl from the ground up: variables and data types
Perl from the ground up: objects and testing
Slicing, Dicing, And Linting OpenAPI
メタプログラミングRuby輪読会 1-4章(復習), 5.1~5.3章
Peek at PHP 7
4.2 PHP Function

Similar to The Functional Rubyist: A Primer (20)

PDF
Functional programming in ruby
PDF
Ruby Functional Programming
PPTX
Functional programming with Ruby - can make you look smart
PPTX
Functional programming and ruby in functional style
PDF
Fog City Ruby - Triple Equals Black Magic with speaker notes
PDF
Clojure for Rubyists
PPTX
Long Live the Rubyist
PDF
Funtional Ruby - Mikhail Bortnyk
PDF
Functional Ruby
PDF
ScotRuby - Dark side of ruby
PDF
Functional Programming in Ruby
PDF
Functional Objects in Ruby: new horizons – Valentine Ostakh
PDF
On Functional Programming - A Clojurian Perspective
PDF
Functional Programming with Groovy
PPTX
Why learn new programming languages
PPTX
Ruby data types and objects
PDF
CS169 UC Berkeley Armando Fox Ruby basics
PDF
Functional Programming and Ruby
ODP
Clojure: Practical functional approach on JVM
PDF
7li7w devcon5
Functional programming in ruby
Ruby Functional Programming
Functional programming with Ruby - can make you look smart
Functional programming and ruby in functional style
Fog City Ruby - Triple Equals Black Magic with speaker notes
Clojure for Rubyists
Long Live the Rubyist
Funtional Ruby - Mikhail Bortnyk
Functional Ruby
ScotRuby - Dark side of ruby
Functional Programming in Ruby
Functional Objects in Ruby: new horizons – Valentine Ostakh
On Functional Programming - A Clojurian Perspective
Functional Programming with Groovy
Why learn new programming languages
Ruby data types and objects
CS169 UC Berkeley Armando Fox Ruby basics
Functional Programming and Ruby
Clojure: Practical functional approach on JVM
7li7w devcon5
Ad

Recently uploaded (20)

PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Machine Learning_overview_presentation.pptx
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
August Patch Tuesday
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Encapsulation theory and applications.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
1. Introduction to Computer Programming.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Machine Learning_overview_presentation.pptx
TLE Review Electricity (Electricity).pptx
Spectroscopy.pptx food analysis technology
Assigned Numbers - 2025 - Bluetooth® Document
cloud_computing_Infrastucture_as_cloud_p
Programs and apps: productivity, graphics, security and other tools
gpt5_lecture_notes_comprehensive_20250812015547.pdf
A comparative study of natural language inference in Swahili using monolingua...
A comparative analysis of optical character recognition models for extracting...
MIND Revenue Release Quarter 2 2025 Press Release
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
August Patch Tuesday
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
Heart disease approach using modified random forest and particle swarm optimi...
Encapsulation theory and applications.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
1. Introduction to Computer Programming.pptx
Ad

The Functional Rubyist: A Primer

Editor's Notes

  • #10: Insert green checkmarks; swap words for language symbols; animate to show the others one at a time Yes, Ruby is a functional programming language. FP is any language that supports functions. Ruby does this with lambdas and procs Matz was primarily inspired by Lisp when he created Ruby. Also functional. Java does it with closures (since Java 7) PHP supports first-class functions
  • #11: referential transparency: a function without side effects animate red x (examples: upcase vs upcase!; <<)
  • #12: Animate “Ruby does not” But wait! What about Object#freeze? What about frozen strings? At the CRuby freezing an object in Ruby is really just setting a bit. Since the bit can be flipped, it’s not guaranteed immutable
  • #19: change text to ruby (more examples: [1,3,5].fetch(2); .fetch(3))
  • #20: less code because it’s doing less updating a db may happen, but it’s not necessary to update an in-memory object (like an active record object)
  • #21: Holden Caulfield
  • #22: animate: each function, one at a time animate: circle add and curried_add - “these are functionally equivalent” animate: circle 2nd curried_add with note “the ruby way” these are both lambdas (using stabby lambda syntax) they are both valid ruby syntax, as we’ll see curried_add is the curried form of add but you can’t call curried_add the same way (demonstrate)
  • #23: used when we know some, but not all, of a function’s arguments the second line is not valid ruby syntax, but curry achieves the same thing. Which brings me to...
  • #24: Ingatius J. Reilly
  • #27: demo find_multiples_of_3 and find_multiples_of_5 For more info on currying and partial function application, see my recent RubyTapas episode
  • #28: New in Ruby 2.6 you can use the infinite range syntax Float::INFINITY lazy evaluation is not unique to FP, but delayed evaluation is core to functional programming allows us to start thinking in terms of “streams of data” rather than finite sets
  • #31: we can do this without talking about stacks and stack frames! note the accumulator The last line of a tail recursive function is a call to the function itself.