SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
FUNCTIONALRUBY
FIRST-CLASSFUNCTIONS
You already use these
# Print each number from 1-30 in hexadecimal
(1..30).each do |number|
puts number.to_s(16)
end
FIRST-CLASSFUNCTIONS
Changing the example slightly:
# Create a lambda which prints a number in hexadecimal
puts_in_hex = lambda do |number|
puts number.to_s(16)
end
(1..10).each { |i| puts_in_hex.call(i) }
FIRST-CLASSFUNCTIONS
This can be further simplified:
puts_in_hex = lambda do |number|
puts number.to_s(16)
end
(1..10).each(&puts_in_hex)
ASIDE:THEAMPERSAND
The ampersand indicates that we're working with a block
def use_block(&block)
block.call(2)
end
use_block do |number|
number * 2
end
# => 4
ASIDE:THEAMPERSAND
It also causes a viariable to be interpreted as a block.
def use_block(&block)
block.call(2)
end
multiply_two = lambda do |number|
number * 2
end
use_block(&multiply_two)
# => 4
ASIDE:SYMBOL#TO_PROC
Creates a proc which will call a method on an object
call_to_s = :to_s.to_proc
# Looks something like this...
proc do |obj, *args|
obj.send(:to_s, *args)
end
# Ends up being 10.send(:to_s) or 10.to_s
call_to_s.call(10)
# => "10"
# Ends up being 10.send(:to_s, 16) or 10.to_s(16)
call_to_s.call(10, 16)
# => "a"
ASIDE:SYMBOL#TO_PROC
In a method call, &:sym is a shortcut for :sym.to_proc
def apply_block_to_array_and_print(&block)
yield ['h', 'e', 'll', 'o', ' ', 'fun', 'ctions', '!']
end
apply_block_to_array_and_print(&:join)
# => "hello functions!"
FILTER
Problem: A list needs to be filtered
FILTER
Solution: delete everything else
# Find all of the adverbs in a word list
word_list.each do |item|
word_list.delete(item) unless /ly$/.match(item)
end
FILTER
Better solution: build a new list!
# Find all of the adverbs in a word list
adverbs = []
word_list.each do |item|
adverbs << item if /ly$/.match(item)
end
FILTER
Better yet: use Enumerable#select
# Find all of the adverbs and non-adverbs in a word list
adverbs = word_list.select { |item| /ly$/.match(item) }
not_adverbs = word_list.reject { |item| /ly$/.match(item) }
MAP
Problem: A list needs to have elements modified
MAP
Solution: Overwrite the original list
# Square all of our numbers
(1...numbers.length).each do |index|
numbers[index] **= 2
end
MAP
Better Solution: generate a new list
numbers = [1,2,3,4,5]
squares = []
# Square all of the numbers
numbers.each do |number|
squares << number ** 2
end
MAP
Better yet: use Enumerable#map
numbers = [1, 2, 3, 4, 5]
# Square all of our numbers
squares = numbers.map { |number| number ** 2 }
# Another way we could do it
squares = numbers.each_with_object(2).map(&:**)
REDUCE
Problem: A list needs to be transformed
REDUCE
Solution: Iterate through the list
numbers = [1, 2, 3, 4, 5]
product = 1
# Alter the product iteratively
numbers.each do |number|
product *= number
end
REDUCE
Better solution: Use Enumerable#reduce
numbers = [1, 2, 3, 4, 5]
# Calculate the product of the list members
product = numbers.reduce { |acc,item| acc * item }
# Shorter way to do the same
product = numbers.reduce(&:*)
ZIP
Problem: Two lists need to be intertwined
ZIP
Solution: Overwrite one of the lists
a = [1, 2, 3]
b = [4, 5, 6]
# Intertwine list a with list b
a.each_with_index do |number, index|
a[index] = [number, b[index]]
end
ZIP
Better Solution: use Enumerable#zip
a = [1, 2, 3]
b = [4, 5, 6]
# Intertwine list a with list b
c = a.zip(b)
# => [[1, 4], [2, 5], [3, 6]]
WARNING
Religion ahead!
STATE
Ruby is good at state.
Mutable
Implicit
Hidden
DANGEROUSSTATE
Consider:
given_names = %w(Alice Bob Eve Mallory)
short_names = given_names.select { |name| name.length < 5 }
short_names.each { |name| puts name.upcase! }
given_names[1] # => ???
DANGEROUSSTATE
Consider:
given_names = %w(Alice Bob Eve Mallory)
short_names = given_names.select { |name| name.length < 5 }
short_names.each { |name| puts name.upcase! }
given_names[1] # => "BOB"
DUPTOTHERESCUE?
Maybe Object#dup will help?:
given_names = %w(Alice Bob Eve Mallory)
safe_names = given_names.dup
short_names = safe_names.select { |name| name.length < 5 }
short_names.each { |name| puts name.upcase! }
given_names[1] # => ???
DUPTOTHERESCUE?
Maybe Object#dup will help?:
given_names = %w(Alice Bob Eve Mallory)
safe_names = given_names.dup
short_names = safe_names.select { |name| name.length < 5 }
short_names.each { |name| puts name.upcase! }
given_names[1] # => "BOB"
WELP.
State is difficult to manage and track
Particularly as systems grow in complexity
Things get more difficult with real threads (Rubinius, JRuby)
Avoiding mutable state in most cases avoids this problem.
BATTLINGSTATE
Avoiding state fits well with good style:
Keep methods short and responsible for one thing
Write methods with idempotence in mind
When mutations seem necessary, use more functions
RULES:MADETOBEBROKEN
Ruby exposes state to the programmer in a dangerous way
Once concurrency comes into play, scary dragons emerge
Avoiding mutable state helps, but can be expensive
PAINPOINTS
Sometimes avoiding state doesn't make sense:
Code runs much heavier than it could
Code runs much slower than it otherwise might (GC runs)
PAINMANAGEMENT
We can keep things from getting out of hand!
Keep code which has side-effects to a minimum
Isolate code which produces side-effects
Don't make it easy to mutate state accidentally
QUESTIONS?COMMENTS?

Mais conteúdo relacionado

Mais procurados (20)

Pytho lists
Pytho listsPytho lists
Pytho lists
 
1 functions
1 functions1 functions
1 functions
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
List in Python
List in PythonList in Python
List in Python
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perl
 
Lists
ListsLists
Lists
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
learn you some erlang - chap0 to chap2
learn you some erlang - chap0 to chap2learn you some erlang - chap0 to chap2
learn you some erlang - chap0 to chap2
 
Python list
Python listPython list
Python list
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Data structure in perl
Data structure in perlData structure in perl
Data structure in perl
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
Merging tables using R
Merging tables using R Merging tables using R
Merging tables using R
 
Python PCEP Function Parameters
Python PCEP Function ParametersPython PCEP Function Parameters
Python PCEP Function Parameters
 
5. string
5. string5. string
5. string
 

Destaque

Lehen hezkuntza garaiko oroitzapenak
Lehen hezkuntza garaiko oroitzapenakLehen hezkuntza garaiko oroitzapenak
Lehen hezkuntza garaiko oroitzapenakbashirlazahar
 
Tecnologia web 2.0 juliana ramirez s.
Tecnologia web 2.0 juliana ramirez s.Tecnologia web 2.0 juliana ramirez s.
Tecnologia web 2.0 juliana ramirez s.julianaramsa
 
Finlandiar hezkuntza
Finlandiar hezkuntzaFinlandiar hezkuntza
Finlandiar hezkuntzabashirlazahar
 
Zehaztapen mailak ariketa_
Zehaztapen mailak ariketa_Zehaztapen mailak ariketa_
Zehaztapen mailak ariketa_bashirlazahar
 
Curriculumeko galderak
Curriculumeko galderakCurriculumeko galderak
Curriculumeko galderakbashirlazahar
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
Trabajo de naty y romy
Trabajo de naty y romyTrabajo de naty y romy
Trabajo de naty y romyalejandraesmay
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingKonrad Szydlo
 
Functional Programming, Is It Worth It?
Functional Programming, Is It Worth It?Functional Programming, Is It Worth It?
Functional Programming, Is It Worth It?Andrew Rollins
 
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
 

Destaque (10)

Lehen hezkuntza garaiko oroitzapenak
Lehen hezkuntza garaiko oroitzapenakLehen hezkuntza garaiko oroitzapenak
Lehen hezkuntza garaiko oroitzapenak
 
Tecnologia web 2.0 juliana ramirez s.
Tecnologia web 2.0 juliana ramirez s.Tecnologia web 2.0 juliana ramirez s.
Tecnologia web 2.0 juliana ramirez s.
 
Finlandiar hezkuntza
Finlandiar hezkuntzaFinlandiar hezkuntza
Finlandiar hezkuntza
 
Zehaztapen mailak ariketa_
Zehaztapen mailak ariketa_Zehaztapen mailak ariketa_
Zehaztapen mailak ariketa_
 
Curriculumeko galderak
Curriculumeko galderakCurriculumeko galderak
Curriculumeko galderak
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Trabajo de naty y romy
Trabajo de naty y romyTrabajo de naty y romy
Trabajo de naty y romy
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Functional Programming, Is It Worth It?
Functional Programming, Is It Worth It?Functional Programming, Is It Worth It?
Functional Programming, Is It Worth It?
 
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
 

Semelhante a A Gentle Introduction to Functional Paradigms in Ruby

A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
Monads in Ruby - Victor Zagorodny
Monads in Ruby - Victor ZagorodnyMonads in Ruby - Victor Zagorodny
Monads in Ruby - Victor ZagorodnyRuby Meditation
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesNiranjan Sarade
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Rubyerockendude
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Rubyerockendude
 
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Live Exam Helper
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingThaichor Seng
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Functional Programming and Ruby
Functional Programming and RubyFunctional Programming and Ruby
Functional Programming and RubyPat Shaughnessy
 

Semelhante a A Gentle Introduction to Functional Paradigms in Ruby (20)

A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Monads in Ruby - Victor Zagorodny
Monads in Ruby - Victor ZagorodnyMonads in Ruby - Victor Zagorodny
Monads in Ruby - Victor Zagorodny
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examples
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
F# intro
F# introF# intro
F# intro
 
Functional Programming and Ruby
Functional Programming and RubyFunctional Programming and Ruby
Functional Programming and Ruby
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 

Último

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 

A Gentle Introduction to Functional Paradigms in Ruby

  • 2. FIRST-CLASSFUNCTIONS You already use these # Print each number from 1-30 in hexadecimal (1..30).each do |number| puts number.to_s(16) end
  • 3. FIRST-CLASSFUNCTIONS Changing the example slightly: # Create a lambda which prints a number in hexadecimal puts_in_hex = lambda do |number| puts number.to_s(16) end (1..10).each { |i| puts_in_hex.call(i) }
  • 4. FIRST-CLASSFUNCTIONS This can be further simplified: puts_in_hex = lambda do |number| puts number.to_s(16) end (1..10).each(&puts_in_hex)
  • 5. ASIDE:THEAMPERSAND The ampersand indicates that we're working with a block def use_block(&block) block.call(2) end use_block do |number| number * 2 end # => 4
  • 6. ASIDE:THEAMPERSAND It also causes a viariable to be interpreted as a block. def use_block(&block) block.call(2) end multiply_two = lambda do |number| number * 2 end use_block(&multiply_two) # => 4
  • 7. ASIDE:SYMBOL#TO_PROC Creates a proc which will call a method on an object call_to_s = :to_s.to_proc # Looks something like this... proc do |obj, *args| obj.send(:to_s, *args) end # Ends up being 10.send(:to_s) or 10.to_s call_to_s.call(10) # => "10" # Ends up being 10.send(:to_s, 16) or 10.to_s(16) call_to_s.call(10, 16) # => "a"
  • 8. ASIDE:SYMBOL#TO_PROC In a method call, &:sym is a shortcut for :sym.to_proc def apply_block_to_array_and_print(&block) yield ['h', 'e', 'll', 'o', ' ', 'fun', 'ctions', '!'] end apply_block_to_array_and_print(&:join) # => "hello functions!"
  • 9. FILTER Problem: A list needs to be filtered
  • 10. FILTER Solution: delete everything else # Find all of the adverbs in a word list word_list.each do |item| word_list.delete(item) unless /ly$/.match(item) end
  • 11. FILTER Better solution: build a new list! # Find all of the adverbs in a word list adverbs = [] word_list.each do |item| adverbs << item if /ly$/.match(item) end
  • 12. FILTER Better yet: use Enumerable#select # Find all of the adverbs and non-adverbs in a word list adverbs = word_list.select { |item| /ly$/.match(item) } not_adverbs = word_list.reject { |item| /ly$/.match(item) }
  • 13. MAP Problem: A list needs to have elements modified
  • 14. MAP Solution: Overwrite the original list # Square all of our numbers (1...numbers.length).each do |index| numbers[index] **= 2 end
  • 15. MAP Better Solution: generate a new list numbers = [1,2,3,4,5] squares = [] # Square all of the numbers numbers.each do |number| squares << number ** 2 end
  • 16. MAP Better yet: use Enumerable#map numbers = [1, 2, 3, 4, 5] # Square all of our numbers squares = numbers.map { |number| number ** 2 } # Another way we could do it squares = numbers.each_with_object(2).map(&:**)
  • 17. REDUCE Problem: A list needs to be transformed
  • 18. REDUCE Solution: Iterate through the list numbers = [1, 2, 3, 4, 5] product = 1 # Alter the product iteratively numbers.each do |number| product *= number end
  • 19. REDUCE Better solution: Use Enumerable#reduce numbers = [1, 2, 3, 4, 5] # Calculate the product of the list members product = numbers.reduce { |acc,item| acc * item } # Shorter way to do the same product = numbers.reduce(&:*)
  • 20. ZIP Problem: Two lists need to be intertwined
  • 21. ZIP Solution: Overwrite one of the lists a = [1, 2, 3] b = [4, 5, 6] # Intertwine list a with list b a.each_with_index do |number, index| a[index] = [number, b[index]] end
  • 22. ZIP Better Solution: use Enumerable#zip a = [1, 2, 3] b = [4, 5, 6] # Intertwine list a with list b c = a.zip(b) # => [[1, 4], [2, 5], [3, 6]]
  • 24. STATE Ruby is good at state. Mutable Implicit Hidden
  • 25. DANGEROUSSTATE Consider: given_names = %w(Alice Bob Eve Mallory) short_names = given_names.select { |name| name.length < 5 } short_names.each { |name| puts name.upcase! } given_names[1] # => ???
  • 26. DANGEROUSSTATE Consider: given_names = %w(Alice Bob Eve Mallory) short_names = given_names.select { |name| name.length < 5 } short_names.each { |name| puts name.upcase! } given_names[1] # => "BOB"
  • 27. DUPTOTHERESCUE? Maybe Object#dup will help?: given_names = %w(Alice Bob Eve Mallory) safe_names = given_names.dup short_names = safe_names.select { |name| name.length < 5 } short_names.each { |name| puts name.upcase! } given_names[1] # => ???
  • 28. DUPTOTHERESCUE? Maybe Object#dup will help?: given_names = %w(Alice Bob Eve Mallory) safe_names = given_names.dup short_names = safe_names.select { |name| name.length < 5 } short_names.each { |name| puts name.upcase! } given_names[1] # => "BOB"
  • 29. WELP. State is difficult to manage and track Particularly as systems grow in complexity Things get more difficult with real threads (Rubinius, JRuby) Avoiding mutable state in most cases avoids this problem.
  • 30. BATTLINGSTATE Avoiding state fits well with good style: Keep methods short and responsible for one thing Write methods with idempotence in mind When mutations seem necessary, use more functions
  • 31. RULES:MADETOBEBROKEN Ruby exposes state to the programmer in a dangerous way Once concurrency comes into play, scary dragons emerge Avoiding mutable state helps, but can be expensive
  • 32. PAINPOINTS Sometimes avoiding state doesn't make sense: Code runs much heavier than it could Code runs much slower than it otherwise might (GC runs)
  • 33. PAINMANAGEMENT We can keep things from getting out of hand! Keep code which has side-effects to a minimum Isolate code which produces side-effects Don't make it easy to mutate state accidentally