SlideShare une entreprise Scribd logo
1  sur  39
Functional Programming (FP)
&
Ruby in Functional style
- Niranjan Sarade
1
Agenda
• WWW of FP
• Spectrum of languages
• OOP and FP
• Imperative vs. Functional
• Examples
• Ruby in a functional style
• References
2
Why FP ?
• Programming has become complex
• Multiprocessors are common place
• Multithreading
• But why?
– Domain is only part of the reason
– We have gone too far with OO programming and
mutable state
3
Perils of Mutable state
• Mutable state
– Leads to more bugs
– Makes concurrency quite difficult
– Shared mutability
4
What’s Old is New again!
5
y = f(x)
6
FP @wikipedia
“In computer science, functional programming is
a programming paradigm that treats
computation as the evaluation of mathematical
functions and avoids state and mutable data. It
emphasizes the application of functions, in
contrast to the imperative programming
style, which emphasizes changes in state.”
7
Spectrum of Languages
Non-functional Hybrid Functional
Java
C++
C#
Ruby
Groovy
Scala
F#
Clojure
Haskell
LISP
Erlang
8
Real world applications of FP
• Erlang: used to implement fault-tolerant
telecommunication system.
• Lisp: used as basis for several applications on
early Apple Macintosh computers.
• Ocaml: use in areas such as financial
analysis, driver verification, industrial robot
programming and static analysis of embedded
software.
9
Continued
• Haskell: aerospace systems, hardware design
and web programming.
• Using the functional ideas, Google has
developed framework called MapReduce for
processing massive amounts of data in
parallel.
• Embedded Lisp interpreters add
programmability to some systems, such as
Emacs.
10
Continued
• Lisp is used for artificial intelligence
applications.
- Knowledge representation
- machine learning
- Natural language processing
- Modeling of speech and vision
11
Principles of FP
• Assignment-less programming
• Immutable state
• Functions as first class citizens
• Higher order functions
• Functions with no side effects
• Referential Transparency
• Lazy evaluation
• Memoization
• Recursion
12
Closure
It is closure because it encloses an environment
that is in place when that code block is instantiated.
def get_adder(value)
proc { |x| x + value }
end
adder5 = get_adder(5) adder10 = get_adder(10)
adder5.call(2) # 7 adder10.call(5) #15
adder5.call(4) # 9 adder10.call(8) #18
13
Immutability /
No side effect
Higher
order Functions
Functional
Style
Ruby
Groovy
Python
Smalltalk
Clojure
Scala
Purely Functional
Haskell
Erlang
Lisp
14
OOP and FP
“OO makes code understandable by
encapsulating moving parts…
FP makes code understandable by minimizing
moving parts.”
- Michael Feathers, author of 'Working with Legacy Code'
15
Imperative vs. Functional
Imperative
Specify each step
How to do stuff
Data mutated
Often has side effect
Accepts data/objects
Hard to compose
Functional
More directive in style
What you want to get
Data transformed
Has no side effect
Accepts functions also
Functional composition
16
Memoization
17
Without memoize
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
fib(35) # slow
#2.879s
18
With memoize
require 'memoize'
# https://github.com/djberg96/memoize
include Memoize
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
memoize(:fib)
fib(35) # fast
# 0.07s
19
Example 1
Squares of Integers
20
Java & Clojure
public class Squint {
public static void main(String args[]) {
for (int i=1; i<=25; i++)
System.out.println(i*i);
}
}
Clojure : (take 25 (squares-of (integers))
(1 2 3 4 5 6 7 8 ...)
(1 4 9 16 25 36 49 64 ...)
(1 4 9 16 25 36 49 64 ... 576 625)
21
Haskell :-
[ x*x | x <- [1..10]]
Ruby :-
(1..10).collect { |x| x*x}
(1..10).map { |x| x*x}
=> [1,4,9,16,25,36,49,64,81, 100]
22
Haskell :-
[ x+1 | x <- [ x*x | x <- [1..10]]]
Ruby :-
(1..10).collect {|x| x*x }.collect {|x| x+1 }
=> [2,5,10,17,26,37,50,65,82,101]
Lazy evaluation:-
take 10 [ x+1 | x <- [ x*x | x <- [1..]]]
23
Lazy evaluation in Ruby 2.0
(0..Float::INFINITY).lazy.map { |x| 2*x }.take(5).to_a
#=> [0, 2, 4, 6, 8]
24
Making an enumerable lazy makes it possible to enumerate infinite
collections.
A lazy enumerable will evaluate the entire chain for each element at a
time, rather than all elements at each stage of the chain.
Example 2
What's the sum of the first 10 natural number
whose square value is divisible by 5?
25
Imperative
Ruby :
n, num_elements, sum = 1, 0, 0
while num_elements < 10
if n**2 % 5 == 0
sum += n
num_elements += 1
end
n += 1
end
sum #=> 275
26
Functional
Ruby 2.0:
Integer::natural.select { |x| x**2 % 5 == 0 }.
take(10).inject(:+)
#=> 275
27
Ruby in a Functional style
28
Everything is an expression
message = “”
if found_dog == our_dog
name = found_dog.name
message = "We found our dog #{name}!"
else
message = "No luck"
end
29
Continued
message = if found_dog == our_dog
"We found our dog #{found_dog.name}!"
else
"No luck"
end
30
Higher-order functions: map
output = []
[1, 2, 3, 4].each do |x|
output << x * 2
end
output # [2, 4, 6, 8]
output = [1, 2, 3, 4].map do |x|
x * 2
end
# [2, 4, 6, 8]
31
Higher-order functions: select
output = []
[1, 2, 3, 4].each do |x|
output << x if x > 2
end
output # [3, 4]
output = [1, 2, 3, 4].select do |x|
x > 2
end
# [3, 4]
32
Higher-order functions: detect
output = nil
[1, 2, 3, 4].each do |x|
if x > 2
output = x
break
end
end
output # 3
output = [1, 2, 3, 4].detect do |x|
x > 2
end # 3
33
Higher-order functions: inject/reduce
total = 0
[1, 2, 3, 4].each do |x|
total += x
end
total # 10
total = [1, 2, 3, 4].inject(0) do |acc, x|
acc + x
end # 10
For simple cases like this:
total = [1, 2, 3, 4].inject(0, :+)
34
Higher-order functions: zip
x = [1, 2, 3]
y = [:a, :b, :c]
output = []
0.upto(x.length - 1).each do |idx|
output << [x[idx], y[idx]]
end
output #=> [[1, :a], [2, :b], [3, :c]]
x = [1, 2, 3]
y = [:a, :b, :c]
output = x.zip(y)
#=> [[1, :a], [2, :b], [3, :c]]
35
Take away
Let’s try to learn at least
One “Functional” Language
and
experience the power of functions !
36
References
• http://en.wikipedia.org/wiki/Functional_programming
• http://pragprog.com/magazines/2013-01/functional-
programming-basics
• http://www.agiledeveloper.com/
• http://www.defmacro.org/ramblings/fp.html
• http://rubysource.com/functional-programming-
techniques-with-ruby-part-i/
• https://code.google.com/p/tokland/wiki/RubyFunction
alProgramming
• http://stackoverflow.com/questions/36504/why-
functional-languages
37
Some Reference videos
• http://vimeo.com/28105411
• http://www.youtube.com/watch?v=8DvxOLzmLSI
• http://www.infoq.com/presentations/Functional-
Programming-A-Pragmatic-Introduction
• http://www.infoq.com/presentations/Are-We-There-
Yet-Rich-Hickey
• http://www.youtube.com/watch?feature=endscreen
&NR=1&v=z0N1aZ6SnBk
38
Thank you all for being patient
and hearing me out.
Hope this helps you!
39

Contenu connexe

Tendances

Python functional programming
Python functional programmingPython functional programming
Python functional programmingGeison Goes
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mindSander Mak (@Sander_Mak)
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Nikos Kalogridis
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionJeongbae Oh
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programmingnewmedio
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScriptAung Baw
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programmingKonrad Szydlo
 
FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)Dierk König
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? reactima
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Dierk König
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++Learn By Watch
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programmingSteve Zhang
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Functional Objects in Ruby: new horizons  – Valentine OstakhFunctional Objects in Ruby: new horizons  – Valentine Ostakh
Functional Objects in Ruby: new horizons – Valentine OstakhRuby Meditation
 

Tendances (20)

Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Some basic FP concepts
Some basic FP conceptsSome basic FP concepts
Some basic FP concepts
 
Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)Functional programing in Javascript (lite intro)
Functional programing in Javascript (lite intro)
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Scala functions
Scala functionsScala functions
Scala functions
 
FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 
Functional Go
Functional GoFunctional Go
Functional Go
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programming
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Functional Objects in Ruby: new horizons  – Valentine OstakhFunctional Objects in Ruby: new horizons  – Valentine Ostakh
Functional Objects in Ruby: new horizons – Valentine Ostakh
 

Similaire à Functional programming and ruby in functional style

Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptTroy Miles
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
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
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
Functional Programming.pptx
Functional Programming.pptxFunctional Programming.pptx
Functional Programming.pptxKarthickT28
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersDiego Freniche Brito
 

Similaire à Functional programming and ruby in functional style (20)

Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
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
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
Functional Programming.pptx
Functional Programming.pptxFunctional Programming.pptx
Functional Programming.pptx
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 

Dernier

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
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...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Functional programming and ruby in functional style

  • 1. Functional Programming (FP) & Ruby in Functional style - Niranjan Sarade 1
  • 2. Agenda • WWW of FP • Spectrum of languages • OOP and FP • Imperative vs. Functional • Examples • Ruby in a functional style • References 2
  • 3. Why FP ? • Programming has become complex • Multiprocessors are common place • Multithreading • But why? – Domain is only part of the reason – We have gone too far with OO programming and mutable state 3
  • 4. Perils of Mutable state • Mutable state – Leads to more bugs – Makes concurrency quite difficult – Shared mutability 4
  • 5. What’s Old is New again! 5
  • 7. FP @wikipedia “In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.” 7
  • 8. Spectrum of Languages Non-functional Hybrid Functional Java C++ C# Ruby Groovy Scala F# Clojure Haskell LISP Erlang 8
  • 9. Real world applications of FP • Erlang: used to implement fault-tolerant telecommunication system. • Lisp: used as basis for several applications on early Apple Macintosh computers. • Ocaml: use in areas such as financial analysis, driver verification, industrial robot programming and static analysis of embedded software. 9
  • 10. Continued • Haskell: aerospace systems, hardware design and web programming. • Using the functional ideas, Google has developed framework called MapReduce for processing massive amounts of data in parallel. • Embedded Lisp interpreters add programmability to some systems, such as Emacs. 10
  • 11. Continued • Lisp is used for artificial intelligence applications. - Knowledge representation - machine learning - Natural language processing - Modeling of speech and vision 11
  • 12. Principles of FP • Assignment-less programming • Immutable state • Functions as first class citizens • Higher order functions • Functions with no side effects • Referential Transparency • Lazy evaluation • Memoization • Recursion 12
  • 13. Closure It is closure because it encloses an environment that is in place when that code block is instantiated. def get_adder(value) proc { |x| x + value } end adder5 = get_adder(5) adder10 = get_adder(10) adder5.call(2) # 7 adder10.call(5) #15 adder5.call(4) # 9 adder10.call(8) #18 13
  • 14. Immutability / No side effect Higher order Functions Functional Style Ruby Groovy Python Smalltalk Clojure Scala Purely Functional Haskell Erlang Lisp 14
  • 15. OOP and FP “OO makes code understandable by encapsulating moving parts… FP makes code understandable by minimizing moving parts.” - Michael Feathers, author of 'Working with Legacy Code' 15
  • 16. Imperative vs. Functional Imperative Specify each step How to do stuff Data mutated Often has side effect Accepts data/objects Hard to compose Functional More directive in style What you want to get Data transformed Has no side effect Accepts functions also Functional composition 16
  • 18. Without memoize def fib(n) return n if n < 2 fib(n-1) + fib(n-2) end fib(35) # slow #2.879s 18
  • 19. With memoize require 'memoize' # https://github.com/djberg96/memoize include Memoize def fib(n) return n if n < 2 fib(n-1) + fib(n-2) end memoize(:fib) fib(35) # fast # 0.07s 19
  • 20. Example 1 Squares of Integers 20
  • 21. Java & Clojure public class Squint { public static void main(String args[]) { for (int i=1; i<=25; i++) System.out.println(i*i); } } Clojure : (take 25 (squares-of (integers)) (1 2 3 4 5 6 7 8 ...) (1 4 9 16 25 36 49 64 ...) (1 4 9 16 25 36 49 64 ... 576 625) 21
  • 22. Haskell :- [ x*x | x <- [1..10]] Ruby :- (1..10).collect { |x| x*x} (1..10).map { |x| x*x} => [1,4,9,16,25,36,49,64,81, 100] 22
  • 23. Haskell :- [ x+1 | x <- [ x*x | x <- [1..10]]] Ruby :- (1..10).collect {|x| x*x }.collect {|x| x+1 } => [2,5,10,17,26,37,50,65,82,101] Lazy evaluation:- take 10 [ x+1 | x <- [ x*x | x <- [1..]]] 23
  • 24. Lazy evaluation in Ruby 2.0 (0..Float::INFINITY).lazy.map { |x| 2*x }.take(5).to_a #=> [0, 2, 4, 6, 8] 24 Making an enumerable lazy makes it possible to enumerate infinite collections. A lazy enumerable will evaluate the entire chain for each element at a time, rather than all elements at each stage of the chain.
  • 25. Example 2 What's the sum of the first 10 natural number whose square value is divisible by 5? 25
  • 26. Imperative Ruby : n, num_elements, sum = 1, 0, 0 while num_elements < 10 if n**2 % 5 == 0 sum += n num_elements += 1 end n += 1 end sum #=> 275 26
  • 27. Functional Ruby 2.0: Integer::natural.select { |x| x**2 % 5 == 0 }. take(10).inject(:+) #=> 275 27
  • 28. Ruby in a Functional style 28
  • 29. Everything is an expression message = “” if found_dog == our_dog name = found_dog.name message = "We found our dog #{name}!" else message = "No luck" end 29
  • 30. Continued message = if found_dog == our_dog "We found our dog #{found_dog.name}!" else "No luck" end 30
  • 31. Higher-order functions: map output = [] [1, 2, 3, 4].each do |x| output << x * 2 end output # [2, 4, 6, 8] output = [1, 2, 3, 4].map do |x| x * 2 end # [2, 4, 6, 8] 31
  • 32. Higher-order functions: select output = [] [1, 2, 3, 4].each do |x| output << x if x > 2 end output # [3, 4] output = [1, 2, 3, 4].select do |x| x > 2 end # [3, 4] 32
  • 33. Higher-order functions: detect output = nil [1, 2, 3, 4].each do |x| if x > 2 output = x break end end output # 3 output = [1, 2, 3, 4].detect do |x| x > 2 end # 3 33
  • 34. Higher-order functions: inject/reduce total = 0 [1, 2, 3, 4].each do |x| total += x end total # 10 total = [1, 2, 3, 4].inject(0) do |acc, x| acc + x end # 10 For simple cases like this: total = [1, 2, 3, 4].inject(0, :+) 34
  • 35. Higher-order functions: zip x = [1, 2, 3] y = [:a, :b, :c] output = [] 0.upto(x.length - 1).each do |idx| output << [x[idx], y[idx]] end output #=> [[1, :a], [2, :b], [3, :c]] x = [1, 2, 3] y = [:a, :b, :c] output = x.zip(y) #=> [[1, :a], [2, :b], [3, :c]] 35
  • 36. Take away Let’s try to learn at least One “Functional” Language and experience the power of functions ! 36
  • 37. References • http://en.wikipedia.org/wiki/Functional_programming • http://pragprog.com/magazines/2013-01/functional- programming-basics • http://www.agiledeveloper.com/ • http://www.defmacro.org/ramblings/fp.html • http://rubysource.com/functional-programming- techniques-with-ruby-part-i/ • https://code.google.com/p/tokland/wiki/RubyFunction alProgramming • http://stackoverflow.com/questions/36504/why- functional-languages 37
  • 38. Some Reference videos • http://vimeo.com/28105411 • http://www.youtube.com/watch?v=8DvxOLzmLSI • http://www.infoq.com/presentations/Functional- Programming-A-Pragmatic-Introduction • http://www.infoq.com/presentations/Are-We-There- Yet-Rich-Hickey • http://www.youtube.com/watch?feature=endscreen &NR=1&v=z0N1aZ6SnBk 38
  • 39. Thank you all for being patient and hearing me out. Hope this helps you! 39

Notes de l'éditeur

  1. FP was introduced a long time ago! It was way ahead of its time. Tell Brief history. Electric car = 1900 yearFunctional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate computability, the Entscheidungsproblem, function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.[1]
  2. Having seen the core principles and spectrum of languages, let’s see where do they fit in a couple of functional principles
  3. Having seen the principles/concepts,So what is the difference between OO and FP ?