SlideShare ist ein Scribd-Unternehmen logo
1 von 25
How to Reinvent
the Y combinator
    Yin Wang
Why do we need the Y combinator?


      For fundamental understanding of
      recursion, we hope to create
      recursive functions using the
      lambda calculus:

                x | t t | λx.t
Why not define or letrec?
(define length                             (letrec ([length
 (lambda (ls)                                     (lambda (ls)
   (cond                                            (cond
    [(null? ls) 0]                                   [(null? ls) 0]
    [else (add1 (length (cdr ls)))])))               [else (add1 (length (cdr ls)))]))])
                                             (length '(a b c)))

             1. We don’t have define or letrec in lambda calculus

             2. For fundamental understanding of recursion, we
                want to see how define and letrec can be created
                using just the three elements of lambda calculus:
                                 x | t t | λx.t

             3. You will see how this understanding can be useful
                when constructing compilers
Plan
(define length
 (lambda (ls)
   (cond
    [(null? ls) 0]
    [else (add1 (length (cdr ls)))])))


• We start by constructing a recursive definition of
  “length” in a pure subset of Scheme
• Then extract a common pattern that can be
  applied to recursive definitions in general
• This common pattern is the Y combinator
How do we do that?

• First, notice we can’t really define a recursive
  function without binding it to a name

• Second, answer this question:
  “Where can we bind something to a name?”

• The answer is: λx.t

• Lambda, the ultimate binder
Step 1: Binder
 (define length
  (lambda (ls)
    (cond
     [(null? ls) 0]
     [else (add1 (length (cdr ls)))])))




• Step1: create a lambda similar to this define
• This creates a binder where we can bind the function to
• Our goal: bind the function “length” to the name length
Step 1: Binder
 (lambda (length)
   (lambda (ls)
     (cond
      [(null? ls) 0]
      [else (add1 (length (cdr ls)))])))




• Step1: create a lambda similar to this define
• This creates a binder where we can bind the function to
• Our goal: bind the function “length” to the name length
Step 2: Copy
((lambda (length)
  (lambda (ls)
    (cond
     [(null? ls) 0]
     [else (add1 (length (cdr ls)))])))
(lambda (length)
  (lambda (ls)
    (cond
     [(null? ls) 0]
     [else (add1 (length (cdr ls)))]))))


         • Make a copy of the function and apply itself
           to the copy (self-application)
         • This will successfully bind the name length
           to the function “itself”
Step 3: Small fix
((lambda (length)
  (lambda (ls)
    (cond
     [(null? ls) 0]
     [else (add1 ((length length) (cdr ls)))])))
(lambda (length)
  (lambda (ls)
    (cond
     [(null? ls) 0]
     [else (add1 ((length length) (cdr ls)))]))))



     The first argument to the application of
     “length” should be itself
Step 4: Extract Patterns
((lambda (length)
   (lambda (ls)
     (cond
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))])))
 (lambda (length)
   (lambda (ls)
     (cond
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))


  • This recursive function will work (try it!)
  • This is called “poor man’s Y”
  • Now we are going to extract the pattern
    in there, so that the same pattern works
    for any function.
Step 4: Extract Patterns
((lambda (length)
   (lambda (ls)
     (cond                                           • But we can’t see the original
      [(null? ls) 0]                                   definition in there.
      [else (add1 ((length length) (cdr ls)))])))    • We hope to see this, but the
 (lambda (length)                                      self-applications (length length)
   (lambda (ls)                                        bother us.
     (cond                                           • Hope we can get rid of them
      [(null? ls) 0]
                                                       while preserving the semantics.
      [else (add1 ((length length) (cdr ls)))]))))


  • This recursive function will work (try it!)
  • This is called “poor man’s Y”                     (lambda (length)
  • Now we are going to extract the pattern              (lambda (ls)
                                                           (cond
    in there, so that the same pattern works                [(null? ls) 0]
    for any function.                                       [else (add1 (length (cdr ls)))])))
Three Self-applications
((lambda (length)
   (lambda (ls)
     (cond
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))])))
 (lambda (length)
   (lambda (ls)
     (cond
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))




            Notice that this code has
            three self-aplications, one
            outer and two inner.
Abstract Outer Self-application
((lambda (length)
   (lambda (ls)
     (cond                                           ((lambda (u) (u u))
      [(null? ls) 0]                                  (lambda (length)
      [else (add1 ((length length) (cdr ls)))])))       (lambda (ls)
 (lambda (length)                                         (cond
   (lambda (ls)                                            [(null? ls) 0]
     (cond                                                 [else (add1 ((length length) (cdr ls)))]))))
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))

                                                            •   First, let’s extract the pattern
                                                                which does the outer self-
                                                                application
                                                            •   In compiler terms, this is called
                                                                “common subexpression
                                                                elimination”
Inner Self-application
((lambda (length)
   (lambda (ls)
     (cond                                           ((lambda (u) (u u))
      [(null? ls) 0]                                  (lambda (length)
      [else (add1 ((length length) (cdr ls)))])))       (lambda (ls)
 (lambda (length)                                         (cond
   (lambda (ls)                                            [(null? ls) 0]
     (cond                                                 [else (add1 ((length length) (cdr ls)))]))))
      [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))


                                                          Now we have only one self-
                                                          application left (why not two?)
Abstract Inner Self-application

                                                     ((lambda (u) (u u))
((lambda (u) (u u))                                   (lambda (length)
 (lambda (length)                                       ((lambda (g)
   (lambda (ls)                                            (lambda (ls)
     (cond                                                   (cond
      [(null? ls) 0]                                          [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))            [else (add1 (g (cdr ls)))])))
                                                         (length length))))



 We can now extract the inner
 self-application                                           •    Done in a very similar way
                                                                 as the outer one.
                                                            •    We may call it “factor out”
Function is there!

                                                     ((lambda (u) (u u))
((lambda (u) (u u))                                   (lambda (length)
 (lambda (length)                                       ((lambda (g)
   (lambda (ls)                                            (lambda (ls)
     (cond                                                   (cond
      [(null? ls) 0]                                          [(null? ls) 0]
      [else (add1 ((length length) (cdr ls)))]))))            [else (add1 (g (cdr ls)))])))
                                                         (length length))))




         • Notice that this part is exactly             (define length
                                                         (lambda (ls)
           the definition of “length”                      (cond
           (modulo alpha-equivalence)                       [(null? ls) 0]
                                                            [else (add1 (length (cdr ls)))])))
         • We are almost done!
Non-termination (CBV)
                                 used to be here

    ((lambda (u) (u u))
     (lambda (length)
       ((lambda (g)
          (lambda (ls)
            (cond
             [(null? ls) 0]
             [else (add1 (g (cdr ls)))])))
        (length length))))



•      But notice that (length length)
       went outside of (lambda (ls) …)
•      This will cause non-termination if
       the language is call-by-value
       (why?)
Eta-expansion

((lambda (u) (u u))                        ((lambda (u) (u u))
 (lambda (length)                           (lambda (length)
   ((lambda (g)                               ((lambda (g)
      (lambda (ls)                               (lambda (ls)
        (cond                                      (cond
         [(null? ls) 0]                             [(null? ls) 0]
         [else (add1 (g (cdr ls)))])))              [else (add1 (g (cdr ls)))])))
    (length length))))                         (lambda (v) ((length length) v))))


                                           •   Eta-expand (length length) will
                                               prevent the non-termination while
                                               preserving the semantics
Abstract out the function

                                                    ((lambda (f)
                                                      ((lambda (u) (u u))
((lambda (u) (u u))
                                                       (lambda (length)
 (lambda (length)
                                                         (f
   ((lambda (g)
                                                          (lambda (v) ((length length) v))))))
      (lambda (ls)
        (cond                            “length”
                                                    (lambda (g)
         [(null? ls) 0]
                                                      (lambda (ls)
         [else (add1 (g (cdr ls)))])))
                                                        (cond
    (lambda (v) ((length length) v))))
                                                         [(null? ls) 0]
                                                         [else (add1 (g (cdr ls)))]))))

                                                • Now we can factor out the
                                                  function “length”
                                                • Notice that we can now
                                                  substitute f for any function
                                                  and get a recursive definition!
This is Y combinator!
                                                               Y combinator!

                                         Y combinator
                                                        ((lambda (f)
                                                          ((lambda (u) (u u))
((lambda (u) (u u))
                                                           (lambda (length)
 (lambda (length)
                                                             (f
   ((lambda (g)
                                                              (lambda (v) ((length length) v))))))
      (lambda (ls)
        (cond                                “length”
                                                        (lambda (g)
         [(null? ls) 0]
                                                          (lambda (ls)
         [else (add1 (g (cdr ls)))])))
                                                            (cond
    (lambda (v) ((length length) v))))
                                                             [(null? ls) 0]
                                                             [else (add1 (g (cdr ls)))]))))

                                                    • Now we can factor out the
                                                      function “length”
                                                    • Notice that we can now
                                                      substitute f for any function
                                                      and get a recursive definition!
Renaming


(lambda (f)                                  (lambda (f)
 ((lambda (u) (u u))                           ((lambda (u) (u u))
  (lambda (length)                              (lambda (x)
    (f                                            (f
     (lambda (v) ((length length) v)))))           (lambda (v) ((x x) v))))))




Does the name “length” matter                      • Obviously no!
here?                                              • So we can rename it
Expanding


(lambda (f)                                    (lambda (f)
  ((lambda (u) (u u))                             ((lambda (x) (f (lambda (v) ((x x) v))))
   (lambda (x) (f (lambda (v) ((x x) v))))))       (lambda (x) (f (lambda (v) ((x x) v))))))




                                                   Or, if you would like self-
                                                   application expanded out,
                                                   this is just another form
CBV and CBN

                                  Y combinator (call-by-value)

                                       (lambda (f)
                                          ((lambda (x) (f (lambda (v) ((x x) v))))
                                           (lambda (x) (f (lambda (v) ((x x) v))))))



                                     Y combinator (call-by-name)

Or, if the language is call-by-        (lambda (f)
name, we get this instead                 ((lambda (x) (f (x x))))
(without eta-expansion)                    (lambda (x) (f (x x))))))
Test (length)
(((lambda (f)
    ((lambda (x) (f (lambda (v) ((x x) v))))
     (lambda (x) (f (lambda (v) ((x x) v))))))
  (lambda (length)
    (lambda (ls)
      (cond
       [(null? ls) 0]
       [else (add1 (length (cdr ls)))]))))
 '(a b c))

==> 3
Test (factorial)
(((lambda (f)
    ((lambda (x) (f (lambda (v) ((x x) v))))
     (lambda (x) (f (lambda (v) ((x x) v))))))
  (lambda (fact)
    (lambda (n)
      (cond
       [(zero? n) 1]
       [else (* n (fact (sub1 n)))]))))
 5)

==> 120

Weitere ähnliche Inhalte

Was ist angesagt?

What is knowledge representation and reasoning ?
What is knowledge representation and reasoning ?What is knowledge representation and reasoning ?
What is knowledge representation and reasoning ?Anant Soft Computing
 
5.2 primitive recursive functions
5.2 primitive recursive functions5.2 primitive recursive functions
5.2 primitive recursive functionsSampath Kumar S
 
Introduction to the theory of computation
Introduction to the theory of computationIntroduction to the theory of computation
Introduction to the theory of computationprasadmvreddy
 
Frontiers of Natural Language Processing
Frontiers of Natural Language ProcessingFrontiers of Natural Language Processing
Frontiers of Natural Language ProcessingSebastian Ruder
 
Ch3 4 regular expression and grammar
Ch3 4 regular expression and grammarCh3 4 regular expression and grammar
Ch3 4 regular expression and grammarmeresie tesfay
 
Machine Learning lecture4(logistic regression)
Machine Learning lecture4(logistic regression)Machine Learning lecture4(logistic regression)
Machine Learning lecture4(logistic regression)cairo university
 
Automata theory - Push Down Automata (PDA)
Automata theory - Push Down Automata (PDA)Automata theory - Push Down Automata (PDA)
Automata theory - Push Down Automata (PDA)Akila Krishnamoorthy
 
Artificial intelligence and knowledge representation
Artificial intelligence and knowledge representationArtificial intelligence and knowledge representation
Artificial intelligence and knowledge representationSajan Sahu
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeKnoldus Inc.
 
Context free grammars
Context free grammarsContext free grammars
Context free grammarsRonak Thakkar
 
Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Yasir Khan
 
Predicate calculus
Predicate calculusPredicate calculus
Predicate calculusRajendran
 
Unit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchUnit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchTekendra Nath Yogi
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithmmeisamstar
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using BacktrackingAbhishek Singh
 
Turing Machine
Turing MachineTuring Machine
Turing MachineRajendran
 
1.9. minimization of dfa
1.9. minimization of dfa1.9. minimization of dfa
1.9. minimization of dfaSampath Kumar S
 

Was ist angesagt? (20)

What is knowledge representation and reasoning ?
What is knowledge representation and reasoning ?What is knowledge representation and reasoning ?
What is knowledge representation and reasoning ?
 
A* Algorithm
A* AlgorithmA* Algorithm
A* Algorithm
 
5.2 primitive recursive functions
5.2 primitive recursive functions5.2 primitive recursive functions
5.2 primitive recursive functions
 
Introduction to the theory of computation
Introduction to the theory of computationIntroduction to the theory of computation
Introduction to the theory of computation
 
Frontiers of Natural Language Processing
Frontiers of Natural Language ProcessingFrontiers of Natural Language Processing
Frontiers of Natural Language Processing
 
Ch3 4 regular expression and grammar
Ch3 4 regular expression and grammarCh3 4 regular expression and grammar
Ch3 4 regular expression and grammar
 
Machine Learning lecture4(logistic regression)
Machine Learning lecture4(logistic regression)Machine Learning lecture4(logistic regression)
Machine Learning lecture4(logistic regression)
 
Automata theory - Push Down Automata (PDA)
Automata theory - Push Down Automata (PDA)Automata theory - Push Down Automata (PDA)
Automata theory - Push Down Automata (PDA)
 
Fuzzy set
Fuzzy set Fuzzy set
Fuzzy set
 
Artificial intelligence and knowledge representation
Artificial intelligence and knowledge representationArtificial intelligence and knowledge representation
Artificial intelligence and knowledge representation
 
Problem formulation
Problem formulationProblem formulation
Problem formulation
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing code
 
Context free grammars
Context free grammarsContext free grammars
Context free grammars
 
Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence
 
Predicate calculus
Predicate calculusPredicate calculus
Predicate calculus
 
Unit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchUnit3:Informed and Uninformed search
Unit3:Informed and Uninformed search
 
Unit26 shortest pathalgorithm
Unit26 shortest pathalgorithmUnit26 shortest pathalgorithm
Unit26 shortest pathalgorithm
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
Turing Machine
Turing MachineTuring Machine
Turing Machine
 
1.9. minimization of dfa
1.9. minimization of dfa1.9. minimization of dfa
1.9. minimization of dfa
 

Andere mochten auch

2012 05-08-lambda-draft
2012 05-08-lambda-draft2012 05-08-lambda-draft
2012 05-08-lambda-draftLin Jen-Shin
 
10 most inspirational entrepreneurship quotes by trep talks
10 most inspirational entrepreneurship quotes by trep talks10 most inspirational entrepreneurship quotes by trep talks
10 most inspirational entrepreneurship quotes by trep talksSushant Misra
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculusEdward Blurock
 
An Adventure in Serverless ClojureScript
An Adventure in Serverless ClojureScriptAn Adventure in Serverless ClojureScript
An Adventure in Serverless ClojureScriptNorman Richards
 
Pop group brochure autopop 2013
Pop group brochure   autopop 2013Pop group brochure   autopop 2013
Pop group brochure autopop 2013PopGroup
 
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov..."Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...Laurence Welford
 
Social Media Changed Events Forever. Here is Proof!
Social Media Changed Events Forever. Here is Proof!Social Media Changed Events Forever. Here is Proof!
Social Media Changed Events Forever. Here is Proof!Julius Solaris
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptNorman Richards
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at NetflixBrendan Gregg
 
Standard Treasury Series A Pitch Deck
Standard Treasury Series A Pitch DeckStandard Treasury Series A Pitch Deck
Standard Treasury Series A Pitch DeckZachary Townsend
 
TouristEye - Personalizing The Travel Experience - 500 Startups
TouristEye - Personalizing The Travel Experience - 500 StartupsTouristEye - Personalizing The Travel Experience - 500 Startups
TouristEye - Personalizing The Travel Experience - 500 Startups500 Startups
 
Square pitch deck
Square pitch deckSquare pitch deck
Square pitch deckpitchenvy
 
500’s Demo Day Batch 12 >> Alfred
500’s Demo Day Batch 12 >> Alfred500’s Demo Day Batch 12 >> Alfred
500’s Demo Day Batch 12 >> Alfred500 Startups
 
BrandBoards demo day pitch deck
BrandBoards demo day pitch deckBrandBoards demo day pitch deck
BrandBoards demo day pitch deck500 Startups
 

Andere mochten auch (20)

Y Combinator Overview
Y Combinator OverviewY Combinator Overview
Y Combinator Overview
 
2012 05-08-lambda-draft
2012 05-08-lambda-draft2012 05-08-lambda-draft
2012 05-08-lambda-draft
 
10 most inspirational entrepreneurship quotes by trep talks
10 most inspirational entrepreneurship quotes by trep talks10 most inspirational entrepreneurship quotes by trep talks
10 most inspirational entrepreneurship quotes by trep talks
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
 
An Adventure in Serverless ClojureScript
An Adventure in Serverless ClojureScriptAn Adventure in Serverless ClojureScript
An Adventure in Serverless ClojureScript
 
Pop group brochure autopop 2013
Pop group brochure   autopop 2013Pop group brochure   autopop 2013
Pop group brochure autopop 2013
 
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov..."Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...
"Inspiring Innovation" HSLU TEDx Event - "Resilience: Key to Successful Innov...
 
Social Media Changed Events Forever. Here is Proof!
Social Media Changed Events Forever. Here is Proof!Social Media Changed Events Forever. Here is Proof!
Social Media Changed Events Forever. Here is Proof!
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScript
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
Standard Treasury Series A Pitch Deck
Standard Treasury Series A Pitch DeckStandard Treasury Series A Pitch Deck
Standard Treasury Series A Pitch Deck
 
TouristEye - Personalizing The Travel Experience - 500 Startups
TouristEye - Personalizing The Travel Experience - 500 StartupsTouristEye - Personalizing The Travel Experience - 500 Startups
TouristEye - Personalizing The Travel Experience - 500 Startups
 
Square pitch deck
Square pitch deckSquare pitch deck
Square pitch deck
 
task.ly pitch deck
task.ly pitch decktask.ly pitch deck
task.ly pitch deck
 
Kibin
Kibin Kibin
Kibin
 
Binpress
BinpressBinpress
Binpress
 
Sverve
SverveSverve
Sverve
 
LaunchRock
LaunchRockLaunchRock
LaunchRock
 
500’s Demo Day Batch 12 >> Alfred
500’s Demo Day Batch 12 >> Alfred500’s Demo Day Batch 12 >> Alfred
500’s Demo Day Batch 12 >> Alfred
 
BrandBoards demo day pitch deck
BrandBoards demo day pitch deckBrandBoards demo day pitch deck
BrandBoards demo day pitch deck
 

Ähnlich wie Reinventing the Y combinator

Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: DeanonymizingDavid Evans
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
new features in jdk8
new features in jdk8new features in jdk8
new features in jdk8岩 夏
 
AutoDesk
AutoDeskAutoDesk
AutoDeskSE3D
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startupsbmlever
 
Syntactic Salt and Sugar Presentation
Syntactic Salt and Sugar PresentationSyntactic Salt and Sugar Presentation
Syntactic Salt and Sugar Presentationgrepalex
 
Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Aysylu Greenberg
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreXavier Coulon
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)Sami Said
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
Basic and logical implementation of r language
Basic and logical implementation of r language Basic and logical implementation of r language
Basic and logical implementation of r language Md. Mahedi Mahfuj
 
From Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn IntroductionFrom Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn Introductionelliando dias
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?Andreas Enbohm
 

Ähnlich wie Reinventing the Y combinator (20)

Clojure intro
Clojure introClojure intro
Clojure intro
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
new features in jdk8
new features in jdk8new features in jdk8
new features in jdk8
 
SacalaZa #1
SacalaZa #1SacalaZa #1
SacalaZa #1
 
AutoDesk
AutoDeskAutoDesk
AutoDesk
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
 
Syntactic Salt and Sugar Presentation
Syntactic Salt and Sugar PresentationSyntactic Salt and Sugar Presentation
Syntactic Salt and Sugar Presentation
 
Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a Datastore
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Scheme language
Scheme languageScheme language
Scheme language
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
Basic and logical implementation of r language
Basic and logical implementation of r language Basic and logical implementation of r language
Basic and logical implementation of r language
 
From Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn IntroductionFrom Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn Introduction
 
Java 8
Java 8Java 8
Java 8
 
Project Lambda - Closures after all?
Project Lambda - Closures after all?Project Lambda - Closures after all?
Project Lambda - Closures after all?
 

Kürzlich hochgeladen

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Kürzlich hochgeladen (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

Reinventing the Y combinator

  • 1. How to Reinvent the Y combinator Yin Wang
  • 2. Why do we need the Y combinator? For fundamental understanding of recursion, we hope to create recursive functions using the lambda calculus: x | t t | λx.t
  • 3. Why not define or letrec? (define length (letrec ([length (lambda (ls) (lambda (ls) (cond (cond [(null? ls) 0] [(null? ls) 0] [else (add1 (length (cdr ls)))]))) [else (add1 (length (cdr ls)))]))]) (length '(a b c))) 1. We don’t have define or letrec in lambda calculus 2. For fundamental understanding of recursion, we want to see how define and letrec can be created using just the three elements of lambda calculus: x | t t | λx.t 3. You will see how this understanding can be useful when constructing compilers
  • 4. Plan (define length (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))]))) • We start by constructing a recursive definition of “length” in a pure subset of Scheme • Then extract a common pattern that can be applied to recursive definitions in general • This common pattern is the Y combinator
  • 5. How do we do that? • First, notice we can’t really define a recursive function without binding it to a name • Second, answer this question: “Where can we bind something to a name?” • The answer is: λx.t • Lambda, the ultimate binder
  • 6. Step 1: Binder (define length (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))]))) • Step1: create a lambda similar to this define • This creates a binder where we can bind the function to • Our goal: bind the function “length” to the name length
  • 7. Step 1: Binder (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))]))) • Step1: create a lambda similar to this define • This creates a binder where we can bind the function to • Our goal: bind the function “length” to the name length
  • 8. Step 2: Copy ((lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))]))) (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))])))) • Make a copy of the function and apply itself to the copy (self-application) • This will successfully bind the name length to the function “itself”
  • 9. Step 3: Small fix ((lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))]))) (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) The first argument to the application of “length” should be itself
  • 10. Step 4: Extract Patterns ((lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))]))) (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) • This recursive function will work (try it!) • This is called “poor man’s Y” • Now we are going to extract the pattern in there, so that the same pattern works for any function.
  • 11. Step 4: Extract Patterns ((lambda (length) (lambda (ls) (cond • But we can’t see the original [(null? ls) 0] definition in there. [else (add1 ((length length) (cdr ls)))]))) • We hope to see this, but the (lambda (length) self-applications (length length) (lambda (ls) bother us. (cond • Hope we can get rid of them [(null? ls) 0] while preserving the semantics. [else (add1 ((length length) (cdr ls)))])))) • This recursive function will work (try it!) • This is called “poor man’s Y” (lambda (length) • Now we are going to extract the pattern (lambda (ls) (cond in there, so that the same pattern works [(null? ls) 0] for any function. [else (add1 (length (cdr ls)))])))
  • 12. Three Self-applications ((lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))]))) (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) Notice that this code has three self-aplications, one outer and two inner.
  • 13. Abstract Outer Self-application ((lambda (length) (lambda (ls) (cond ((lambda (u) (u u)) [(null? ls) 0] (lambda (length) [else (add1 ((length length) (cdr ls)))]))) (lambda (ls) (lambda (length) (cond (lambda (ls) [(null? ls) 0] (cond [else (add1 ((length length) (cdr ls)))])))) [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) • First, let’s extract the pattern which does the outer self- application • In compiler terms, this is called “common subexpression elimination”
  • 14. Inner Self-application ((lambda (length) (lambda (ls) (cond ((lambda (u) (u u)) [(null? ls) 0] (lambda (length) [else (add1 ((length length) (cdr ls)))]))) (lambda (ls) (lambda (length) (cond (lambda (ls) [(null? ls) 0] (cond [else (add1 ((length length) (cdr ls)))])))) [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) Now we have only one self- application left (why not two?)
  • 15. Abstract Inner Self-application ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (length) ((lambda (g) (lambda (ls) (lambda (ls) (cond (cond [(null? ls) 0] [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) [else (add1 (g (cdr ls)))]))) (length length)))) We can now extract the inner self-application • Done in a very similar way as the outer one. • We may call it “factor out”
  • 16. Function is there! ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (length) ((lambda (g) (lambda (ls) (lambda (ls) (cond (cond [(null? ls) 0] [(null? ls) 0] [else (add1 ((length length) (cdr ls)))])))) [else (add1 (g (cdr ls)))]))) (length length)))) • Notice that this part is exactly (define length (lambda (ls) the definition of “length” (cond (modulo alpha-equivalence) [(null? ls) 0] [else (add1 (length (cdr ls)))]))) • We are almost done!
  • 17. Non-termination (CBV) used to be here ((lambda (u) (u u)) (lambda (length) ((lambda (g) (lambda (ls) (cond [(null? ls) 0] [else (add1 (g (cdr ls)))]))) (length length)))) • But notice that (length length) went outside of (lambda (ls) …) • This will cause non-termination if the language is call-by-value (why?)
  • 18. Eta-expansion ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (length) ((lambda (g) ((lambda (g) (lambda (ls) (lambda (ls) (cond (cond [(null? ls) 0] [(null? ls) 0] [else (add1 (g (cdr ls)))]))) [else (add1 (g (cdr ls)))]))) (length length)))) (lambda (v) ((length length) v)))) • Eta-expand (length length) will prevent the non-termination while preserving the semantics
  • 19. Abstract out the function ((lambda (f) ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (length) (f ((lambda (g) (lambda (v) ((length length) v)))))) (lambda (ls) (cond “length” (lambda (g) [(null? ls) 0] (lambda (ls) [else (add1 (g (cdr ls)))]))) (cond (lambda (v) ((length length) v)))) [(null? ls) 0] [else (add1 (g (cdr ls)))])))) • Now we can factor out the function “length” • Notice that we can now substitute f for any function and get a recursive definition!
  • 20. This is Y combinator! Y combinator! Y combinator ((lambda (f) ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (length) (f ((lambda (g) (lambda (v) ((length length) v)))))) (lambda (ls) (cond “length” (lambda (g) [(null? ls) 0] (lambda (ls) [else (add1 (g (cdr ls)))]))) (cond (lambda (v) ((length length) v)))) [(null? ls) 0] [else (add1 (g (cdr ls)))])))) • Now we can factor out the function “length” • Notice that we can now substitute f for any function and get a recursive definition!
  • 21. Renaming (lambda (f) (lambda (f) ((lambda (u) (u u)) ((lambda (u) (u u)) (lambda (length) (lambda (x) (f (f (lambda (v) ((length length) v))))) (lambda (v) ((x x) v)))))) Does the name “length” matter • Obviously no! here? • So we can rename it
  • 22. Expanding (lambda (f) (lambda (f) ((lambda (u) (u u)) ((lambda (x) (f (lambda (v) ((x x) v)))) (lambda (x) (f (lambda (v) ((x x) v)))))) (lambda (x) (f (lambda (v) ((x x) v)))))) Or, if you would like self- application expanded out, this is just another form
  • 23. CBV and CBN Y combinator (call-by-value) (lambda (f) ((lambda (x) (f (lambda (v) ((x x) v)))) (lambda (x) (f (lambda (v) ((x x) v)))))) Y combinator (call-by-name) Or, if the language is call-by- (lambda (f) name, we get this instead ((lambda (x) (f (x x)))) (without eta-expansion) (lambda (x) (f (x x))))))
  • 24. Test (length) (((lambda (f) ((lambda (x) (f (lambda (v) ((x x) v)))) (lambda (x) (f (lambda (v) ((x x) v)))))) (lambda (length) (lambda (ls) (cond [(null? ls) 0] [else (add1 (length (cdr ls)))])))) '(a b c)) ==> 3
  • 25. Test (factorial) (((lambda (f) ((lambda (x) (f (lambda (v) ((x x) v)))) (lambda (x) (f (lambda (v) ((x x) v)))))) (lambda (fact) (lambda (n) (cond [(zero? n) 1] [else (* n (fact (sub1 n)))])))) 5) ==> 120