Functional programming and ruby in functional style
Upcoming SlideShare
Loading in...5

Functional programming and ruby in functional style



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 ...

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 !



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • 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 ?

Functional programming and ruby in functional style Functional programming and ruby in functional style Presentation Transcript

  • 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• References2
  • 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
  • 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 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
  • 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 several applications onearly Apple Macintosh computers.• Ocaml: use in areas such as financialanalysis, driver verification, industrial robotprogramming and static analysis of embeddedsoftware.9
  • 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
  • Continued• Lisp is used for artificial intelligenceapplications.- Knowledge representation- machine learning- Natural language processing- Modeling of speech and vision11
  • 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
  • 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) # 7 # 9 #1813
  • Immutability /No side effectHigherorder FunctionsFunctionalStyleRubyGroovyPythonSmalltalkClojureScalaPurely FunctionalHaskellErlangLisp14
  • 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
  • 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
  • Memoization17
  • Without memoizedef fib(n)return n if n < 2fib(n-1) + fib(n-2)endfib(35) # slow#2.879s18
  • With memoizerequire memoize# Memoizedef fib(n)return n if n < 2fib(n-1) + fib(n-2)endmemoize(:fib)fib(35) # fast# 0.07s19
  • 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);}}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) { |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.
  • 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 += 1endsum #=> 27526
  • FunctionalRuby { |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}!"elsemessage = "No luck"end29
  • Continuedmessage = if found_dog == our_dog"We found our dog #{}!"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].map do |x|x * 2end# [2, 4, 6, 8]31
  • 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
  • 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
  • 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
  • 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 => [[1, :a], [2, :b], [3, :c]]35
  • Take awayLet’s try to learn at leastOne “Functional” Languageandexperience the power of functions !36
  • References•••••••
  • Some Reference videos•••••
  • Thank you all for being patientand hearing me out.Hope this helps you!39