SlideShare une entreprise Scribd logo
1  sur  33
@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

Contenu connexe

Similaire à The Functional Rubyist: A Primer

Zen and the Art of Code Maintenance
Zen and the Art of Code MaintenanceZen and the Art of Code Maintenance
Zen and the Art of Code MaintenanceJemuel Young
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingLex Sheehan
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987乐群 陈
 
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
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional styleNiranjan Sarade
 

Similaire à The Functional Rubyist: A Primer (20)

Php extensions
Php extensionsPhp extensions
Php extensions
 
Zen and the Art of Code Maintenance
Zen and the Art of Code MaintenanceZen and the Art of Code Maintenance
Zen and the Art of Code Maintenance
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987
 
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
 
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
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 

Dernier

Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Dernier (20)

Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

The Functional Rubyist: A Primer

Notes de l'éditeur

  1. 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
  2. referential transparency: a function without side effects animate red x (examples: upcase vs upcase!; <<)
  3. 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
  4. change text to ruby (more examples: [1,3,5].fetch(2); .fetch(3))
  5. 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)
  6. Holden Caulfield
  7. 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)
  8. 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...
  9. Ingatius J. Reilly
  10. demo find_multiples_of_3 and find_multiples_of_5 For more info on currying and partial function application, see my recent RubyTapas episode
  11. 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
  12. 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.