Your SlideShare is downloading. ×
0
Functional Programming (FP)&Ruby in Functional style- Niranjan Sarade1
Agenda• WWW of FP• Spectrum of languages• OOP and FP• Imperative vs. Functional• Examples• Ruby in a functional style• Ref...
Why FP ?• Programming has become complex• Multiprocessors are common place• Multithreading• But why?– Domain is only part ...
Perils of Mutable state• Mutable state– Leads to more bugs– Makes concurrency quite difficult– Shared mutability4
What’s Old is New again!5
y = f(x)6
FP @wikipedia“In computer science, functional programming isa programming paradigm that treatscomputation as the evaluatio...
Spectrum of LanguagesNon-functional Hybrid FunctionalJavaC++C#RubyGroovyScalaF#ClojureHaskellLISPErlang8
Real world applications of FP• Erlang: used to implement fault-toleranttelecommunication system.• Lisp: used as basis for ...
Continued• Haskell: aerospace systems, hardware designand web programming.• Using the functional ideas, Google hasdevelope...
Continued• Lisp is used for artificial intelligenceapplications.- Knowledge representation- machine learning- Natural lang...
Principles of FP• Assignment-less programming• Immutable state• Functions as first class citizens• Higher order functions•...
ClosureIt is closure because it encloses an environmentthat is in place when that code block is instantiated.def get_adder...
Immutability /No side effectHigherorder FunctionsFunctionalStyleRubyGroovyPythonSmalltalkClojureScalaPurely FunctionalHask...
OOP and FP“OO makes code understandable byencapsulating moving parts…FP makes code understandable by minimizingmoving part...
Imperative vs. FunctionalImperativeSpecify each stepHow to do stuffData mutatedOften has side effectAccepts data/objectsHa...
Memoization17
Without memoizedef fib(n)return n if n < 2fib(n-1) + fib(n-2)endfib(35) # slow#2.879s18
With memoizerequire memoize# https://github.com/djberg96/memoizeinclude Memoizedef fib(n)return n if n < 2fib(n-1) + fib(n...
Example 1Squares of Integers20
Java & Clojurepublic class Squint {public static void main(String args[]) {for (int i=1; i<=25; i++)System.out.println(i*i...
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...
Lazy evaluation in Ruby 2.0(0..Float::INFINITY).lazy.map { |x| 2*x }.take(5).to_a#=> [0, 2, 4, 6, 8]24Making an enumerable...
Example 2Whats the sum of the first 10 natural numberwhose square value is divisible by 5?25
ImperativeRuby :n, num_elements, sum = 1, 0, 0while num_elements < 10if n**2 % 5 == 0sum += nnum_elements += 1endn += 1end...
FunctionalRuby 2.0:Integer::natural.select { |x| x**2 % 5 == 0 }.take(10).inject(:+)#=> 27527
Ruby in a Functional style28
Everything is an expressionmessage = “”if found_dog == our_dogname = found_dog.namemessage = "We found our dog #{name}!"el...
Continuedmessage = if found_dog == our_dog"We found our dog #{found_dog.name}!"else"No luck"end30
Higher-order functions: mapoutput = [][1, 2, 3, 4].each do |x|output << x * 2endoutput # [2, 4, 6, 8]output = [1, 2, 3, 4]...
Higher-order functions: selectoutput = [][1, 2, 3, 4].each do |x|output << x if x > 2endoutput # [3, 4]output = [1, 2, 3, ...
Higher-order functions: detectoutput = nil[1, 2, 3, 4].each do |x|if x > 2output = xbreakendendoutput # 3output = [1, 2, 3...
Higher-order functions: inject/reducetotal = 0[1, 2, 3, 4].each do |x|total += xendtotal # 10total = [1, 2, 3, 4].inject(0...
Higher-order functions: zipx = [1, 2, 3]y = [:a, :b, :c]output = []0.upto(x.length - 1).each do |idx|output << [x[idx], y[...
Take awayLet’s try to learn at leastOne “Functional” Languageandexperience the power of functions !36
References• http://en.wikipedia.org/wiki/Functional_programming• http://pragprog.com/magazines/2013-01/functional-programm...
Some Reference videos• http://vimeo.com/28105411• http://www.youtube.com/watch?v=8DvxOLzmLSI• http://www.infoq.com/present...
Thank you all for being patientand hearing me out.Hope this helps you!39
Upcoming SlideShare
Loading in...5
×

Functional programming and ruby in functional style

995

Published on

This presentation gives brief introduction to Functional Programming and how we can apply functional style of programming in Ruby language. The mentioned references are of great help to prepare this presentation. Especially video talks of Dr. Venkat Subramaniam. Some slides are from his presentation.

Functional programming (FP) is becoming popular day by day ! The initial learning curve for some of the functional languages like Lisp, Haskell, OCaml, Scala, Scheme, Clojure, etc. .... (there are many) might be high, but once you know the problem context and power of functions, you will work like a boss ! You will be more declarative than imperative !

Ruby is an Object Oriented (OO) language and we love Ruby, isn't it ? But once you understand the importance of FP, you would certainly want to apply FP concepts while writing Ruby code. In fact, you might have used some of those concepts unknowingly. Yes, we are talking about lambda, proc .. but, that's not all. Learn to unleash the power of Ruby in the hands of a functional programmer! You can write wonderful (and working) ruby code with functional style. In this presentation, I will briefly go through FP basics and then jump over to code examples.

Finally, it's all about changing your mindset! No one has stopped you to become a Boss !

Published in: Technology, Education
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
995
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • 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]
  • Having seen the core principles and spectrum of languages, let’s see where do they fit in a couple of functional principles
  • Having seen the principles/concepts,So what is the difference between OO and FP ?
  • Transcript of "Functional programming and ruby in functional style"

    1. 1. Functional Programming (FP)&Ruby in Functional style- Niranjan Sarade1
    2. 2. Agenda• WWW of FP• Spectrum of languages• OOP and FP• Imperative vs. Functional• Examples• Ruby in a functional style• References2
    3. 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 andmutable state3
    4. 4. Perils of Mutable state• Mutable state– Leads to more bugs– Makes concurrency quite difficult– Shared mutability4
    5. 5. What’s Old is New again!5
    6. 6. y = f(x)6
    7. 7. FP @wikipedia“In computer science, functional programming isa programming paradigm that treatscomputation as the evaluation of mathematicalfunctions and avoids state and mutable data. Itemphasizes the application of functions, incontrast to the imperative programmingstyle, which emphasizes changes in state.”7
    8. 8. Spectrum of LanguagesNon-functional Hybrid FunctionalJavaC++C#RubyGroovyScalaF#ClojureHaskellLISPErlang8
    9. 9. Real world applications of FP• Erlang: used to implement fault-toleranttelecommunication system.• Lisp: used as basis for several applications onearly Apple Macintosh computers.• Ocaml: use in areas such as financialanalysis, driver verification, industrial robotprogramming and static analysis of embeddedsoftware.9
    10. 10. Continued• Haskell: aerospace systems, hardware designand web programming.• Using the functional ideas, Google hasdeveloped framework called MapReduce forprocessing massive amounts of data inparallel.• Embedded Lisp interpreters addprogrammability to some systems, such asEmacs.10
    11. 11. Continued• Lisp is used for artificial intelligenceapplications.- Knowledge representation- machine learning- Natural language processing- Modeling of speech and vision11
    12. 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• Recursion12
    13. 13. ClosureIt is closure because it encloses an environmentthat is in place when that code block is instantiated.def get_adder(value)proc { |x| x + value }endadder5 = get_adder(5) adder10 = get_adder(10)adder5.call(2) # 7 adder10.call(5) #15adder5.call(4) # 9 adder10.call(8) #1813
    14. 14. Immutability /No side effectHigherorder FunctionsFunctionalStyleRubyGroovyPythonSmalltalkClojureScalaPurely FunctionalHaskellErlangLisp14
    15. 15. OOP and FP“OO makes code understandable byencapsulating moving parts…FP makes code understandable by minimizingmoving parts.”- Michael Feathers, author of Working with Legacy Code15
    16. 16. Imperative vs. FunctionalImperativeSpecify each stepHow to do stuffData mutatedOften has side effectAccepts data/objectsHard to composeFunctionalMore directive in styleWhat you want to getData transformedHas no side effectAccepts functions alsoFunctional composition16
    17. 17. Memoization17
    18. 18. Without memoizedef fib(n)return n if n < 2fib(n-1) + fib(n-2)endfib(35) # slow#2.879s18
    19. 19. With memoizerequire memoize# https://github.com/djberg96/memoizeinclude Memoizedef fib(n)return n if n < 2fib(n-1) + fib(n-2)endmemoize(:fib)fib(35) # fast# 0.07s19
    20. 20. Example 1Squares of Integers20
    21. 21. Java & Clojurepublic 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. 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. 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. 24. Lazy evaluation in Ruby 2.0(0..Float::INFINITY).lazy.map { |x| 2*x }.take(5).to_a#=> [0, 2, 4, 6, 8]24Making an enumerable lazy makes it possible to enumerate infinitecollections.A lazy enumerable will evaluate the entire chain for each element at atime, rather than all elements at each stage of the chain.
    25. 25. Example 2Whats the sum of the first 10 natural numberwhose square value is divisible by 5?25
    26. 26. ImperativeRuby :n, num_elements, sum = 1, 0, 0while num_elements < 10if n**2 % 5 == 0sum += nnum_elements += 1endn += 1endsum #=> 27526
    27. 27. FunctionalRuby 2.0:Integer::natural.select { |x| x**2 % 5 == 0 }.take(10).inject(:+)#=> 27527
    28. 28. Ruby in a Functional style28
    29. 29. Everything is an expressionmessage = “”if found_dog == our_dogname = found_dog.namemessage = "We found our dog #{name}!"elsemessage = "No luck"end29
    30. 30. Continuedmessage = if found_dog == our_dog"We found our dog #{found_dog.name}!"else"No luck"end30
    31. 31. Higher-order functions: mapoutput = [][1, 2, 3, 4].each do |x|output << x * 2endoutput # [2, 4, 6, 8]output = [1, 2, 3, 4].map do |x|x * 2end# [2, 4, 6, 8]31
    32. 32. Higher-order functions: selectoutput = [][1, 2, 3, 4].each do |x|output << x if x > 2endoutput # [3, 4]output = [1, 2, 3, 4].select do |x|x > 2end# [3, 4]32
    33. 33. Higher-order functions: detectoutput = nil[1, 2, 3, 4].each do |x|if x > 2output = xbreakendendoutput # 3output = [1, 2, 3, 4].detect do |x|x > 2end # 333
    34. 34. Higher-order functions: inject/reducetotal = 0[1, 2, 3, 4].each do |x|total += xendtotal # 10total = [1, 2, 3, 4].inject(0) do |acc, x|acc + xend # 10For simple cases like this:total = [1, 2, 3, 4].inject(0, :+)34
    35. 35. Higher-order functions: zipx = [1, 2, 3]y = [:a, :b, :c]output = []0.upto(x.length - 1).each do |idx|output << [x[idx], y[idx]]endoutput #=> [[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. 36. Take awayLet’s try to learn at leastOne “Functional” Languageandexperience the power of functions !36
    37. 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/RubyFunctionalProgramming• http://stackoverflow.com/questions/36504/why-functional-languages37
    38. 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=z0N1aZ6SnBk38
    39. 39. Thank you all for being patientand hearing me out.Hope this helps you!39
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×