SlideShare a Scribd company logo
Functional Ruby
Kerry Buckley, 10 November 2011
λ
Lambda calculus
Lambda expressions are composed of
     variables v1, v2, ..., vn, ...
     the abstraction symbols λ and .
     parentheses ( )
The set of lambda expressions, Λ, can be defined recursively:
     1. If x is a variable, then x ∈ Λ
     2. If x is a variable and M ∈ Λ, then (λx.M) ∈ Λ
     3. If M, N ∈ Λ, then (M N) ∈ Λ
Instances of rule 2 are known as abstractions and instances of rule 3 are
known as applications.
Clear?
Clear?

Me neither.
Enumerable

The Enumerable mixin provides collection
classes with several traversal and searching
methods, and with the ability to sort. The
class must provide a method each, which
yields successive members of the collection.
Enumerable
all?                 find         minmax_by
any?                 find_all     none?
chunk                find_index   one?
collect              first        partition
collect_concat       flat_map     reduce
count                grep         reject
cycle                group_by     reverse_each
detect               include?     select
drop                 inject       slice_before
drop_while           map          sort
each_cons            max          sort_by
each_entry           max_by       take
each_slice           member?      take_while
each_with_index      min          to_a
each_with_object     min_by       zip
entries              minmax
Enumerable

If Enumerable#max, min, or sort is used,
the objects in the collection must also
implement a meaningful <=> operator, as
these methods rely on an ordering between
members of the collection.
Better iteration
def crappy_method
  results = []
  @collection.each do |thing|
    results << thing.property
  end
  results
end

def nicer_method
  @collection.map {|a| a.property }
end

def more_concise_method
  @collection.map &:property
end
each or map?

collection.each do |a|
  do_something_with_side_effects(a)
end

another_collection = collection.map {|a| transform(a) }
do…end or {…}?

• do…end for multiple lines
• {…} when chaining
• do…end when there are side-effects
• do…end for control flow
Filtering
def crappy_filter
  matches = []
  @collection.each do |item|
    matches << item if item.something?
  end
  matches
end

def nicer_sum
  @collection.select {|a| a.something? }
end

def more_concise_sum
  @collection.select &:something?
end
Proc objects

palindromic = proc {|s| s == s.reverse }

words = File.read("/usr/share/dict/words").split

words.select &palindromic
  #=> ["A", "a", "aa", "aba", ... "yoy", "Z", "z"]
inject
def crappy_sum
  sum = 0
  @collection.each do |number|
    sum += number
  end
  sum
end

def nicer_sum
  @collection.inject(0) {|a, n| a + n }
end

def more_concise_sum
  @collection.inject &:+
end
Chaining functions
def crappy_sum_of_odd_numbers
  sum = 0
  @collection.each do |number|
    sum += number if number.odd?
  end
  sum
end

def sum_of_odd_numbers_using_inject
  @collection.inject(0) {|a, n| n.odd? ? a + n : a }
end

def sum_of_odd_numbers_using_select_and_inject
  @collection.select(&:odd?).inject(&:+)
end
Synonyms
• collect = map
• inject = reduce
• collect_concat = flat_map
• find = detect
• find_all = select
• to_a = entries
• include? = member?

More Related Content

What's hot (19)

PDF
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Philip Schwarz
 
PDF
Map, Reduce and Filter in Swift
Aleksandras Smirnovas
 
PDF
Lecture 4
Muhammad Fayyaz
 
PDF
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 
PDF
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
PDF
List-based Monadic Computations for Dynamically Typed Languages (Python version)
Wim Vanderbauwhede
 
PDF
Functional Programming and Haskell - TWBR Away Day 2011
Adriano Bonat
 
PDF
On fuctional programming, high order functions, ML
Simone Di Maulo
 
PPTX
Array, string and pointer
Nishant Munjal
 
PPTX
Array and string
prashant chelani
 
PDF
The Functional Programming Triad of fold, scan and iterate
Philip Schwarz
 
PDF
Monad Fact #4
Philip Schwarz
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
PDF
Real World Haskell: Lecture 5
Bryan O'Sullivan
 
PPT
Strings Functions in C Programming
DevoAjit Gupta
 
PDF
Why Haskell Matters
romanandreg
 
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Philip Schwarz
 
ODP
Collections In Scala
Knoldus Inc.
 
PDF
Arrays
Shakila Mahjabin
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Philip Schwarz
 
Map, Reduce and Filter in Swift
Aleksandras Smirnovas
 
Lecture 4
Muhammad Fayyaz
 
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
List-based Monadic Computations for Dynamically Typed Languages (Python version)
Wim Vanderbauwhede
 
Functional Programming and Haskell - TWBR Away Day 2011
Adriano Bonat
 
On fuctional programming, high order functions, ML
Simone Di Maulo
 
Array, string and pointer
Nishant Munjal
 
Array and string
prashant chelani
 
The Functional Programming Triad of fold, scan and iterate
Philip Schwarz
 
Monad Fact #4
Philip Schwarz
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Real World Haskell: Lecture 5
Bryan O'Sullivan
 
Strings Functions in C Programming
DevoAjit Gupta
 
Why Haskell Matters
romanandreg
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Philip Schwarz
 
Collections In Scala
Knoldus Inc.
 

Viewers also liked (8)

PDF
Perspectivas de-mercado-junio-2012
Rankia
 
PDF
RTC Decision- Exclusion of Linda and Fernando Gonzalez from the book of voters
Cong Fernando Gonzalez
 
PPT
Apocalypse In Death Valley 1.1 Maries Dream
Dellyo_82
 
PPTX
The Open Web approach
Tristan Nitot
 
PDF
Presentación junio dexia AM
Rankia
 
PPT
Working with digital technology to enhance inquiry learning | 25 June13
Karen Spencer
 
PDF
Filiere pomme maroc
agrimaroc
 
PPT
KSDE video games in the classroom
Doug Adams
 
Perspectivas de-mercado-junio-2012
Rankia
 
RTC Decision- Exclusion of Linda and Fernando Gonzalez from the book of voters
Cong Fernando Gonzalez
 
Apocalypse In Death Valley 1.1 Maries Dream
Dellyo_82
 
The Open Web approach
Tristan Nitot
 
Presentación junio dexia AM
Rankia
 
Working with digital technology to enhance inquiry learning | 25 June13
Karen Spencer
 
Filiere pomme maroc
agrimaroc
 
KSDE video games in the classroom
Doug Adams
 
Ad

Similar to Functional ruby (20)

ODP
Functional Programming With Scala
Knoldus Inc.
 
PDF
Practical cats
Raymond Tay
 
ODP
Functional programming with Scala
Neelkanth Sachdeva
 
PPTX
Python advance
Deepak Chandella
 
PPTX
Scala collections wizardry - Scalapeño
Sagie Davidovich
 
PPT
MatlabIntro.ppt
ShwetaPandey248972
 
PPT
MatlabIntro.ppt
konkatisandeepkumar
 
PPT
MatlabIntro.ppt
ssuser772830
 
PPT
MatlabIntro.ppt
Rajmohan Madasamy
 
PPT
Matlab intro
THEMASTERBLASTERSVID
 
PDF
Lecture 3
Muhammad Fayyaz
 
PPT
MatlabIntro1234.ppt.....................
RajeshMadarkar
 
PDF
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
PDF
Underscore.js
timourian
 
PDF
Comonads in Haskell
David Overton
 
PDF
Fibonacci Function Gallery - Part 2 - One in a series
Philip Schwarz
 
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
PPT
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
IrlanMalik
 
PPT
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
IrlanMalik
 
ODP
Functors, applicatives, monads
rkaippully
 
Functional Programming With Scala
Knoldus Inc.
 
Practical cats
Raymond Tay
 
Functional programming with Scala
Neelkanth Sachdeva
 
Python advance
Deepak Chandella
 
Scala collections wizardry - Scalapeño
Sagie Davidovich
 
MatlabIntro.ppt
ShwetaPandey248972
 
MatlabIntro.ppt
konkatisandeepkumar
 
MatlabIntro.ppt
ssuser772830
 
MatlabIntro.ppt
Rajmohan Madasamy
 
Matlab intro
THEMASTERBLASTERSVID
 
Lecture 3
Muhammad Fayyaz
 
MatlabIntro1234.ppt.....................
RajeshMadarkar
 
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
Underscore.js
timourian
 
Comonads in Haskell
David Overton
 
Fibonacci Function Gallery - Part 2 - One in a series
Philip Schwarz
 
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
IrlanMalik
 
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
IrlanMalik
 
Functors, applicatives, monads
rkaippully
 
Ad

More from Kerry Buckley (20)

PDF
Jasmine
Kerry Buckley
 
PDF
Testing http calls with Webmock and VCR
Kerry Buckley
 
PDF
BDD with cucumber
Kerry Buckley
 
KEY
Ruby nooks & crannies
Kerry Buckley
 
KEY
TDD refresher
Kerry Buckley
 
KEY
Javasccript MV* frameworks
Kerry Buckley
 
KEY
Tdd for BT E2E test community
Kerry Buckley
 
PDF
7li7w devcon5
Kerry Buckley
 
PDF
What I learned from Seven Languages in Seven Weeks (IPRUG)
Kerry Buckley
 
KEY
Adastral Park code retreat introduction
Kerry Buckley
 
KEY
MongoMapper lightning talk
Kerry Buckley
 
KEY
Ruby
Kerry Buckley
 
KEY
Cloud
Kerry Buckley
 
PDF
The secret life of bees
Kerry Buckley
 
PDF
Background processing
Kerry Buckley
 
PDF
Katas, Contests and Coding Dojos
Kerry Buckley
 
PDF
Rack
Kerry Buckley
 
PDF
Doing REST Right
Kerry Buckley
 
PPT
Kanban and Iterationless Working
Kerry Buckley
 
PPT
Software Development Trends
Kerry Buckley
 
Jasmine
Kerry Buckley
 
Testing http calls with Webmock and VCR
Kerry Buckley
 
BDD with cucumber
Kerry Buckley
 
Ruby nooks & crannies
Kerry Buckley
 
TDD refresher
Kerry Buckley
 
Javasccript MV* frameworks
Kerry Buckley
 
Tdd for BT E2E test community
Kerry Buckley
 
7li7w devcon5
Kerry Buckley
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
Kerry Buckley
 
Adastral Park code retreat introduction
Kerry Buckley
 
MongoMapper lightning talk
Kerry Buckley
 
The secret life of bees
Kerry Buckley
 
Background processing
Kerry Buckley
 
Katas, Contests and Coding Dojos
Kerry Buckley
 
Doing REST Right
Kerry Buckley
 
Kanban and Iterationless Working
Kerry Buckley
 
Software Development Trends
Kerry Buckley
 

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 

Functional ruby

  • 2. λ
  • 3. Lambda calculus Lambda expressions are composed of variables v1, v2, ..., vn, ... the abstraction symbols λ and . parentheses ( ) The set of lambda expressions, Λ, can be defined recursively: 1. If x is a variable, then x ∈ Λ 2. If x is a variable and M ∈ Λ, then (λx.M) ∈ Λ 3. If M, N ∈ Λ, then (M N) ∈ Λ Instances of rule 2 are known as abstractions and instances of rule 3 are known as applications.
  • 6. Enumerable The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.
  • 7. Enumerable all? find minmax_by any? find_all none? chunk find_index one? collect first partition collect_concat flat_map reduce count grep reject cycle group_by reverse_each detect include? select drop inject slice_before drop_while map sort each_cons max sort_by each_entry max_by take each_slice member? take_while each_with_index min to_a each_with_object min_by zip entries minmax
  • 8. Enumerable If Enumerable#max, min, or sort is used, the objects in the collection must also implement a meaningful <=> operator, as these methods rely on an ordering between members of the collection.
  • 9. Better iteration def crappy_method results = [] @collection.each do |thing| results << thing.property end results end def nicer_method @collection.map {|a| a.property } end def more_concise_method @collection.map &:property end
  • 10. each or map? collection.each do |a| do_something_with_side_effects(a) end another_collection = collection.map {|a| transform(a) }
  • 11. do…end or {…}? • do…end for multiple lines • {…} when chaining • do…end when there are side-effects • do…end for control flow
  • 12. Filtering def crappy_filter matches = [] @collection.each do |item| matches << item if item.something? end matches end def nicer_sum @collection.select {|a| a.something? } end def more_concise_sum @collection.select &:something? end
  • 13. Proc objects palindromic = proc {|s| s == s.reverse } words = File.read("/usr/share/dict/words").split words.select &palindromic #=> ["A", "a", "aa", "aba", ... "yoy", "Z", "z"]
  • 14. inject def crappy_sum sum = 0 @collection.each do |number| sum += number end sum end def nicer_sum @collection.inject(0) {|a, n| a + n } end def more_concise_sum @collection.inject &:+ end
  • 15. Chaining functions def crappy_sum_of_odd_numbers sum = 0 @collection.each do |number| sum += number if number.odd? end sum end def sum_of_odd_numbers_using_inject @collection.inject(0) {|a, n| n.odd? ? a + n : a } end def sum_of_odd_numbers_using_select_and_inject @collection.select(&:odd?).inject(&:+) end
  • 16. Synonyms • collect = map • inject = reduce • collect_concat = flat_map • find = detect • find_all = select • to_a = entries • include? = member?

Editor's Notes