Continuations allow saving and restoring the execution context of a program, enabling time travel capabilities to pause execution and resume it later from the saved point; continuation passing style converts programs to pass continuations as arguments rather than returning values from functions; delimited continuations provide a more controlled way to capture partial continuations up to a defined boundary rather than the entire remaining computation.
This talk covers a novel approach to "name binding" in syntax trees for programming languages that makes it much easier to write compilers and interpreters with a higher degree of assurance.
Exceptions are runtime errors that a program may encounter. There are two types: synchronous from faults in input data, and asynchronous from external events. Exception handling uses try, throw, and catch keywords. Code that may cause exceptions is placed in a try block. When an exception occurs it is thrown, and the catch block handles it to prevent program termination. Multiple catch blocks can handle different exception types, and a catch-all block uses ellipses to catch any exception.
Static Data Members and Member FunctionsMOHIT AGARWAL
Static data members and static member functions in C++ classes are shared by all objects of that class. Static data members are initialized to zero when the first object is created and shared across all instances, while static member functions can only access other static members and are called using the class name and scope resolution operator. The example program demonstrates a class with a static data member "count" that is incremented and accessed by multiple objects to assign increasing code values, and a static member function "showcount" that prints the shared count value.
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
This document discusses polymorphism in C++. It defines polymorphism as the ability for functions or operators to have different meanings depending on the context. It describes different types of polymorphism including static and dynamic polymorphism. It then provides examples of method overloading, operator overloading, and virtual functions to illustrate polymorphism concepts in C++.
Complete C++ programming Language CourseVivek chan
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without the use of operators. We can define operators as symbols that helps us to perform specific mathematical and logical computations on operands. In other words we can say that an operator operates the operands.
This talk covers a novel approach to "name binding" in syntax trees for programming languages that makes it much easier to write compilers and interpreters with a higher degree of assurance.
Exceptions are runtime errors that a program may encounter. There are two types: synchronous from faults in input data, and asynchronous from external events. Exception handling uses try, throw, and catch keywords. Code that may cause exceptions is placed in a try block. When an exception occurs it is thrown, and the catch block handles it to prevent program termination. Multiple catch blocks can handle different exception types, and a catch-all block uses ellipses to catch any exception.
Static Data Members and Member FunctionsMOHIT AGARWAL
Static data members and static member functions in C++ classes are shared by all objects of that class. Static data members are initialized to zero when the first object is created and shared across all instances, while static member functions can only access other static members and are called using the class name and scope resolution operator. The example program demonstrates a class with a static data member "count" that is incremented and accessed by multiple objects to assign increasing code values, and a static member function "showcount" that prints the shared count value.
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
This document discusses polymorphism in C++. It defines polymorphism as the ability for functions or operators to have different meanings depending on the context. It describes different types of polymorphism including static and dynamic polymorphism. It then provides examples of method overloading, operator overloading, and virtual functions to illustrate polymorphism concepts in C++.
Complete C++ programming Language CourseVivek chan
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without the use of operators. We can define operators as symbols that helps us to perform specific mathematical and logical computations on operands. In other words we can say that an operator operates the operands.
This document discusses multiple inheritance in C++. It defines multiple inheritance as a class inheriting from more than one base class. An example program is provided to demonstrate multiple inheritance, with a student class inheriting privately from both an info class and a result class. The document notes that multiple inheritance is useful when a derived class needs functionality from multiple base classes. It concludes with a summary of inheritance and its classifications.
Object Oriented Programming : A Brief History and its significanceGajesh Bhat
A Brief history and significance of Object Oriented Programming and about its past and present. Presented as a Part of Class assignment for Visual Programming Class.
This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Python-04| Fundamental data types vs immutabilityMohd Sajjad
Fundamental data types like integers, floats, booleans and strings are immutable in Python. Immutable means the object cannot be changed once created. For integers from 0 to 256, Python reuses the same integer objects to save memory. It also reuses the two boolean objects for True and False. For strings, a new object is created each time due to the large number of possible string values. Floats and complexes are also immutable and do not reuse objects. Immutability helps improve performance and memory usage in Python.
Les variables, telles que nous les avons vues dans les chapitres précédents, ne permettent de stocker qu'une seule donnée à la fois. Or, pour de très nombreux programmes, on a besoin d'avoir plusieurs données du même type et qui jouent quasiment le même rôle. Pensez par exemple à la liste des utilisateurs d'un site web, cela représente plusieurs variables de type string.
L’utilisation des variables distinctes, dans ce cas, seraient beaucoup trop lourdes à gérer. Heureusement, le C++ propose un moyen simple de regrouper ces données dans un seul support. Il s’agit des tableaux.
Les tableaux sont des structures de données constituées d'un certain nombre d'éléments de même type. Ils correspondent aux vecteurs et matrices en mathématiques. Un tableau est caractérisé par sa taille et par le type de ses éléments.
Dans ce chapitre, je vais vous apprendre à manipuler deux sortes de tableaux :
Les tableaux statiques : ceux dont la taille est connue à l'avance, elle est donc figée une fois pour toute et ne peut pas être modifiée en cours d'exécution du programme.
Les tableaux dynamiques : ceux dont la taille peut varier au cours de l'exécution du programme.
Les chaînes de caractères sont déclarées en C++ comme tableaux de caractères et permettent l'utilisation d'un certain nombre de notations et de fonctions spéciales. Les particularités des tableaux de caractères seront traitées séparément à la fin de ce chapitre.
Learn and master the Conditional statements, conditional expressions and logical expressions in Python. These slides are part of the Python Masterclass by Python Whiz
Python Programming - VI. Classes and ObjectsRanel Padon
This document discusses classes and objects in Python programming. It covers key concepts like class attributes, instantiating classes to create objects, using constructors and destructors, composition where objects have other objects as attributes, and referencing objects. The document uses examples like a Time class to demonstrate class syntax and how to define attributes and behaviors for classes.
The document provides an introduction to Python programming. It discusses key concepts like variables, data types, operators, and sequential data types. Python is presented as an interpreted programming language that uses indentation to indicate blocks of code. Comments and documentation are included to explain the code. Various data types are covered, including numbers, strings, booleans, and lists. Operators for arithmetic, comparison, assignment and more are also summarized.
Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program. We will discuss these in turn.
This document summarizes an introductory session on object-oriented programming in Python. It introduces key concepts of OOP like classes, objects, attributes, methods, encapsulation, inheritance and provides examples of defining classes for a Person and Bank Account. It also demonstrates how to define a class, create objects, access attributes and methods in Python. The benefits of OOP like code reusability, abstraction and inheritance are discussed.
Let'Swift 2019 컨퍼런스에서 RxSwift to Combine 이라고 발표한 자료입니다. 자료 내에 언급되는 코드 링크는 다음과 같습니다.
[BringMyOwnBeer]
• RxSwift/RxCocoa: https://github.com/fimuxd/BringMyOwnBeer-
• Combine/SwiftUI: https://github.com/fimuxd/BringMyOwnBeer-Combine
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
Valgrind is a suite of tools for debugging and profiling C and C++ programs. Memcheck is its most popular tool for detecting memory errors like leaks, accesses to uninitialized memory, and invalid reads/writes. It works by instrumenting the program binary to track "V-bits" and "A-bits" associated with each value and memory location. When the program is executed, Memcheck checks these bits to detect errors and produces detailed error reports with stack traces. The tutorial provides instructions on running Memcheck, understanding its output, and using options like suppressions and attaching a debugger. It also briefly describes how Memcheck works and lists some other Valgrind tools.
Virtual functions allow dynamic binding in C++ by allowing a function to be overridden in a derived class. A function is declared virtual by using the virtual keyword. At runtime, the compiler will call the version of a virtual function that is defined in the object's own class, rather than being bound at compile time like regular functions. This allows a base class pointer or reference to call a derived class implementation of a virtual function. Classes that contain virtual functions are called polymorphic classes.
This document describes the steps to convert a TensorFlow model to a TensorRT engine for inference. It includes steps to parse the model, optimize it, generate a runtime engine, serialize and deserialize the engine, as well as perform inference using the engine. It also provides code snippets for a PReLU plugin implementation in C++.
Asynchronous programming done right - Node.jsPiotr Pelczar
This document discusses asynchronous programming and avoiding race conditions. It covers how asynchronous actions allow the main program flow to continue processing without blocking on I/O. It also discusses how asynchronous programming works with callbacks and promises rather than sequential execution. It provides examples of using libraries like Async to control asynchronous flows and common pitfalls to avoid like double callbacks and unexpected asynchronous behavior.
The Ring programming language version 1.8 book - Part 88 of 202Mahmoud Samir Fayed
This document discusses embedding Ring code within Ring programs and applications using the Ring virtual machine. It provides functions for executing Ring code in isolated environments to avoid conflicts between different code sections. Examples show initializing Ring states, running code within a state, passing variables between states, and executing Ring files and programs from within Ring applications. The ability to embed Ring programs within each other in a controlled way allows for modular and extensible Ring applications.
This document discusses multiple inheritance in C++. It defines multiple inheritance as a class inheriting from more than one base class. An example program is provided to demonstrate multiple inheritance, with a student class inheriting privately from both an info class and a result class. The document notes that multiple inheritance is useful when a derived class needs functionality from multiple base classes. It concludes with a summary of inheritance and its classifications.
Object Oriented Programming : A Brief History and its significanceGajesh Bhat
A Brief history and significance of Object Oriented Programming and about its past and present. Presented as a Part of Class assignment for Visual Programming Class.
This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Python-04| Fundamental data types vs immutabilityMohd Sajjad
Fundamental data types like integers, floats, booleans and strings are immutable in Python. Immutable means the object cannot be changed once created. For integers from 0 to 256, Python reuses the same integer objects to save memory. It also reuses the two boolean objects for True and False. For strings, a new object is created each time due to the large number of possible string values. Floats and complexes are also immutable and do not reuse objects. Immutability helps improve performance and memory usage in Python.
Les variables, telles que nous les avons vues dans les chapitres précédents, ne permettent de stocker qu'une seule donnée à la fois. Or, pour de très nombreux programmes, on a besoin d'avoir plusieurs données du même type et qui jouent quasiment le même rôle. Pensez par exemple à la liste des utilisateurs d'un site web, cela représente plusieurs variables de type string.
L’utilisation des variables distinctes, dans ce cas, seraient beaucoup trop lourdes à gérer. Heureusement, le C++ propose un moyen simple de regrouper ces données dans un seul support. Il s’agit des tableaux.
Les tableaux sont des structures de données constituées d'un certain nombre d'éléments de même type. Ils correspondent aux vecteurs et matrices en mathématiques. Un tableau est caractérisé par sa taille et par le type de ses éléments.
Dans ce chapitre, je vais vous apprendre à manipuler deux sortes de tableaux :
Les tableaux statiques : ceux dont la taille est connue à l'avance, elle est donc figée une fois pour toute et ne peut pas être modifiée en cours d'exécution du programme.
Les tableaux dynamiques : ceux dont la taille peut varier au cours de l'exécution du programme.
Les chaînes de caractères sont déclarées en C++ comme tableaux de caractères et permettent l'utilisation d'un certain nombre de notations et de fonctions spéciales. Les particularités des tableaux de caractères seront traitées séparément à la fin de ce chapitre.
Learn and master the Conditional statements, conditional expressions and logical expressions in Python. These slides are part of the Python Masterclass by Python Whiz
Python Programming - VI. Classes and ObjectsRanel Padon
This document discusses classes and objects in Python programming. It covers key concepts like class attributes, instantiating classes to create objects, using constructors and destructors, composition where objects have other objects as attributes, and referencing objects. The document uses examples like a Time class to demonstrate class syntax and how to define attributes and behaviors for classes.
The document provides an introduction to Python programming. It discusses key concepts like variables, data types, operators, and sequential data types. Python is presented as an interpreted programming language that uses indentation to indicate blocks of code. Comments and documentation are included to explain the code. Various data types are covered, including numbers, strings, booleans, and lists. Operators for arithmetic, comparison, assignment and more are also summarized.
Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program. We will discuss these in turn.
This document summarizes an introductory session on object-oriented programming in Python. It introduces key concepts of OOP like classes, objects, attributes, methods, encapsulation, inheritance and provides examples of defining classes for a Person and Bank Account. It also demonstrates how to define a class, create objects, access attributes and methods in Python. The benefits of OOP like code reusability, abstraction and inheritance are discussed.
Let'Swift 2019 컨퍼런스에서 RxSwift to Combine 이라고 발표한 자료입니다. 자료 내에 언급되는 코드 링크는 다음과 같습니다.
[BringMyOwnBeer]
• RxSwift/RxCocoa: https://github.com/fimuxd/BringMyOwnBeer-
• Combine/SwiftUI: https://github.com/fimuxd/BringMyOwnBeer-Combine
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
Valgrind is a suite of tools for debugging and profiling C and C++ programs. Memcheck is its most popular tool for detecting memory errors like leaks, accesses to uninitialized memory, and invalid reads/writes. It works by instrumenting the program binary to track "V-bits" and "A-bits" associated with each value and memory location. When the program is executed, Memcheck checks these bits to detect errors and produces detailed error reports with stack traces. The tutorial provides instructions on running Memcheck, understanding its output, and using options like suppressions and attaching a debugger. It also briefly describes how Memcheck works and lists some other Valgrind tools.
Virtual functions allow dynamic binding in C++ by allowing a function to be overridden in a derived class. A function is declared virtual by using the virtual keyword. At runtime, the compiler will call the version of a virtual function that is defined in the object's own class, rather than being bound at compile time like regular functions. This allows a base class pointer or reference to call a derived class implementation of a virtual function. Classes that contain virtual functions are called polymorphic classes.
This document describes the steps to convert a TensorFlow model to a TensorRT engine for inference. It includes steps to parse the model, optimize it, generate a runtime engine, serialize and deserialize the engine, as well as perform inference using the engine. It also provides code snippets for a PReLU plugin implementation in C++.
Asynchronous programming done right - Node.jsPiotr Pelczar
This document discusses asynchronous programming and avoiding race conditions. It covers how asynchronous actions allow the main program flow to continue processing without blocking on I/O. It also discusses how asynchronous programming works with callbacks and promises rather than sequential execution. It provides examples of using libraries like Async to control asynchronous flows and common pitfalls to avoid like double callbacks and unexpected asynchronous behavior.
The Ring programming language version 1.8 book - Part 88 of 202Mahmoud Samir Fayed
This document discusses embedding Ring code within Ring programs and applications using the Ring virtual machine. It provides functions for executing Ring code in isolated environments to avoid conflicts between different code sections. Examples show initializing Ring states, running code within a state, passing variables between states, and executing Ring files and programs from within Ring applications. The ability to embed Ring programs within each other in a controlled way allows for modular and extensible Ring applications.
The document discusses porting the readline library to Ruby. It proposes either extending readline with Ruby or building a new readline-like library in Ruby called ReadRhine. ReadRhine uses an MVC architecture with separate models, views, and controls. It aims to have a unit test friendly design with spec files for components like the buffer and completion. The document outlines available commands and how to define keys in an internal DSL. It also lists some TODO items like improving completion and handling signals safely.
Tail recursion is when a recursive call is the last thing executed by a function. This allows the call stack to reuse stack frames rather than building up the call stack, avoiding stack overflow issues. A tail recursive function calculates results as it goes rather than waiting to return from recursive calls. This optimization makes tail recursive functions more efficient than regular recursive functions in terms of speed and memory usage.
Tail recursion is a type of recursion where the recursive call is the last thing executed by the function. This allows the compiler to optimize recursion by reusing the stack frame rather than allocating a new one for each recursive call. The key advantage is that tail recursive functions can process recursive problems of any size without overflowing the stack. Some examples show how a factorial function can be written iteratively using tail recursion, avoiding wasting memory on multiple stack frames.
The document discusses procedure activations and lifetimes. It provides an example of an activation tree for a quicksort program, showing the nested calls to procedures like partition and quicksort. It describes how activation records are used to store state and pass parameters during procedure calls, including the use of control links and access links to manage nested procedures and nonlocal data.
This document provides an introduction to SystemVerilog assertions in Japanese. It discusses what assertions are, the different types of assertions including concurrent and immediate assertions. It covers the SystemVerilog assertion checker library, how to write custom assertions, advanced assertion features like implication and repetition operators. It also provides examples of how to use assertions to check behaviors like interface protocols, temporal relationships and FSM operations.
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
The document describes embedding Ring code in Ring programs without sharing state. It allows quick integration of Ring programs and applications together without conflicts by executing Ring code in isolated environments. Functions like ring_state_init(), ring_state_runcode(), and ring_state_delete() are used to initialize a state, run code in it, and delete it. This prevents variables from one state being accessible from another. Serial execution of Ring applications is also demonstrated using ring_state_main().
The document provides an overview of key concepts in C programming including variables, data types, operators, control flow structures like decisions and loops, and functions. It discusses how computers perform simple tasks like addition via inputs, storage in memory, processing, and outputs. Examples are provided to illustrate concepts like printf formatting, if/else statements, for/while loops, and break/continue keywords. Self-check questions review variable definitions, loop execution, and output of sample programs.
This document discusses implementing a job queue in Golang. It begins by explaining buffered and unbuffered channels, and shows examples of using channels to coordinate goroutines. It then demonstrates how to build a job queue that uses a channel to enqueue jobs and have worker goroutines process jobs from the channel concurrently. It also discusses ways to gracefully shutdown workers using contexts and wait groups. Finally, it covers topics like auto-scaling agents, communicating between servers and agents, and handling job cancellation.
Async Debugging - A Practical Guide to survive !Mirco Vanini
This document provides an overview of async debugging techniques. It discusses how async code uses an "async logical call stack" rather than a physical call stack due to the use of continuations. It demonstrates how the debugger can show this async call stack to understand the flow of async code. It also covers other async debugging windows and tools like the tasks window, threads window, and parallel watch. The document provides examples of async code and how it is decomposed by the compiler into state machines. It concludes with some tips for writing high-quality async code to facilitate debugging.
Functional programming with Ruby - can make you look smartChen Fisher
Functional programming can make you look smart and others feel stupid. Learn how with Ruby
code can be found here:
https://github.com/chenfisher/functional-programming-with-ruby
Youtube:
https://www.youtube.com/watch?v=Qzoh8w4OPtU
The Ring programming language version 1.3 book - Part 59 of 88Mahmoud Samir Fayed
The document provides details about printing the final intermediate code generated after executing a Ring program.
It begins by showing the output of running a test Ring program and printing the bytecode. This includes the byte code instructions, operation codes, program counter, data, and other details.
It then shows sections of the large intermediate code output, including function and method definitions, variable assignments, calls between functions, and other low-level operations.
The document explains that the output provides a detailed view of the final bytecode generated from the Ring source code after it has been executed by the Ring virtual machine. This allows viewing and understanding the low-level operations performed during program execution.
Why do we need promises? How does promises compare to a simple callback approach or modules like async? Are promises just a hype or a new standard for asynchronous code?
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
The document discusses different types of control statements in C programming including decision control statements, iteration statements, and transfer statements. It provides details about if, if-else, switch, while, do-while, for loops. Decision control statements like if, if-else, switch allow altering the flow of execution based on certain conditions. Iteration statements like while, do-while, for are used to repeat a block of code until the given condition is true. They allow looping in a program.
The document introduces different types of loops in C programming including while, for, and do-while loops. It explains that loops allow repeated execution of a block of code until a certain condition is met. The key types of loops are pretest and post-test loops, which differ in when the loop condition is evaluated. It provides examples of implementing various loops in C and using concepts like initialization, updating, nesting, and break/continue statements.
PL/SQL is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database, Times Ten in-memory database, and IBM DB 2. Oracle Corporation usually extends PL/SQL functionality with each successive release of the Oracle Database.
14. class ControlCentre
def exploreTerrain
marsPlateau = Plateau.new(5, 5)
alpha = Rover.new("alpha")
c = nil
source = callcc do |cc|
c = cc
Position.new(1, 2, "N")
end
alpha.land(marsPlateau, source)
destination = alpha.explore("LMLMLMLMM")
print destination
return c
end
end
> c = exploreTerrain
“1 3 N”
=> #<Continuation:0xb7466240>
> c.call(Position.new(2, 3, “E”))
“2 4 E”
=> #<Continuation:0xb7466240>
15. Normal Control Flow with Continuation invoked
Control Flow Continuations with different parameters
continuation
continuation With different
parameters
16. def continuation
puts "i do some computation " +
"& save the state of execution."
m = callcc { |cc| return cc }
puts "then i restart the execution from " +
"the saved state & pass custom " +
"values such as "#{m[0]}" and "#{m[1]}""
end
> c = continuation
i do some computation & save the state of execution.
> c.call("so..", "then..")
then i restart the execution from the saved state & pass custom
values such as "so.." and "then.."
17. Normal Control Flow with Continuation reinvoked
Control Flow Continuations paused with parameters
continuation
With parameters
continuation
18.
19. Continuation?
●
A continuation reifies the control flow of a
program as just another data value
●
Reify – To consider an abstract concept to be
real. To make control flow as first class
functions/objects.
20. Continuation
●
Continuation is an object that takes a
snapshot copy of the running process.
●
The current process is copied and saved.
●
Current process – execution context and
all local variables
21. Normal Control Flow marked with
Control Flow continuation
Memory
Local variables
#
continuation
22. A new process that
invokes a continuation
Memory
#
The current execution is abandoned
Note: Global data does not
get stored in a continuation
23. Continuations
●
A Continuation stores the execution context, its
references and pointers.
●
However, it does not store the heap data or
data that is outside the scope of local
references and pointers.
●
So any change made to them will stay changed
even after invoking the continuation.
26. call-with-current-continuation
●
call-with-current-continuation, in short
called as “call/cc” is a procedure first
introduced in Scheme.
●
Now exists in several other programming
languages such as Ruby, known as
“callcc”
27. call-with-current-continuation
● call/cc takes in only one argument, which is a
function f.
● It takes the current continuation as an object and
applies f to it.
– continuation = new Continuation()
– function(continuation)
●
When, callcc gets invoked, the program flow will
continue from the point it was captured and the
argument to the continuation will become its
return value
31. def continue_example
i = 0
print "Before callcc #{i}n"
callcc do |cc|
for i in 1..10 do
print "In callcc #{i}n"
return cc if i > 5
end
end
print "After callcc #{i}n"
end
32. def continue_example
i = 0
print "Before callcc #{i}n"
callcc do |cc|
for i in 1..10 do
print "In callcc #{i}n"
return cc if i > 5
end
end
print "After callcc #{i}n"
end
puts "begin control flow."
c = continue_example()
puts "after invoking the method"
if c
c.call
puts "this will not get executed"
end
33. def continue_example
i = 0
print "Before callcc #{i}n"
callcc do |cc| begin control flow.
for i in 1..10 do Before callcc 0
print "In callcc #{i}n" In callcc 1
return cc if i > 5 In callcc 2
end In callcc 3
end In callcc 4
print "After callcc #{i}n" In callcc 5
end In callcc 6
after invoking the method
After callcc 6
after invoking the method
puts "begin control flow."
c = continue_example()
puts "after invoking the method"
if c
c.call
puts "this will not get executed"
end
34. call-with-current-continuation
●
Continuations are sort of goto labels. But
more powerful.
●
We can store the continuation in a variable or
object field, unlike a goto label.
●
Goto labels are restricted within a functional
scope, continuations are not limited by that.
35. The following code is strictly for session purposes
only. Implementing this in usable code may cause
harm to life and limb.
36. Continuation as a GOTO
def goto_in_ruby_1
i = 0
callcc {|@label|}
i = i + 1
print "#{i}t"
@label.call if i < 10
end
37. Continuation as a GOTO
def goto_in_ruby_1
i = 0
callcc {|@label|}
i = i + 1
print "#{i}t"
@label.call if i < 10
end
output:
1 2 3 4 5 6 7 8 9 10
38. Continuation as a GOTO
def goto_in_ruby_1 def goto_in_ruby_2
i = 0 i = 0
callcc {|@label|} callcc do |label|
i = i + 1 label.call
print "#{i}t" i = 99
@label.call if i < 10 end
end print i
end
output:
1 2 3 4 5 6 7 8 9 10
39. Continuation as a GOTO
def goto_in_ruby_1 def goto_in_ruby_2
i = 0 i = 0
callcc {|@label|} callcc do |label|
i = i + 1 label.call
print "#{i}t" i = 99
@label.call if i < 10 end
end print i
end
output: output:
1 2 3 4 5 6 7 8 9 10 0
40. Summary
●
Continuation is a procedure that represents
the remaining steps in a computation.
●
It is a "snapshot" of the current control
context or control state of the program
●
The continuation can be later invoked
(repeatedly) with custom arguments
41. Continuations
●
Languages that support first class
continuations
●
Scheme (call/cc)
●
Ruby (callcc)
●
Smalltalk (Continuation currentDo:)
●
Rhino [JavaScript] (new Continuation())
●
Scala (Responder & shift, reset)
●
Perl (Coro)
●
Haskell (Control.Monad.Cont)
42. Continuations Types
●
First class continuations
●
Continuation Passing Style (CPS)
●
Delimited Continuations
43.
44. Continuation Passing Style
●
A function, instead of returning an explict
value, it takes an explict 'continuation'
argument – another function which is
meant to receive the result of the
computation
46. CPS - Example
function add(x, y) {
return x + y
}
function square(x) {
return x * x
}
function calculate(x, y) {
return add(square(x), square(y))
}
js> print(calculate(3, 4))
=> 25
47. CPS - Example
function add_cps(x, y, c) {
c(x + y)
}
function square_cps(x, c) {
c(x * x)
}
48. CPS - Example
function add_cps(x, y, c) {
c(x + y)
}
function square_cps(x, c) {
c(x * x)
}
function calculate_cps(x, y, c) {
square_cps(x, function(v) {
square_cps(y, function(r){
add_cps(v,r,c)
})
})
}
49. CPS - Example
function add_cps(x, y, c) {
c(x + y)
}
function square_cps(x, c) {
c(x * x)
}
function calculate_cps(x, y, c) {
square_cps(x, function(v) {
square_cps(y, function(r){
add_cps(v,r,c)
})
})
}
js> calculate_cps(3, 4, print)
=> 25
js> calculate_cps(3, 4, function(v) {print(sqrt(v))});
=> 5
50. CPS
● CPS is used in programming languages that do not
have first – class continuations, but have first –
class functions
● Every call is a tail call and if used without Tail Call
Optimization (TCO), the continuation would grow
during recursion
● Using CPS and TCO, compilers and interperters of
some programming languages managed to
eliminate the need for a runtime stack.
51.
52. Delimited Continuations
● Delimited (or partial, or composable) continuations are
more like regular functions and less like GOTOs. They
do not embody the entire rest of the computation, but
just a partial rest, up to a programmer-defined outer
bound.
● delimited continuations will return control to the caller
after they are invoked, and they may also return values
– Tiark Rompf, Ingo Maier, Martin Odersky
53. Normal Control Flow with
Control Flow Delimited Continuations Continuation invoked
Continuation -
start
Delimited
continuation
Continuation -
end
54. Delimited Continuations
●
Delimited Continuations are manipulated
by means of two primitives, shift and
reset.
●
Calling shift captures the current
continuation, and reset defines the
boundary up to which the continuation
reaches.
61. Applications of Continuations
●
Pause and Play e.g. User Interface design
●
Backtracking
●
Coroutines
●
Exception Handling
●
Web Frameworks
●
Compiler & Interpreter implementation
62. Problems
●
Page centric
●
HTTP Stateless-ness causes heavy use of
session, cookies
●
'Back' button in user interaction pages
●
Browser cloning in user interaction pages
●
Inversion of control
63. def add_two_numbers
n1 = callcc { |cc| return ask("1st number:", cc) }
n2 = callcc { |cc| return ask("2nd number:", cc) }
print "sum of two numbers is #{n1 + n2}n"
end
64. def add_two_numbers
n1 = callcc { |cc| return ask("1st number:", cc) }
n2 = callcc { |cc| return ask("2nd number:", cc) }
print "sum of two numbers is #{n1 + n2}n"
end
irb> add_two_numbers
1st number:
respond with: submit(25, ...): => #<Continuation:0xb76e0e58>
irb> submit(25, 30)
2nd number:
respond with: submit(37, ...): => #<Continuation:0xb76ddde8>
irb> submit(37, 12)
sum of two numbers is 42
=> nil
65. def add_two_numbers
n1 = callcc { |cc| return ask("1st number:", cc) }
n2 = callcc { |cc| return ask("2nd number:", cc) }
print "sum of two numbers is #{n1 + n2}n"
end
@session = Hash.new
def ask(str, cc)
r = rand(100).to_i
print "#{str}nrespond with: submit(#{r}, ...): "
@session[r] = cc
cc
end
def submit(id, number)
@session[id].call(number)
End
66. Continuations lookup table (session)
Server renders the
page and saves the The continuation
continuation in the object is looked up
session with a uuid based on the uuid The page is
1 4 in the url and rendered with the
executed uuid given in the
url
server
2
call: page a
call: page b client
call: page c
3
Client makes a
server response
with required
information
67. Web Frameworks
●
Seaside in Smalltalk (v 3.1)
●
Wee in Ruby (v 2.1)
●
Nagare in Python (v 0.3)
●
Apache Cocoon in Java (v 2.2)
●
RIFE in Java (v 1.6)
●
Ocsigen in OCaml (v 1.3)
●
Weblocks in Common Lisp
68. Web Servers with Continuations
support
● Continuity (Perl)
● Jetty 6 (Java)
● Plt-Scheme web server (Scheme)
69.
70. Seaside
● Written in Smalltalk
● Often called the 'heretic' framework because it doesn't
follow the 'conventional' web wisdom
– Clean urls
– Templates to separate model and view
– Share as little state as possible
– Urls contain session identifiers
– There is no 'view' or html templates. Views are part of smalltalk objects
– Seaside continuations & callbacks give a stateful behavior
72. Seaside - Workspace
●
Smalltalk deals with image snapshots for
saving the workspace.
●
There is no concept of 'files' and 'editors'
●
Class objects are created through 'object
browser' and code is executed through a
'workspace'
73. Seaside - Components
● Components represent the whole of a page or portion of
pages
● The inherit from 'WAComponent' class
● Components maintain state
● Component's response loop
– Renders the component
– Waits for user's input
– Executes a block of code when a link or button is pressed
– Re-renders itself or another component in place
74. Image from - Seaside – A Multiple Control Flow Web Application Framework, Stéphane Ducasse
75. Seaside - callbacks
● Every user interaction on the web page triggers a
callback.
●
A callback can be on a link, button or any other
form elements
●
The callback will execute a block of code whose
result will end in re-rendering the component or
a new component
76. SimpleCounter>>initialize
super initialize.
counter := 0.
SimpleCounter>>renderContentOn: html
html heading: 'the counter is ', counter asString.
html anchor
callback: [ counter := counter + 1 ];
with: 'increase'.
77. Seaside - Continuations
● Call / Answer
● call: takes a component as a parameter and it swaps
the current component for the new component
● The new component will be rendered and user action
will cause a callback to run that'll send an answer:
● The value passed to answer: will be returned to call:
and the program will continue from there.
78. Image from - Seaside – A Multiple Control Flow Web Application Framework, Stéphane Ducasse
79. Problem with full continuation
Response 1 Response 2
Continuation saved Continuation invoked
Request 1 Request 2