SlideShare a Scribd company logo
1 of 7
11.4 Lazy Evaluation
Once we have an interpreter, we can change the meaning of our language by changing
the evaluation rules.
This enables a new problem-solving strategy: if the solution to a problem cannot
be expressed easily in an existing language, define and implement an interpreter for a
new language in which the problem can be solved more easily.
This section explores a variation on Charme we call LazyCharme. LazyCharme changes
the application evaluation rule so that operand expressions are not evaluated until their
values are needed.
This is known as lazy evaluation. Lazy evaluation enables many procedures which
would otherwise be awkward to express to be defined concisely.
Since both Charme and LazyCharme are universal programming languages they
can express the same set of computations:
all of the procedures we define that take advantage of lazy evaluation could be defined
with eager evaluation (for example, by first defining a lazy interpreter as we do here).
11.4.1 Lazy Interpreter
The Charme interpreter as well as the standard Scheme language evaluate application
expressions eagerly: all operand subexpressions are evaluated whether or not their
values are needed.
This is known as eager evaluation. Eager evaluation means that any expression
that does not always evaluate all of its subexpressions must be a special form.
For example, there is no way to define a procedure that behaves like the if special
form. With lazy evaluation, an expression is evaluated only when its value is needed.
Lazy evaluation changes the evaluation rule for applications of constructed procedures.
Instead of evaluating all operand expressions, lazy evaluation delays evaluation of
an operand expression until the value of the parameter is needed.
To keep track of what is needed to perform the evaluation when and if it is needed, a
special object known as a thunk is created and stored in the place associated with the
parameter name.
By delaying evaluation of operand expressions until their value is needed, we can enable
programs to define procedures that conditionally evaluate their operands like the
if special form.
The lazy rule for applying constructed procedures is:
Lazy Application Rule 2: Constructed Procedures. To apply a
constructed procedure:
Construct a new environment, whose parent is the environment of the
applied procedure.
For each procedure parameter, create a place in the frame of the new environment with
the name of the parameter. Put a thunk in that place, which is an object that can
be used later to evaluate the value of the corresponding operand expression
if and when its value is needed.
Evaluate the body of the procedure in the newly created environment. The
resulting value is the value of the application.
The rule is identical to the Stateful Application Rule except for the bolded part of step
2.
To implement lazy evaluation we modify the interpreter to implement the
lazy application rule.
We start by defining a Python class for representing thunks and then modify the
interpreter to support lazy evaluation.
Making Thunks. A thunk keeps track of an expression whose evaluation is
delayed until it is needed.
Once the evaluation is performed, the resulting value is saved so the expression does not
need to be re-evaluated the next time the value is needed.
Thus, a thunk is in one of two possible states: unevaluated
andevaluated.
11.4.2 Lazy Programming
Lazy evaluation enables programming constructs that are not possible with eager
evaluation.
For example, with lazy evaluation we can define a procedure that behaves like
the if expression special form.
We first define true and false as procedures that take two parameters and output the first
or second parameter:
(define true (lambda (ab) a)) (define false (lambda (a b) b))
Then, this definition defines a procedure with
behavior similar to the if special form:
(define ifp (lambda (p c a) (p c a)))
With eager evaluation, this would not work since all operands would be evaluated; with
lazy evaluation, only the operand that corresponds to the appropriate consequent
or alternate expression is evaluated.
Lazy evaluation also enables programs to deal with seemingly infinite data structures.
This is possible since only those values of the apparently infinite data structure that are
used need to be created.
Suppose we define procedures similar to the Scheme procedures for manipulating pairs:
(define cons (lambda (ab) (lambda (p) (if pab)))) (define car (lambda (p) (ptrue)))
(define cdr (lambda (p) (pfalse))) (define nullfalse)
(define null? (lambda (x) (= x false)))
These behave similarly to the corresponding Scheme procedures, except in LazyCharme
their operands are evaluated lazily. This means, we can define an infinite list:
(define ints-from (lambda (n) (cons n (ints-from (+ n 1)))))
With eager evaluation, (ints-from 1) would never finish evaluating; it has no base case for
stopping the recursive applications.
In LazyCharme, however, the operands to the cons application in the body of ints-
from are not evaluated until they are needed.
Hence, (ints-from 1) terminates and produces a seemingly infinite list, but only the
evaluations that are needed are performed:
LazyCharme> (car (ints-from 1)) 1
LazyCharme> (car (cdr (cdr (cdr (ints-from 1))))) 4
Some evaluations fail to terminate even with lazy evaluation. For example, assume the
standard definition of list-length:
(define list-length
(lambda (lst) (if (null? lst) 0 (+ 1 (list-length (cdr lst))))))
An evaluation of (length (ints-from 1)) never
terminates.
Every time an application of list-length is evaluated, it applies cdr to the input list, which
causes ints-from to evaluate another cons, increasing the length of the list by one.
The actual length of the list is infinite, so the application of list-lengthdoes not
terminate. Lists with delayed evaluation can be used in useful programs.
Reconsider the Fibonacci sequence from Chapter 7. Using lazy evaluation, we can define
a list that is the infinitely long Fibonacci sequence:1

More Related Content

What's hot

2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method OverloadingMichael Heron
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageHossam Ghareeb
 
Notes: Verilog Part 5 - Tasks and Functions
Notes: Verilog Part 5 - Tasks and FunctionsNotes: Verilog Part 5 - Tasks and Functions
Notes: Verilog Part 5 - Tasks and FunctionsJay Baxi
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Programming in python w6
Programming in python w6Programming in python w6
Programming in python w6Priya Nayak
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014Noopur Gupta
 
Keywords in python
Keywords in pythonKeywords in python
Keywords in pythonPushpakBhoge
 
10 implementing subprograms
10 implementing subprograms10 implementing subprograms
10 implementing subprogramsMunawar Ahmed
 
Test 3 exam review guide
Test 3 exam review guideTest 3 exam review guide
Test 3 exam review guidebgb02burns
 
Pure functions
Pure functionsPure functions
Pure functionsPer Arneng
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes NUST Stuff
 
Highorderfunctions in swift
Highorderfunctions in swiftHighorderfunctions in swift
Highorderfunctions in swiftAhmet Keskin
 
Implicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingImplicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingVIKASH MAINANWAL
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming languageVasavi College of Engg
 

What's hot (20)

Function
FunctionFunction
Function
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
 
C#4.0 features
C#4.0 featuresC#4.0 features
C#4.0 features
 
Ch07
Ch07Ch07
Ch07
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Notes: Verilog Part 5 - Tasks and Functions
Notes: Verilog Part 5 - Tasks and FunctionsNotes: Verilog Part 5 - Tasks and Functions
Notes: Verilog Part 5 - Tasks and Functions
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Programming in python w6
Programming in python w6Programming in python w6
Programming in python w6
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014
 
Keywords in python
Keywords in pythonKeywords in python
Keywords in python
 
scope of python
scope of pythonscope of python
scope of python
 
10 implementing subprograms
10 implementing subprograms10 implementing subprograms
10 implementing subprograms
 
Test 3 exam review guide
Test 3 exam review guideTest 3 exam review guide
Test 3 exam review guide
 
Pure functions
Pure functionsPure functions
Pure functions
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
 
Functions
FunctionsFunctions
Functions
 
Unit 4
Unit 4Unit 4
Unit 4
 
Highorderfunctions in swift
Highorderfunctions in swiftHighorderfunctions in swift
Highorderfunctions in swift
 
Implicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingImplicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handling
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 

Viewers also liked

My trip in hokkaido
My trip in hokkaidoMy trip in hokkaido
My trip in hokkaidoR. Ayakix
 
Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012paniczone
 
list procedures
list procedureslist procedures
list proceduresRajendran
 
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCMNhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCMTien Thao
 
Cv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunicationCv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunicationFaisal Mehmood
 
Proyecto de vida zz
Proyecto de vida zzProyecto de vida zz
Proyecto de vida zzZurdo Cano
 
Упасть, чтобы подняться
Упасть, чтобы поднятьсяУпасть, чтобы подняться
Упасть, чтобы поднятьсяsmartnick
 
Tratamiento para crecer el cabello
Tratamiento para crecer el cabelloTratamiento para crecer el cabello
Tratamiento para crecer el cabelloamientqol
 
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...Tien Thao
 
Relaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra SalazarRelaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra SalazarSandraEliSalazar
 
Loichucvui
LoichucvuiLoichucvui
LoichucvuiHa Hoa
 
Dusaodinua
DusaodinuaDusaodinua
DusaodinuaHa Hoa
 
Lebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukLebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukInna Slobodyanyuk
 

Viewers also liked (16)

Nicole mejia
Nicole mejiaNicole mejia
Nicole mejia
 
My trip in hokkaido
My trip in hokkaidoMy trip in hokkaido
My trip in hokkaido
 
Trampo rods
Trampo rodsTrampo rods
Trampo rods
 
Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012Volantes #OpPaperStormSv 15 de Septiembre 2012
Volantes #OpPaperStormSv 15 de Septiembre 2012
 
list procedures
list procedureslist procedures
list procedures
 
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCMNhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
Nhận tổ chức sự kiện, khánh thành, khởi công chuyên nghiệp nhất tại TPHCM
 
Cv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunicationCv faisal mehmood-telecommunication
Cv faisal mehmood-telecommunication
 
Proyecto de vida zz
Proyecto de vida zzProyecto de vida zz
Proyecto de vida zz
 
Упасть, чтобы подняться
Упасть, чтобы поднятьсяУпасть, чтобы подняться
Упасть, чтобы подняться
 
Tratamiento para crecer el cabello
Tratamiento para crecer el cabelloTratamiento para crecer el cabello
Tratamiento para crecer el cabello
 
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng  tạ...
Tổ chức sự kiện khai trương, khánh thành uy tín,chuyên nghiệp, chất lượng tạ...
 
Bokstavelig!
Bokstavelig!Bokstavelig!
Bokstavelig!
 
Relaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra SalazarRelaciones entre los Seres Vivos por Sandra Salazar
Relaciones entre los Seres Vivos por Sandra Salazar
 
Loichucvui
LoichucvuiLoichucvui
Loichucvui
 
Dusaodinua
DusaodinuaDusaodinua
Dusaodinua
 
Lebenslauf Inna Slobodyanyuk
Lebenslauf Inna SlobodyanyukLebenslauf Inna Slobodyanyuk
Lebenslauf Inna Slobodyanyuk
 

Similar to lazy evaluation

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfDeeptiMalhotra19
 
LISP: Program structure in lisp
LISP: Program structure in lispLISP: Program structure in lisp
LISP: Program structure in lispLISP Content
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
A Verified Modern SAT Solver
A Verified Modern SAT SolverA Verified Modern SAT Solver
A Verified Modern SAT SolverKatie Naple
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwMayankSinghRawat6
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
session-1_Design_Analysis_Algorithm.pptx
session-1_Design_Analysis_Algorithm.pptxsession-1_Design_Analysis_Algorithm.pptx
session-1_Design_Analysis_Algorithm.pptxchandankumar364348
 
Unit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxUnit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxdickonsondorris
 

Similar to lazy evaluation (20)

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Function in C++
Function in C++Function in C++
Function in C++
 
procedures
proceduresprocedures
procedures
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
 
LISP:Program structure in lisp
LISP:Program structure in lispLISP:Program structure in lisp
LISP:Program structure in lisp
 
LISP: Program structure in lisp
LISP: Program structure in lispLISP: Program structure in lisp
LISP: Program structure in lisp
 
python
pythonpython
python
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
Mule expression
Mule expressionMule expression
Mule expression
 
A Verified Modern SAT Solver
A Verified Modern SAT SolverA Verified Modern SAT Solver
A Verified Modern SAT Solver
 
Functions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjwFunctions in Python.pdfnsjiwshkwijjahuwjwjw
Functions in Python.pdfnsjiwshkwijjahuwjwjw
 
final pl paper
final pl paperfinal pl paper
final pl paper
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
session-1_Design_Analysis_Algorithm.pptx
session-1_Design_Analysis_Algorithm.pptxsession-1_Design_Analysis_Algorithm.pptx
session-1_Design_Analysis_Algorithm.pptx
 
Unit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docxUnit 2 Modeling of Programs A function maps inputs to out.docx
Unit 2 Modeling of Programs A function maps inputs to out.docx
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower boundsRajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsRajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statisticsRajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theoremRajendran
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 
Master method
Master method Master method
Master method Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisRajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of QuicksortRajendran
 
Np completeness
Np completenessNp completeness
Np completenessRajendran
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

lazy evaluation

  • 1. 11.4 Lazy Evaluation Once we have an interpreter, we can change the meaning of our language by changing the evaluation rules. This enables a new problem-solving strategy: if the solution to a problem cannot be expressed easily in an existing language, define and implement an interpreter for a new language in which the problem can be solved more easily. This section explores a variation on Charme we call LazyCharme. LazyCharme changes the application evaluation rule so that operand expressions are not evaluated until their values are needed. This is known as lazy evaluation. Lazy evaluation enables many procedures which would otherwise be awkward to express to be defined concisely. Since both Charme and LazyCharme are universal programming languages they can express the same set of computations: all of the procedures we define that take advantage of lazy evaluation could be defined with eager evaluation (for example, by first defining a lazy interpreter as we do here).
  • 2. 11.4.1 Lazy Interpreter The Charme interpreter as well as the standard Scheme language evaluate application expressions eagerly: all operand subexpressions are evaluated whether or not their values are needed. This is known as eager evaluation. Eager evaluation means that any expression that does not always evaluate all of its subexpressions must be a special form. For example, there is no way to define a procedure that behaves like the if special form. With lazy evaluation, an expression is evaluated only when its value is needed. Lazy evaluation changes the evaluation rule for applications of constructed procedures. Instead of evaluating all operand expressions, lazy evaluation delays evaluation of an operand expression until the value of the parameter is needed. To keep track of what is needed to perform the evaluation when and if it is needed, a special object known as a thunk is created and stored in the place associated with the parameter name. By delaying evaluation of operand expressions until their value is needed, we can enable programs to define procedures that conditionally evaluate their operands like the if special form.
  • 3. The lazy rule for applying constructed procedures is: Lazy Application Rule 2: Constructed Procedures. To apply a constructed procedure: Construct a new environment, whose parent is the environment of the applied procedure. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Put a thunk in that place, which is an object that can be used later to evaluate the value of the corresponding operand expression if and when its value is needed. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application. The rule is identical to the Stateful Application Rule except for the bolded part of step 2. To implement lazy evaluation we modify the interpreter to implement the lazy application rule. We start by defining a Python class for representing thunks and then modify the interpreter to support lazy evaluation.
  • 4. Making Thunks. A thunk keeps track of an expression whose evaluation is delayed until it is needed. Once the evaluation is performed, the resulting value is saved so the expression does not need to be re-evaluated the next time the value is needed. Thus, a thunk is in one of two possible states: unevaluated andevaluated.
  • 5. 11.4.2 Lazy Programming Lazy evaluation enables programming constructs that are not possible with eager evaluation. For example, with lazy evaluation we can define a procedure that behaves like the if expression special form. We first define true and false as procedures that take two parameters and output the first or second parameter: (define true (lambda (ab) a)) (define false (lambda (a b) b)) Then, this definition defines a procedure with behavior similar to the if special form: (define ifp (lambda (p c a) (p c a))) With eager evaluation, this would not work since all operands would be evaluated; with lazy evaluation, only the operand that corresponds to the appropriate consequent or alternate expression is evaluated. Lazy evaluation also enables programs to deal with seemingly infinite data structures. This is possible since only those values of the apparently infinite data structure that are used need to be created.
  • 6. Suppose we define procedures similar to the Scheme procedures for manipulating pairs: (define cons (lambda (ab) (lambda (p) (if pab)))) (define car (lambda (p) (ptrue))) (define cdr (lambda (p) (pfalse))) (define nullfalse) (define null? (lambda (x) (= x false))) These behave similarly to the corresponding Scheme procedures, except in LazyCharme their operands are evaluated lazily. This means, we can define an infinite list: (define ints-from (lambda (n) (cons n (ints-from (+ n 1))))) With eager evaluation, (ints-from 1) would never finish evaluating; it has no base case for stopping the recursive applications. In LazyCharme, however, the operands to the cons application in the body of ints- from are not evaluated until they are needed. Hence, (ints-from 1) terminates and produces a seemingly infinite list, but only the evaluations that are needed are performed: LazyCharme> (car (ints-from 1)) 1 LazyCharme> (car (cdr (cdr (cdr (ints-from 1))))) 4 Some evaluations fail to terminate even with lazy evaluation. For example, assume the standard definition of list-length: (define list-length (lambda (lst) (if (null? lst) 0 (+ 1 (list-length (cdr lst))))))
  • 7. An evaluation of (length (ints-from 1)) never terminates. Every time an application of list-length is evaluated, it applies cdr to the input list, which causes ints-from to evaluate another cons, increasing the length of the list by one. The actual length of the list is infinite, so the application of list-lengthdoes not terminate. Lists with delayed evaluation can be used in useful programs. Reconsider the Fibonacci sequence from Chapter 7. Using lazy evaluation, we can define a list that is the infinitely long Fibonacci sequence:1