Vectors in Scheme. Data Structures in Scheme

Similar documents
Functional Programming. Pure Functional Programming

User-defined Functions. Conditional Expressions in Scheme

An Explicit-Continuation Metacircular Evaluator

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

LECTURE 16. Functional Programming

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

Simplifying Logical Formulas

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Scheme Quick Reference

CSc 520 Principles of Programming Languages

Functional Programming - 2. Higher Order Functions

Scheme Quick Reference

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

CS61A Midterm 2 Review (v1.1)

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

Chapter 1. Fundamentals of Higher Order Programming

Data abstraction, revisited

Introduction to Scheme

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

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Racket: Modules, Contracts, Languages

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

Functional Programming. Pure Functional Languages

ALISP interpreter in Awk

Functional Programming

Functional Programming. Pure Functional Languages

6.001: Structure and Interpretation of Computer Programs

Essentials of Programming Languages Language

Essentials of Programming Languages Language

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

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

Discussion 12 The MCE (solutions)

Evaluating Scheme Expressions

Imperative languages

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

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

COP4020 Programming Assignment 1 - Spring 2011

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

An Introduction to Scheme

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

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

CS 314 Principles of Programming Languages. Lecture 16

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

Note that pcall can be implemented using futures. That is, instead of. we can use

Lists in Lisp and Scheme

INTRODUCTION TO SCHEME

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

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

CSC 533: Programming Languages. Spring 2015

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

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

Building up a language SICP Variations on a Scheme. Meval. The Core Evaluator. Eval. Apply. 2. syntax procedures. 1.

Parsing Scheme (+ (* 2 3) 1) * 1

FP Foundations, Scheme

Turtles All The Way Down

CS 314 Principles of Programming Languages

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

Documentation for LISP in BASIC

SCHEME AND CALCULATOR 5b

SOFTWARE ARCHITECTURE 6. LISP

Scheme: Strings Scheme: I/O

CMSC 331 Final Exam Section 0201 December 18, 2000

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

Project 2: Scheme Interpreter

Lecture #24: Programming Languages and Programs

Lexical vs. Dynamic Scope

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Lisp Basic Example Test Questions

Building a system for symbolic differentiation

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

CS 360 Programming Languages Interpreters

Typed Racket: Racket with Static Types

1.3. Conditional expressions To express case distinctions like

Fall 2017 December 4, 2017

A Brief Introduction to Scheme (II)

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?

How to Design Programs Languages

CS 314 Principles of Programming Languages

An introduction to Scheme

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

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

4/19/2018. Chapter 11 :: Functional Languages

Programming Languages

Functional programming in LISP

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

CS 314 Principles of Programming Languages

Lecture Notes on Lisp A Brief Introduction

Functions, Conditionals & Predicates

Building a system for symbolic differentiation

CS 275 Name Final Exam Solutions December 16, 2016

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams

This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

Common LISP-Introduction

Functional Programming Languages (FPL)

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

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

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

Transcription:

Data Structures in Scheme Vectors in Scheme In Scheme, lists and S-expressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked structure. To access an element deep within a list we can use: -tail L k This returns list L after removing the first k elements. For example, -tail '(1 2 3 4 5 2 (3 4 5 Scheme provides a vector type that directly implements one dimensional arrays. Literals are of the form #(... For example, #(1 2 3 or #(1 2.0 "three" The function (vector? val tests whether val is a vector or not. (vector? 'abc #f (vector? '(a b c #f (vector? #(a b c #t -ref L k This returns the k-th element in L (counting from 0. For example, -ref '(1 2 3 4 5 2 3 The function (vector v1 v2... evaluates v1, v2,... and puts them into a vector. (vector 1 2 3 #(1 2 3 130 131 The function (make-vector k val creates a vector composed of k copies of val. Thus (make-vector 4 (/ 1 2 #(1/2 1/2 1/2 1/2 The function (vector-ref vect k returns the k-th element of vect, starting at position 0. It is essentially the same as vect[k] in C or Java. For example, (vector-ref #(2 4 6 8 10 3 8 The function (vector-set! vect k val sets the k-th element of vect, starting at position 0, to be val. It is essentially the same as vect[k]=val in C or Java. The value returned by the function is unspecified. The suffix! in set! indicates that the function has a side-effect. For example, v #(1 2 3 4 5 (vector-set! v 2 0 v #(1 2 0 4 5 Vectors aren t lists (and lists aren t vectors. Thus (car #(1 2 3 doesn t work. There are conversion routines: (vector->list V converts vector V to a list containing the same values as V. For example, (vector->list #(1 2 3 (1 2 3 ->vector L converts list L to a vector containing the same values as L. For example, ->vector '(1 2 3 #(1 2 3 132 133

In general Scheme names a conversion function from type T to type Q as T->Q. For example, string->list converts a string into a list containing the characters in the string. Records and Structs In Scheme we can represent a record, struct, or class object as an association list of the form ((obj1 val1 (obj2 val2... In the association list, which is a list of (object value sublists, object serves as a key to locate the desired sublist. For example, the association list ( (A 10 (B 20 (C 30 serves the same role as struct { int a = 10; int b = 20; int c = 30;} 134 135 The predefined Scheme function (assoc obj alist checks alist (an association list to see if it contains a sublist with obj as its head. If it does, the list starting with obj is returned; otherwise #f (indicating failure is returned. For example, L '( (a 10 (b 20 (c 30 (assoc 'a L (a 10 (assoc 'b L (b 20 (assoc 'x L #f We can use non-atomic objects as keys too! price-list '( ((bmw m5 71095 ((bmw z4 40495 ((jag xj8 56975 ((mb sl500 86655 (assoc '(bmw z4 price-list ((bmw z4 40495 136 137

Using assoc, we can easily define a structure function: (structure key alist will return the value associated with key in alist; in C or Java notation, it returns alist.key. (structure key alist (if (assoc key alist (car (cdr (assoc key alist #f We can improve this function in two ways: The same call to assoc is made twice; we can save the value computed by using a let expression. Often combinations of car and cdr are needed to extract a value. Scheme has a number of predefined functions that combine several calls to car and cdr into one function. For example, (caar x (car (car x (cadr x (car (cdr x (cdar x (cdr (car x (cddr x (cdr (cdr x Using these two insights we can now define a better version of structure (structure key alist (let ((p (assoc key alist (if p (cadr p #f 138 139 What does assoc do if more than one sublist with the same key exists? It returns the first sublist with a matching key. In fact, this property can be used to make a simple and fast function that updates association lists: (set-structure key alist val (cons key val alist If we want to be more spaceefficient, we can create a version that updates the internal structure of an association list, using set-cdr! which changes the cdr value of a list: (set-structure! key alist val (let ( (p (assoc key alist (if p (begin (set-cdr! p val alist (cons key val alist 140 141

Functions are First-class Objects Functions may be passed as parameters, returned as the value of a function call, stored in data objects, etc. This is a consequence of the fact that (lambda (args (body evaluates to a function just as (+ 1 1 evaluates to an integer. Scoping In Scheme scoping is static (lexical. This means that nonlocal identifiers are bound to containing lambda parameters, or let values, or globally defined values. For example, (f x (lambda (y (+ x y Function f takes one parameter, x. It returns a function (of y, with x in the returned function bound to the value of x used when f was called. Thus (f 10 (lambda (y (+ 10 y ((f 10 12 22 142 143 Unbound symbols are assumed to be globals; there is a run-time error if an unbound global is referenced. For example, (p y (+ x y (p 20 ; error -- x is unbound x 10 (p 20 30 We can use let bindings to create private local variables for functions: F (let ( (X 1 (lambda ( X F is a function (of no arguments. (F calls F. X 22 We can encapsulate internal state with a function by using private, let-bound variables: cnt (let ( (I 0 (lambda ( (set! I (+ I 1 I Now, (cnt 1 (cnt 2 (cnt 3 etc. (F 1;X used in F is private 144 145

Let Bindings can be Subtle Simulating Class Objects You must check to see if the letbound value is created when the function is created or when it is called. Compare cnt (let ( (I 0 (lambda ( (set! I (+ I 1 I vs. reset (lambda ( (let ( (I 0 (set! I (+ I 1 I (reset 1, (reset 1, etc. Using association lists and private bound values, we can encapsulate data and functions. This gives us the effect of class objects. (point x y 'rect (lambda ( x y 'polar (lambda ( (sqrt (+ (* x x (* y y (atan (/ x y A call (point 1 1 creates an association list of the form ( (rect funct (polar funct 146 147 We can use structure to access components: p (point 1 1 ( (structure 'rect p (1 1 ( (structure 'polar p ( 2 π -- 4 We can add new functionality by just adding new (id function pairs to the association list. (point x y 'rect (lambda ( x y 'polar (lambda ( (sqrt (+ (* x x (* y y (atan (/ x y 'set-rect! (lambda (newx newy (set! x newx (set! y newy x y 'set-polar! (lambda (r theta (set! x (* r (sin theta (set! y (* r (cos theta r theta 148 149

Now we have p (point 1 1 ( (structure 'rect p (1 1 ( (structure 'polar p 2 π 4 -- ( ((structure 'set-polar! p 1 π/4 (1 π/4 ( (structure 'rect p 1 ------ 2 1 ------ 2 ( Limiting Access to Internal Structure We can improve upon our association list approach by returning a single function (similar to a C++ or Java object rather than an explicit list of (id function pairs. The function will take the name of the desired operation as one of its arguments. 150 151 First, let s differentiate between def1 (let ( (I 0 (lambda ( (set! I (+ I 1 I and (def2 (let ( (I 0 (lambda ( (set! I (+ I 1 I def1 is a zero argument function that increments a local variable and returns its updated value. def2 is a a zero argument function that generates a function of zero arguments (that increments a local variable and returns its updated value. Each call to def2 creates a different function. Stack Implemented as a Function ( stack (let ( (s ( (lambda (op. args ; var # args (cond ((equal? op 'push! (set! s (cons (car args s (car s ((equal? op 'pop! (if (null? s #f (let ( (top (car s (set! s (cdr s top ((equal? op 'empty? (null? s (else #f 152 153

stk (stack;new empty stack (stk 'push! 1 1 ;s = (1 (stk 'push! 3 3 ;s = (3 1 (stk 'push! 'x x ;s = (x 3 1 (stk 'pop! x ;s = (3 1 (stk 'empty? #f ;s = (3 1 (stk 'dump #f ;s = (3 1 154