SlideShare a Scribd company logo
1 of 107
Download to read offline
Functional
      Programming

λ                     Bryan Weber
        Near Infinity Corporation
                    January 2009



                                    1
About the Speaker

• Let’s be honest
• You don’t know
• You don’t care
• Let’s move on...

                            2
                                2
Things should not change
               and they should
not affect others

                                 3
                                     3
and it would be good if they
could do both at the
same time

                               4
                                   4
What’s the point?




                    5
                        5
What
not how
not when

           6
               6
Before we go any further..




                             7
                                 7
Mathematics!




               8
Uh oh!




         9
Please don’t leave..


                       10
Good book




            11
Functional Languages
Haskell
                       Scala
Clean
                     Clojure
F#
                      XSLT
ML / OCaml
                      Erlang
Lisp / Scheme
                               12
                               12
Pure Functional Languages
Haskell
                     Scala
Clean
                   Clojure
F#
                    XSLT
ML / OCaml
                    Erlang
Lisp / Scheme
                             13
                             13
Haskell




          14
Introductory?




                15
Programming?




               16
Is it too hard?




                  17
Again?




         18
         18
The foundation




                 19
What is a function?

              y = f(x)
                         20
Lambda Calculus




                  21
Lambda expression

        λ x. x + 2
                     22
How do we achieve
functions like..
          f(x,y) -> z
                        23
Function Currying Example

foo(x,y) -> z
     bar(x) -> baz
     baz(y) -> z
                             24
“It's not difficult at all,
      proc {|x, y, z| x + y + z }.curry
 returns the proc object equivalent to
proc {|x| proc {|y| proc {|z| x + y + z } } }
                    See?”
                         matz.




                                                25
Why do this in Ruby?

plus_five =proc{|x,y,z|x+y+z }.curry.call(2).call(3)

plus_five[10]       #=> 15



                                                      26
Ruby,
really?
          C# too!
          LINQ
                    27
Arity example   (1)


%% sum/1
sum(L) -> sum(L,0).

%% sum/2
sum([], N) -> N;
sum([H|T],N) -> sum(T, H+N).
                               28
Pattern Matching
            example


                      29
-module(patternmatch).
-export([run/0]).
run() ->
         tupleassign(),
         pmatch(),
         invalid().
invalid() ->
     Str1 = quot;have a nice dayquot;,
     Str2 = quot;have another nice dayquot;,
     Str1 = Str2. %% this is an error!
tupleassign() ->
         MyTuple = {1,2,3},
         {A,B,C} = MyTuple, %% this assigns values to unbound A, B and C
         io:format(quot;A:~p B:~p C:~p ~nquot;,[A,B,C]).
pmatch() ->
         Str1 = quot;la la laquot;,
         case Str1 of
                  quot;fooquot; ->
                            io:format(quot;uh oh ~nquot;);
                  3 ->
                            io:format(quot;wrong type ~nquot;);
                  quot;la la laquot; ->
                            io:format(quot;We have a match ~nquot;);
                  _ ->
                            io:format(quot;like an else ~nquot;)
         end.


                                                                           30
Built in Assertions /
          Single Assignment
invalid() ->
      Str1 = quot;have a nice dayquot;,
      Str2 = quot;have another nice dayquot;,
      Str1 = Str2. %% this is an error!


                                          31
Multiple Assignment
tupleassign() ->
  %% create a tuple

 MyTuple = {1,2,3},
  %% assign values to unbound A, B and C

 {A,B,C} = MyTuple,
  %% print the result

 io:format(quot;A:~p B:~p C:~p ~nquot;,[A,B,C]).



                                            32
Switch Statement

   Str1 = quot;la la laquot;,

   case Str1 of

   
 quot;fooquot; ->

   
 
 io:format(quot;uh oh ~nquot;);

   
 3 ->

   
 
 io:format(quot;wrong type ~nquot;);

   
 quot;la la laquot; ->

   
 
 io:format(quot;We have a match ~nquot;);

   
 _ ->

   
 
 io:format(quot;like an else ~nquot;)

   end.
                                           33
Call by Future

                 34
Lazy Evaluation

                  35
Control Structure Example



                            36
DEFINE:
newOr a b = if a then a else b

EXAMPLE:
newOr (4==4) (length [1..] > 0)

                                  37
And now, for our
  featured
presentation
                    38
Immutability

           Concurrency

                    Side Effects

                               39
Functional


Object Oriented

                  40
Immutability

           Concurrency

                    Side Effects

                               41
Object Oriented


  Functional


                  42
Enlightenment?




                 43
Immutability

           Concurrency

                    Side Effects

                               44
Immutability

           Concurrency

                    Side Effects

                               45
Can Things Change?




                     46
Immutable Collections
                                example
Lists (IPersistentList)
Vectors (IPersistentVector)
Maps (IPersistentMap)
                              StructMaps
                               ArrayMaps*
                                     Sets
                                            47
PROGRAM: (2)
(in-ns 'main)
(clojure/refer 'clojure)

(defn main [args]
  (def x (list 1 2 3))
  (def y (conj x quot;helloquot; quot;therequot; quot;worldquot;))
  (println quot;list is: [quot; (apply str (interpose quot;, quot; y)) quot;]quot;)
 )

PRODUCES:
list is: [ world, there, hello, 1, 2, 3 ]


                                                              48
Erlang Lists (3)
              append(List1, List2) -> List3

                         Types:

            List1 = List2 = List3 = [term()]

Returns a new list List3 which is made from the elements
       of List1 followed by the elements of List2.



                                                           49
Immutability

           Concurrency

                    Side Effects

                               50
Complexity

             51
No shared state


                  52
STM
Example



          53
Operation        Type Signature
atomically        STM a -> IO a
  retry               STM a
 orElse      STM a -> STM a -> STM a
newTVar         a -> STM (TVar a)
readTVar         TVar a -> STM a
writeTVar      TVar a -> a -> STM ()

                                       54
(4)
module Main where
<< ... imports omitted ... >>
main = do shared <- atomically $ newTVar 0
        before <- atomRead shared
        putStrLn $ quot;Before: quot; ++ show before
        forkIO $ 25 `timesDo` (dispVar shared >> milliSleep 20)
        forkIO $ 10 `timesDo` (appV ((+) 2) shared >> milliSleep 50)
        forkIO $ 20 `timesDo` (appV pred shared >> milliSleep 25)
        milliSleep 800
        after <- atomRead shared
        putStrLn $ quot;After: quot; ++ show after
 where timesDo = replicateM_
     milliSleep = threadDelay . (*) 1000
atomRead = atomically . readTVar
dispVar x = atomRead x >>= print
appV fn x = atomically $ readTVar x >>= writeTVar x . fn

                                                                   55
Message Passing

                  56
Actor Primitives
     spawn
    send (!)
    receive
                   57
Actor



actor
         58
Actor           Actor



        Spawn
                        59
Actor          Actor



        Send
                       60
Actor                Actor



  Receive (pull model)
                             61
Actor Example



                62
-module(actor).
-export([run/0]).

act() ->
 receive
   Message ->
    io:format(quot;You said: ~p~nquot;,[Message])
 end.

run() ->
 Pid = spawn(fun act/0),
 Pid ! quot;Foobarbazquot;.

                                            63
Immutability

           Concurrency

                    Side Effects

                               64
Purity

         65
         65
Side effects




               66
               66
Your program

      Your   API
      Code
You                Black Box




                               67
                               67
Your program
                        State
                        State


      Your   API
      Code
You                Black Box




                                68
                                68
Your program
                         State
                                    Database
                        (Memory)

      Your   API
                                   File System
      Code
You                Black Box


                                    Network


                                                 69
                                                 69
Launch Missiles




                  70
                  70
ALSO
     IO
              Exceptions
 Network
              Randomness
 Database
                Memory
File System
                 Order
  Console
                           71
Side effects are bad, mkay?

                              72
What can I do then?




                      73
Monads!


          74
What is a Monad?




                   75
Monadic Laws

1) Left identify
2) Right identity
3) Associativity

                    76
Monad
        example



                  77
(5)
hPutStr :: Handle -> String -> IO ()
hGetLine :: Handle -> IO String

hEchoLine :: Handle -> IO String
hEchoLine h = do {
  s <- hGetLine h
  ; hPutStr h (“I read: ” ++ s ++ “n”)
  ; return s
}


                                          78
Does order matter?




                     79
Order is a side effect as well..
                                   80
Order
        example



                  81
func(x,y,z) -> r

                        zr
xa         yb




                             82
func(x,y,z) -> r

                        zr
xa         yb




                             83
Data dependency
             example

                       84
func(x,y) -> z

                      bz
xa       y,a b




                           85
func(x,y) -> z

                      bz
xa       y,a b




                           86
func(x,y) -> z

                      bz
xa       y,a b




                           87
func(x,y) -> z

                      bz
xa       y,a b




                           88
Function
       Optimization
                      Example

f = g(x) + g(x)

                                89
The Real WOrld



                 90
No time for:
    Polymorphism
            Lists
             Tuples
              Guards
               Accumulators
                Continuations
               Comprehensions
               Fault      Tolerance
             Type           Systems
          Process             Linking
        Recursion              (TCO)
     Higher Order             Functions

                                          91
Summary



          92
Functions (Math)




                   93
Functions (Math)

Immutability




                   94
Functions (Math)

Immutability

Concurrency




                   95
Functions (Math)

Immutability

Concurrency

  Developer
Optimizations


                    96
Functions (Math)

Immutability        Side Effects

Concurrency

  Developer
Optimizations


                                   97
Functions (Math)

Immutability        Side Effects

Concurrency           Monads

  Developer
Optimizations


                                   98
Functions (Math)

Immutability        Side Effects

Concurrency            Monads

  Developer          Automated
Optimizations       Optimizations


                                    99
Things should not change
 (but state is great!)
            and they should
  not affect others
(without notifying us)        100
                              100
and it would be good if they
could do both at the
same time
(all the time)
                               101
                               101
Resources



            102
Books
       Beautiful Code (Oram and Wilson)
Real World Haskell (O’Sullivan, Stewart and Goerzen)
       Programming Erlang (Armstrong)
       Foundations of F# (Pickering)
    Expert F# (Syme, Granicz and Cisternino)
         F# for Scientists (Harrop)
       Programming in Haskell (Hutton)

                Coming Soon
        Programming Scala (Subramaniam)
         Programming Clojure (Halloway)

                                                       103
The Web
              http://www.erlang.org
              http://www.haskell.org
              http://www.clojure.org
             http://www.trapexit.org
            http://www.scala-lang.org
         http://lambda-the-ultimate.org
        http://pragmaticstudio.com/erlang
        http://en.wikibooks.org/wiki/Haskell
       http://book.realworldhaskell.org/read
     http://www.lisperati.com/fringedc.html
http://research.microsoft.com/fsharp/fsharp.aspx
                                                   104
IRC
chat.freenode.net
     #haskell
      #scala
     #erlang
     #clojure
     #fsharp
                    105
References
1) Example shamelessly stolen from page 42 of
“Programming Erlang” by Joe Armstrong.
2) Shamelessly stolen from Clojure doc
3) From Erlang stdlib documentation
4) Shamelessly stolen from
http://www.haskell.org/haskellwiki/Simple_STM_example
5) Example from “Beautiful Code” by Oram and Wilson




                                                        106
Questions?

             107

More Related Content

What's hot

Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
Farag Zakaria
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 

What's hot (20)

Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
State Monad
State MonadState Monad
State Monad
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 

Similar to Functional Concepts for OOP Developers

F# Presentation
F# PresentationF# Presentation
F# Presentation
mrkurt
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
Ross Lawley
 

Similar to Functional Concepts for OOP Developers (20)

Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
Subtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff HammondSubtle Asynchrony by Jeff Hammond
Subtle Asynchrony by Jeff Hammond
 
Writing Macros
Writing MacrosWriting Macros
Writing Macros
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Matlab1
Matlab1Matlab1
Matlab1
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Brief introduction to Algorithm analysis
Brief introduction to Algorithm analysis Brief introduction to Algorithm analysis
Brief introduction to Algorithm analysis
 
presentation.pptx
presentation.pptxpresentation.pptx
presentation.pptx
 
Cpl
CplCpl
Cpl
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Lisp and prolog in artificial intelligence
Lisp and prolog in artificial intelligenceLisp and prolog in artificial intelligence
Lisp and prolog in artificial intelligence
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
 
Class 16: Making Loops
Class 16: Making LoopsClass 16: Making Loops
Class 16: Making Loops
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
Introduction to PyTorch
Introduction to PyTorchIntroduction to PyTorch
Introduction to PyTorch
 
Groovy
GroovyGroovy
Groovy
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 

Functional Concepts for OOP Developers