SlideShare a Scribd company logo
______                _   _                   _
| ____|               | | (_)                 | |
| |__ _   _ _ __   ___| |_ _ ___ _ __     __ _| |
| __| | | | '_  / __| __| |/ _ | '_  / _` | |
| | | |_| | | | | (__| |_| | (_) | | | | (_| | |
|_|   __,_|_| |_|___|__|_|___/|_| |_|__,_|_|


 _____                                               _
| __                                               (_)
| |__) | __ ___   __ _ _ __ __ _ _ __ ___ _ __ ___ _ _ __     __ _
| ___/ '__/ _  / _` | '__/ _` | '_ ` _ | '_ ` _ | | '_  / _` |
| |   | | | (_) | (_| | | | (_| | | | | | | | | | | | | | | | (_| |
|_|   |_| ___/ __, |_| __,_|_| |_| |_|_| |_| |_|_|_| |_|__, |
                  __/ |                                       __/ |
                 |___/                                       |___/
           ____   __   __      __     __ __      ____    __   _ _    __ ____   __   ____   __    __ _
         (  _  / _ ( )     / _ _( )( )      (      / _ ( / ) / (      / _ ( _  / _ ( ( 
          ) _ (/     / (_//     / )  )(    ) D (/      / / ( O )) D (/     )   //    /     /
         (____/_/_/____/_/_/____/(__)    (____/_/_/_)(_/ __/(____/_/_/(___)_/_/_)__)
http://eli.thegreenplace.net/wp-content/uploads/2008/05/tc_000.png
http://sites.google.com/site/andrewsporfotilio/_/rsrc/1226818616654/Home/math_400.jpg
Functional Programming is a style whose
underlying model of computation is the
function.




          f(x)
Referential Transparency
     Higher Order functions
     Lazy Evaluation
     Pattern Matching




http://picasaweb.google.com/damodaran.balaji/DevCampChennaiJuly2010#5493004664487949618
Lambda Calculus
Continuations
Monads
Type Inference
Referential Transparency
Higher Order functions
Lazy Evaluation
Pattern Matching
Referential Transparency
             “Equals can be replaced
                  with equals”




http://2.bp.blogspot.com/_DS3VD3b2euI/TRIcIUzduDI/AAAAAAAAAGA/Xp2E6kPxZCc/s1600/Pascal+the+chameleon+from+tangled+rapunzel+disney+cartoon.jpg
Referential Transparency
“Equals can be replaced with equals”


        f(x) = g(x) + 5
        h(x) = x * f(x)
Referential Transparency
“Equals can be replaced with equals”


        f(x) = g(x) + 5
        h(x) = x * f(x)

        h(x) = x * (g(x) + 5)
public class ReferentiallyOpaque {
    private int x = 0;

    static int f(int y) {
        return x += y;
    }

    public static void main(String[] args) {
        ReferentiallyOpaque ro = new ReferentiallyOpaque();
        System.out.println(ro.f(5));
        System.out.println(ro.f(5));
    }
}
public class ReferentiallyOpaque {
    private int x = 0;;

    static int f(int y) {
        return x += y;
    }

    public static void main(String[] args) {
        ReferentiallyOpaque ro = new ReferentiallyOpaque();
        System.out.println(ro.f(5));
        System.out.println(ro.f(5));
    }
}


                            5
                            10
public class Example {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Hello World");
        System.out.println(buffer.reverse());
        System.out.println(buffer.reverse());
    }
}
public class Example {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Hello World");
        System.out.println(buffer.reverse());
        System.out.println(buffer.reverse());
    }
}


                       dlroW olleH
                       Hello World
public class Example {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Hello World");
        StringBuffer s1 = buffer.reverse();
        StringBuffer s2 = buffer.reverse();
        System.out.println(s1 + " " + s2);
    }
}
public class Example {
    public static void main(String[] args) {

        StringBuffer buffer = new StringBuffer("Hello World");
        StringBuffer s1 = buffer.reverse();
        StringBuffer s2 = buffer.reverse();
        System.out.println(s1 + " " + s2);
    }
}


              Hello World Hello World
Varying Variables
Global State
•    Looping
                                                             •    File I/O
                                                             •    Modify Data
                                                             •    Do more than one thing?




http://paulafanclub.com/wp-content/uploads/2010/12/confused.jpg
Looping



static int factorial(int number) {
   int f = 1;
   for (int i = number; i > 0; i--)
       f = f * i;
   return f;
}
Looping
                                                              Recursion
               static int factorial(int number) {
                  int f = 1;
                  for (int i = number; i > 0; i--)
                      f = f * i;
                  return f;
               }
                                                          static int factorial(int number) {
                                                              return (number == 1) ?
                                                                number :
                                                                number * factorial(number - 1);
                                                          }




http://www.shrink4men.com/wp-content/uploads/2010/11/dog-chasing-its-tail.jpg
Modifying data



static List<Integer> addToList(List<Integer> integers, int a) {
   integers.add(a);
   return integers;
}




                Mutable data structures
Modifying data
                                    Immutable
static List<Integer> addToList(List<Integer> integers, int a) {
   integers.add(a);
   return integers;
}


                    let addToList list a =
                        list @ [a]

                    > let g = [1;2;3;];;
                    val g : int list = [1; 2; 3]

                    > addToList g 4;;
                    val it : int list = [1; 2; 3; 4]

                    > g;;
                    val it : int list = [1; 2; 3]
                    >




            http://4.bp.blogspot.com/_RpRScqAI8e4/SbNPgumsqPI/AAAAAAAAAK4/ZK8ZsfKJCmQ/s400/wolverine+hugh+jackman.jpg
Referential Transparency
Higher Order functions
Lazy Evaluation
Pattern Matching
Higher Order functions
“Functions as first class values”




                    http://www.dreamstime.com/looking-up-to-the-sky-thumb4655038.jpg
Higher Order functions
“Functions that can be passed as arguments”



     def square(x):
         return x * x

     def add(function, x):
         return function(x) + function(x)

     print add(square, 5)
Higher Order functions
“Functions that can be returned as results”

     function addNumber(x) {
         return function(y) {
             return x + y
         }
     }

     var add4With = addNumber(4)
     var add5With = addNumber(5)

     add4with(8)
     add5with(8)

     12
     13
Higher Order functions
           “Functions that can be returned as results”

                   function addNumber(x) {
Lambda Functions
                       return function(y) {
                           return x + y
                       }
                   }

                   var add4With = addNumber(4)
                   var add5With = addNumber(5)

                   add4with(8)
                   add5with(8)

                   12
                   13
Higher Order functions
           “Functions that can be returned as results”

                   function addNumber(x) {
Lambda Functions
                       return function(y) {
                           return x + y
                       }
                   }

                   var add4With = addNumber(4)
                   var add5With = addNumber(5)

                   add4with(8)
                                                 Functions stored in
                   add5with(8)
                                                   data structures
                   12
                   13
Higher Order functions
           “Currying”
let add x y =
    x + y

val add : int -> int -> int

> let add5 = add 5;;
val add5 : (int -> int)

> add5 4;;
val it : int = 9
>
Referential Transparency
Higher Order functions
Lazy Evaluation
Pattern Matching
Lazy Evaluation
“Arguments in a function call are evaluated at most once.”




       http://www.arngren.dk/image/Wallpaper/Comic/Calvin%20Hobbes/Sleeping1024.jpg
Lazy Evaluation
“Ability to invoke expressions only when its value is needed.”
   static void Main(string[] args)
   {
       var lazy = new Lazy<int>(() =>
       {
           Console.WriteLine("calculating...");
           return 6 * 7;
       });
       Console.WriteLine(lazy.Value);
       Console.WriteLine(lazy.Value);
   }
Lazy Evaluation
“Ability to invoke expressions only when its value is needed.”
   static void Main(string[] args)
   {
       var lazy = new Lazy<int>(() =>
       {
           Console.WriteLine("calculating...");
           return 6 * 7;
       });
       Console.WriteLine(lazy.Value);
       Console.WriteLine(lazy.Value);
   }


                      calculating...
                      42
                      42
Lazy Evaluation
                         “Memoization”
function Lazy_Memoized(def) {
  var cache = [];

    return function(i) {
      return (i in cache) ? cache[i] :
        (cache[i] = def.call(arguments.callee, i));
    };
}

var factorial = new Lazy_Memoized(function(i) {
  return i <= 1 ? i : i * this(i - 1);
});

factorial(6)
Lazy Evaluation
         “Ability to create infinite sequence in data structures”




http://softwarezku.co.cc/wp-content/uploads/2010/09/Visual-Studio-2010-Logo.png
Referential Transparency
Higher Order functions
Lazy Evaluation
Pattern Matching
Pattern Matching
      “Writing several equations defining the same function”




http://softwareandfinance.com/images/vcpp-trig1.jpg
Pattern Matching
A typical function definition


f(x) = 1, when x = 0
      = 3x + ex, when x > 0
Pattern Matching
A typical function definition

 fac :: Integer -> Integer
 fac 0 = 1
 fac n | n > 0 = n * fac(n-1)




let rec factorial = function
    | 0 -> 1
    | n -> n * factorial(n - 1)
References
•   Concepts, Evolution and Application of Functional Programming Languages – Paul
    Hudak
•   http://msdn.microsoft.com/en-us/library/dd547125.aspx - Pattern Matching in
    F#
•   http://appden.com/javascript/lazy-list-comprehensions-in-javascript-a-lazy-
    evalution/
•   http://images.google.com
•   http://en.wikipedia.org
•   http://www.haskell.org/haskellwiki/Haskell
•   http://homepages.inf.ed.ac.uk/wadler/

More Related Content

What's hot

Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
gekiaruj
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
Dr. Volkan OBAN
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
Luka Jacobowitz
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In R
Rsquared Academy
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
Roberto Pepato
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
John De Goes
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
Karlijn Willems
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
Fp java8
Fp java8Fp java8
Fp java8
Yanai Franchi
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
Andrei Solntsev
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
Luka Jacobowitz
 

What's hot (20)

Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
R Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In RR Programming: Learn To Manipulate Strings In R
R Programming: Learn To Manipulate Strings In R
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Fp java8
Fp java8Fp java8
Fp java8
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 

Similar to Functional programming basics

Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
SQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
Samir Chekkal
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
Lukasz Dynowski
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
Georgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
Innovecs
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
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
Jason Larsen
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovyTed Leung
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
Istanbul Tech Talks
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
tdc-globalcode
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 

Similar to Functional programming basics (20)

Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
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
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Javascript
JavascriptJavascript
Javascript
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Functional programming basics

  • 1. ______ _ _ _ | ____| | | (_) | | | |__ _ _ _ __ ___| |_ _ ___ _ __ __ _| | | __| | | | '_ / __| __| |/ _ | '_ / _` | | | | | |_| | | | | (__| |_| | (_) | | | | (_| | | |_| __,_|_| |_|___|__|_|___/|_| |_|__,_|_| _____ _ | __ (_) | |__) | __ ___ __ _ _ __ __ _ _ __ ___ _ __ ___ _ _ __ __ _ | ___/ '__/ _ / _` | '__/ _` | '_ ` _ | '_ ` _ | | '_ / _` | | | | | | (_) | (_| | | | (_| | | | | | | | | | | | | | | | (_| | |_| |_| ___/ __, |_| __,_|_| |_| |_|_| |_| |_|_|_| |_|__, | __/ | __/ | |___/ |___/ ____ __ __ __ __ __ ____ __ _ _ __ ____ __ ____ __ __ _ ( _ / _ ( ) / _ _( )( ) ( / _ ( / ) / ( / _ ( _ / _ ( ( ) _ (/ / (_// / ) )( ) D (/ / / ( O )) D (/ ) // / / (____/_/_/____/_/_/____/(__) (____/_/_/_)(_/ __/(____/_/_/(___)_/_/_)__)
  • 4. Functional Programming is a style whose underlying model of computation is the function. f(x)
  • 5. Referential Transparency Higher Order functions Lazy Evaluation Pattern Matching http://picasaweb.google.com/damodaran.balaji/DevCampChennaiJuly2010#5493004664487949618
  • 7. Referential Transparency Higher Order functions Lazy Evaluation Pattern Matching
  • 8. Referential Transparency “Equals can be replaced with equals” http://2.bp.blogspot.com/_DS3VD3b2euI/TRIcIUzduDI/AAAAAAAAAGA/Xp2E6kPxZCc/s1600/Pascal+the+chameleon+from+tangled+rapunzel+disney+cartoon.jpg
  • 9. Referential Transparency “Equals can be replaced with equals” f(x) = g(x) + 5 h(x) = x * f(x)
  • 10. Referential Transparency “Equals can be replaced with equals” f(x) = g(x) + 5 h(x) = x * f(x) h(x) = x * (g(x) + 5)
  • 11. public class ReferentiallyOpaque { private int x = 0; static int f(int y) { return x += y; } public static void main(String[] args) { ReferentiallyOpaque ro = new ReferentiallyOpaque(); System.out.println(ro.f(5)); System.out.println(ro.f(5)); } }
  • 12. public class ReferentiallyOpaque { private int x = 0;; static int f(int y) { return x += y; } public static void main(String[] args) { ReferentiallyOpaque ro = new ReferentiallyOpaque(); System.out.println(ro.f(5)); System.out.println(ro.f(5)); } } 5 10
  • 13. public class Example { public static void main(String[] args) { StringBuffer buffer = new StringBuffer("Hello World"); System.out.println(buffer.reverse()); System.out.println(buffer.reverse()); } }
  • 14. public class Example { public static void main(String[] args) { StringBuffer buffer = new StringBuffer("Hello World"); System.out.println(buffer.reverse()); System.out.println(buffer.reverse()); } } dlroW olleH Hello World
  • 15. public class Example { public static void main(String[] args) { StringBuffer buffer = new StringBuffer("Hello World"); StringBuffer s1 = buffer.reverse(); StringBuffer s2 = buffer.reverse(); System.out.println(s1 + " " + s2); } }
  • 16. public class Example { public static void main(String[] args) { StringBuffer buffer = new StringBuffer("Hello World"); StringBuffer s1 = buffer.reverse(); StringBuffer s2 = buffer.reverse(); System.out.println(s1 + " " + s2); } } Hello World Hello World
  • 18. Looping • File I/O • Modify Data • Do more than one thing? http://paulafanclub.com/wp-content/uploads/2010/12/confused.jpg
  • 19. Looping static int factorial(int number) { int f = 1; for (int i = number; i > 0; i--) f = f * i; return f; }
  • 20. Looping Recursion static int factorial(int number) { int f = 1; for (int i = number; i > 0; i--) f = f * i; return f; } static int factorial(int number) { return (number == 1) ? number : number * factorial(number - 1); } http://www.shrink4men.com/wp-content/uploads/2010/11/dog-chasing-its-tail.jpg
  • 21. Modifying data static List<Integer> addToList(List<Integer> integers, int a) { integers.add(a); return integers; } Mutable data structures
  • 22. Modifying data Immutable static List<Integer> addToList(List<Integer> integers, int a) { integers.add(a); return integers; } let addToList list a = list @ [a] > let g = [1;2;3;];; val g : int list = [1; 2; 3] > addToList g 4;; val it : int list = [1; 2; 3; 4] > g;; val it : int list = [1; 2; 3] > http://4.bp.blogspot.com/_RpRScqAI8e4/SbNPgumsqPI/AAAAAAAAAK4/ZK8ZsfKJCmQ/s400/wolverine+hugh+jackman.jpg
  • 23. Referential Transparency Higher Order functions Lazy Evaluation Pattern Matching
  • 24. Higher Order functions “Functions as first class values” http://www.dreamstime.com/looking-up-to-the-sky-thumb4655038.jpg
  • 25. Higher Order functions “Functions that can be passed as arguments” def square(x): return x * x def add(function, x): return function(x) + function(x) print add(square, 5)
  • 26. Higher Order functions “Functions that can be returned as results” function addNumber(x) { return function(y) { return x + y } } var add4With = addNumber(4) var add5With = addNumber(5) add4with(8) add5with(8) 12 13
  • 27. Higher Order functions “Functions that can be returned as results” function addNumber(x) { Lambda Functions return function(y) { return x + y } } var add4With = addNumber(4) var add5With = addNumber(5) add4with(8) add5with(8) 12 13
  • 28. Higher Order functions “Functions that can be returned as results” function addNumber(x) { Lambda Functions return function(y) { return x + y } } var add4With = addNumber(4) var add5With = addNumber(5) add4with(8) Functions stored in add5with(8) data structures 12 13
  • 29. Higher Order functions “Currying” let add x y = x + y val add : int -> int -> int > let add5 = add 5;; val add5 : (int -> int) > add5 4;; val it : int = 9 >
  • 30. Referential Transparency Higher Order functions Lazy Evaluation Pattern Matching
  • 31. Lazy Evaluation “Arguments in a function call are evaluated at most once.” http://www.arngren.dk/image/Wallpaper/Comic/Calvin%20Hobbes/Sleeping1024.jpg
  • 32. Lazy Evaluation “Ability to invoke expressions only when its value is needed.” static void Main(string[] args) { var lazy = new Lazy<int>(() => { Console.WriteLine("calculating..."); return 6 * 7; }); Console.WriteLine(lazy.Value); Console.WriteLine(lazy.Value); }
  • 33. Lazy Evaluation “Ability to invoke expressions only when its value is needed.” static void Main(string[] args) { var lazy = new Lazy<int>(() => { Console.WriteLine("calculating..."); return 6 * 7; }); Console.WriteLine(lazy.Value); Console.WriteLine(lazy.Value); } calculating... 42 42
  • 34. Lazy Evaluation “Memoization” function Lazy_Memoized(def) { var cache = []; return function(i) { return (i in cache) ? cache[i] : (cache[i] = def.call(arguments.callee, i)); }; } var factorial = new Lazy_Memoized(function(i) { return i <= 1 ? i : i * this(i - 1); }); factorial(6)
  • 35. Lazy Evaluation “Ability to create infinite sequence in data structures” http://softwarezku.co.cc/wp-content/uploads/2010/09/Visual-Studio-2010-Logo.png
  • 36. Referential Transparency Higher Order functions Lazy Evaluation Pattern Matching
  • 37. Pattern Matching “Writing several equations defining the same function” http://softwareandfinance.com/images/vcpp-trig1.jpg
  • 38. Pattern Matching A typical function definition f(x) = 1, when x = 0 = 3x + ex, when x > 0
  • 39. Pattern Matching A typical function definition fac :: Integer -> Integer fac 0 = 1 fac n | n > 0 = n * fac(n-1) let rec factorial = function | 0 -> 1 | n -> n * factorial(n - 1)
  • 40.
  • 41.
  • 42. References • Concepts, Evolution and Application of Functional Programming Languages – Paul Hudak • http://msdn.microsoft.com/en-us/library/dd547125.aspx - Pattern Matching in F# • http://appden.com/javascript/lazy-list-comprehensions-in-javascript-a-lazy- evalution/ • http://images.google.com • http://en.wikipedia.org • http://www.haskell.org/haskellwiki/Haskell • http://homepages.inf.ed.ac.uk/wadler/