What is tail position?

Similar documents
What is tail position?

User-defined Functions. Conditional Expressions in Scheme

Functional Programming. Pure Functional Programming

Overview. CS301 Session 3. Problem set 1. Thinking recursively

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

CS 314 Principles of Programming Languages

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Functional programming in μscheme

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13

CS 314 Principles of Programming Languages

An Explicit-Continuation Metacircular Evaluator

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Vectors in Scheme. Data Structures in Scheme

Functional Programming - 2. Higher Order Functions

Data! Two new kinds of data. The automatically managed cons cell Mother of heap-allocated data structures

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Functional Programming. Pure Functional Languages

6.001, Spring Semester, 1998, Final Exam Solutions Your Name: 2 Part c: The procedure eval-until: (define (eval-until exp env) (let ((return (eval-seq

(scheme-1) has lambda but NOT define

Simplifying Logical Formulas

Extensible Pattern Matching

Functional Programming. Pure Functional Languages

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

A Brief Introduction to Scheme (II)

CS 314 Principles of Programming Languages

Pattern Matching for Scheme

Logic - CM0845 Introduction to Haskell

Symbolic Computation

Scheme as implemented by Racket

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

Problem 1: Binary Trees: Flatten

6.945 Adventures in Advanced Symbolic Programming

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

Important Example: Gene Sequence Matching. Corrigiendum. Central Dogma of Modern Biology. Genetics. How Nucleotides code for Amino Acids

Functional programming in μscheme

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Programming Languages

ALISP interpreter in Awk

1.3. Conditional expressions To express case distinctions like

Putting the fun in functional programming

CS 275 Name Final Exam Solutions December 16, 2016

CS 314 Principles of Programming Languages. Lecture 16

Building a system for symbolic differentiation

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

From Syntactic Sugar to the Syntactic Meth Lab:

Functional Programming in Scheme

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Quicksort. Alternative Strategies for Dividing Lists. Fundamentals of Computer Science I (CS F)

CPSC 311, 2010W1 Midterm Exam #2

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Discussion 4. Data Abstraction and Sequences

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CS3: Introduction to Symbolic Programming. Lecture 14: Lists.

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Lecture #24: Programming Languages and Programs

Introduction to Scheme

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CS 360 Programming Languages Day 14 Closure Idioms

INTRODUCTION TO SCHEME

Scheme Quick Reference

CMSC 331 Final Exam Section 0201 December 18, 2000

YOUR NAME PLEASE: *** SOLUTIONS ***

Project 2: Scheme Interpreter

CS422 - Programming Language Design

Informatics 1 Functional Programming Lecture 4. Lists and Recursion. Don Sannella University of Edinburgh

April 2 to April 4, 2018

Scheme Quick Reference

Introduction to Functional Programming in Haskell 1 / 56

Principles of Programming Languages

Problems 3-1, 3.3, 3.4 and 3.5 in Chapter 3 of Winston and Horn's LISP (see Below)

CS 320 Midterm Exam. Fall 2018

Chapter 15. Functional Programming Languages

Verified compilation of a first-order Lisp language

CSCI0170. Today s topics. Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe

Implementing Coroutines with call/cc. Producer/Consumer using Coroutines

Typed Scheme: Scheme with Static Types

CSE413 Midterm. Question Max Points Total 100

Building a system for symbolic differentiation

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

Lambda Calculus see notes on Lambda Calculus

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

Introduction to Functional Programming

Principles of Programming Languages 2017W, Functional Programming

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Documentation for LISP in BASIC

Accurate Step Counting

Transcription:

What is tail position? Tail position is defined inductively: The body of a function is in tail position When(if e1 e2 e3) is in tail position, so are e2 ande3 When(let (...) e) is in tail position, so ise, and similary forletrec andlet*. When(begin e1... en) is in tail position, so isen. Idea: The last thing that happens

Tail-call optimization Before executing a call in tail position, abandon your stack frame Results in asymptotic space savings Works for any call!

Example of tail position (define reverse (xs) (if (null? xs) () (append (reverse (cdr xs)) (list1 (car xs)))))

Example of tail position (define reverse (xs) (if (null? xs) () (append (reverse (cdr xs)) (list1 (car xs)))))

Another example of tail position (define revapp (xs zs) (if (null? xs) zs (revapp (cdr xs) (cons (car xs) zs))))

Another example of tail position (define revapp (xs zs) (if (null? xs) zs (revapp (cdr xs) (cons (car xs) zs))))

Question In your past, what did you call a construct that 1. Transfers control to a point in the code? 2. Uses no stack space?

How functions finish Direct: True CPS: uscheme: return answer; throw k answer; (k answer)

Design Problem: Missing Value Provide a witness to existence: (witness p? xs) == x, where (member x xs), provided (exists? p? xs) Problem: What if there exists no suchx?

Solution: A New Interface Success and failure continuations! Laws: (witness-cps p? xs succ fail) = (succ x) ; where x is in xs and (p? x) (witness-cps p? xs succ fail) = (fail) ; where (not (exists? p? xs))

Refine the laws (witness-cps p? xs succ fail) = (succ x) ; where x is in xs and (p? x) (witness-cps p? xs succ fail) = (fail) ; where (not (exists? p? xs)) (witness-cps p? () succ fail) =? (witness-cps p? (cons z zs) succ fail) =? ; when (p? z) (witness-cps p? (cons z zs) succ fail) =? ; when (not (p? z))

Codingwitness with continuations (define witness-cps (p? xs succ fail) (if (null? xs) (fail) (let ([x (car xs)]) (if (p? x) (succ x) (witness-cps p? (cdr xs) succ fail)))))

Continuation-Passing Style All tail positions are continuations or recursive calls (define witness-cps (p? xs succ fail) (if (null? xs) (fail) (let ([x (car xs)]) (if (p? x) (succ x) (witness-cps p? (cdr xs) succ fail))))) Compiles to tight code

Example Use: Instructor Lookup -> (val 2016f ((Fisher 105)(Hescott 170)(Chow 116))) -> (instructor-info Fisher 2016f) (Fisher teaches 105) -> (instructor-info Chow 2016f) (Chow teaches 116) -> (instructor-info Souvaine 2016f) (Souvaine is-not-on-the-list)

Instructor Lookup: The Code ; info has form: (Fisher 105) ; classes has form: (info_1 info_n) (define instructor-info (instructor classes) (let ( [s (lambda (info) ; success continuation (list3 instructor teaches (cadr info)))] [f (lambda () ; failure continuation (list2 instructor is-not-on-the-list))]) (witness-cps pred classes s f))

Instructor Lookup: The Code ; info has form: (Fisher 105) ; classes has form: (info_1 info_n) (define instructor-info (instructor classes) (let ( [s (lambda (info) ; success continuation (list3 instructor teaches (cadr info)))] [f (lambda () ; failure continuation (list2 instructor is-not-on-the-list))]) (witness-cps (o ((curry =) instructor) car) classes s f))

Instructor Lookup: The Code ; info has form: (Fisher 105) ; classes has form: (info_1 info_n) (define instructor-info (instructor classes) (let ( [s (lambda (info) ; success continuation (list3 instructor teaches (cadr info)))] [f (lambda () ; failure continuation (list2 instructor is-not-on-the-list))]) (witness-cps (o ((curry =) instructor) car) classes s f))

Instructor Lookup: The Code ; info has form: (Fisher 105) ; classes has form: (info_1 info_n) (define instructor-info (instructor classes) (let ( [s (lambda (info) ; success continuation (list3 instructor teaches (cadr info)))] [f (lambda () ; failure continuation (list2 instructor is-not-on-the-list))]) (witness-cps (o ((curry =) instructor) car) classes s f)))

Continuations for Search start fail start +-----------+ succeed ---------> ------------> solver <--------- <----------- fail +-----------+ resume Gets partial solution,fail,succeed (On homework, solution is assignment) Partial solution won t work (no params) succeed Gets improved solution +resume resume If improved solution won t work, try another (no params) A composable unit!

Continuations for the solver A big box contains two smaller boxes A and B There are two ways to wire them up (board) Imagine A and B as formulas Imagine A as a formula, B as a list of formulas!

Solving a literal (define satisfy-literal-true (x current succ fail) (if (bound? x current) (if (find x current) (succ current fail) (fail)) (succ (bind x #t current) fail)))