# CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

Save this PDF as:

Size: px
Start display at page:

Download "CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires"

## Transcription

1 1 A couple of Functions 1 Let's take another example of a simple lisp function { one that does insertion sort. Let us assume that this sort function takes as input a list of numbers and sorts them in ascending order. Remember how insertion sort works { it rst orders 2 elements with respect to each other, then inserts a third into that in the correct place and so on. At step n, nnumbers are sorted with respect to each other. > (insert-sort '(5 1 2)) 1 Enter INSER-SOR (5 1 2) 2 Enter INSER-SOR (1 2) 3 Enter INSER-SOR (2) 4 Enter INSER-SOR NIL 4 Exit INSER-SOR NIL 4 Enter INSER-INO-SORED 2 NIL 4 Exit INSER-INO-SORED (2) 3 Exit INSER-SOR (2) 3 Enter INSER-INO-SORED 1 (2) 3 Exit INSER-INO-SORED (1 2) 2 Exit INSER-SOR (1 2) 2 Enter INSER-INO-SORED 5 (1 2) 3 Enter INSER-INO-SORED 5 (2) 4 Enter INSER-INO-SORED 5 NIL 4 Exit INSER-INO-SORED (5) 3 Exit INSER-INO-SORED (2 5) 2 Exit INSER-INO-SORED (1 2 5) 1 Exit INSER-SOR (1 2 5) (1 2 5) (defun insert-sort (nums) takes a list of numbers and sorts them in ascending order using insertion sort''

2 CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires only simple recursion { calling the function again on the cdr of a list. We may encounter problems which require more complicated recursion. Let's do a more complicated example of a member function. Call it (emb-member ele emb-list). his function returns t if ele occurs ANYWHERE in emb-list. Note here that emb-list is an arbitrary complicated list. So, for example: > (emb-member 'a '(a b c)) > (emb-member 'a '((c d (a) b) e)) base: {emb-list is empty { ele is the car of emb-list simpler-problems: { if car is emb-list is a list and ele is an emb-memberofit{ifeleis an emb-memberofthecdr of l (defun emb-member (ele emb-list) takes as input an s-expression, ele, and an arbitrarily complex list, emb-list. Returns t if ele occurs somewhere in emb-list'' > (emb-member 'a '((c d (a) b) e)) > (emb-member 'a ()) NIL > (emb-member 'a '(((a))))

3 CIS4/681 { Articial Intelligence 3 > (emb-member 'a '(b (c d (e)))) NIL Dene a function (subst new old emb-list) which substitutes the value of new for old wherever old occurs in emb-list. Examples: > (subst 'a 'b '((a b) (c (b) d) (e))) ((A A) (C (A) D) (E)) > (subst 'a 'b '(d b e f b)) (D A E F A) > (subst '(a b) 'c '(a (b c) d ((e c)))) (A (B (A B)) D ((E (A B)))) > (subst 'a '(b c) '(a (b c) d e)) (A A D E) base conditions: { when emb-list is empty, when the car of emb-list is old easier problem: {looktoseeif new occurs in the car (provided it is a list) and cons what you get to doing the subst to the cdr { else cons the car to what you get from doing the subst to the cdr. (defun subst (new old emb-list) substitutes new for old wherever it occurs in emb-list and returns the new list'' > (subst 'a 'b '((c b) b d)) ((C A) A D) 3 he Symbol able Each entry in the symbol table is a fairly complicated thing. For instance, we can think of the symbol table as consisting of 5 elds (only 4 of which I know).

4 CIS4/681 { Articial Intelligence 4 Print-Name the name of the symbol that gets printed on the terminal. Value Function Denition Property-list the symbols value as is set by setf or by being bound within a function call (when it is a formal parameter for the function for example). the denition of the function named by the symbol. his denition is \set" via defun. a list of name-value pairs. hese may be set using the (setf (get name property) value) function, and retrieved using the (get name property) function. Property lists are useful as ways of holding information about objects. For instance, we might have some information about an object named AI-Class. For instance, this object may have 4 assignments, 5 homeworks, a midterm and a nal exam, and an instructor named McCoy. his could be kept in a property list: (setf (get 'AI-Class 'numb-assignments) 4) (setf (get 'AI-Class 'numb-homeworks) 5) (setf (get 'AI-Class 'exams) '(midterm final)) (setf (get 'AI-Class 'instructor) 'McCoy) In our program we could then query these individual items: > (get 'AI-Class 'numb-homeworks) 5 > (get 'AI-Class 'instructor) McCoy 4 Lisp Style Just a word on what the functions you hand in should look like. Indent code to reect level of nesting of parenthesis. Otherwise it is impossible to read {ifyou put that setenv thing in your.login le vi will do a pretty good job of getting the indentation right. Conventions: Make code reect the way you think about the problem { recursively! Each function usually consists of a conditional checking base conditions and then a recursive call { usually cons the car onto result of doing function to rest of list. Variable and function names should be well-chosen (descriptive)

5 CIS4/681 { Articial Intelligence 5 Use special names for global variables (e.g., *data*). Use global variables only when they are the clearest way to do things (e.g., as pointers to a global data base). Stress functional embedding. Avoid temp or local variables. \he judicious use of LE and functional embedding can remove the need for most instances of SEF. Doing this is considered the mark of an expert lisp programmer." Keep functions short. Break up large functions into several logically self-contained programs. his will make testing and debugging much easier! COMMEN CODE! Each function should have a block comment in the beginning explaining what kind of input arguments are expected, and what is returned. In the code, anything tricky should have a comment. Another mark of a good lisp programmer is to be able to look at a system written years before and gure out how it works in 5 minutes { nd functions to borrow etc... 5 Logical Operators and Equal First, a couple more predicates need to be introduced: (and x 1 x 2 :::x n ) { returns NIL is any argument evaluates to nil. his function is smart in that it only evaluates until it nds a null argument. (or x 1 x 2 :::x n ) { returns non-null if any argument evaluates to non-null. he value returned is the value of the rst non-null argument. his function is also smart in its evaluation { it only evaluates until it nds an argument that evaluates to non-null. (list x 1 x 2 :::x n ) { makes a list out of the arguments. In lisp, there are really two dierent functions for deciding whether or not two things are equal. (eql x 1 x 2 ) { returns tifx 1 and x 2 are pointers to the same memory location. hat is, if they are the same atom, or they are pointers to the same list cell. (equal x 1 x 2 ) { returns t if x 1 and x 2 look the same. hat is, if they are the same atom (as in eql), or if they are lists with the same structure and elements that look to be the same. We can write the equal function in terms of eql as below: (defun our-equal (x y) takes two s-expressions and returns t if they appear equal''

6 CIS4/681 { Articial Intelligence 6 > (our-equal 'a 'a) > (our-equal '(a b) '(a b)) > (our-equal '(a (b)) '(a b c)) NIL > (our-equal '(a (b) c) '(a (b))) NIL > (our-equal '(a (b (c d)) e) '(a (b (c d)) e)) 6 Printing Functions If you want your functions to print something out on the screen, there are anumber of lisp functions available for this purpose. You may nd these particularly useful in debugging (if the trace function does not give you all of the information that you need). (print x) { prints the value of x and returns the value of x. (princ x) { like print but omits delimiters (terpri) { prints a carriage return Some simple examples: > (print 'a) A A > (print "this and that") "this and that" "this and that" > (princ "this and that") this and that "this and that" > (terpri)

7 CIS4/681 { Articial Intelligence 7 NIL he backquote  is a rather useful device for formatting output. It allows you to insert a value for a variable (using,) or splice the value in here are particularly useful in conjunction with the print statement. > (setf x '(a b c)) (A B C) > (print (the value of x is,x)) (HE VALUE OF X IS (A B C)) (HE VALUE OF X IS (A B C)) > (print (the value of the three arguments (HE VALUE OF HE HREE ARGUMENS IS A B C) (HE VALUE OF HE HREE ARGUMENS IS A B C) 7 Iterative Programming Constructs he most general form of an iterative construct can be found in the prog statement: (prog (v1 v2... vn) e1 e2... ek) Allows local variables v1...vn to be set (using setf) within the prog statement. hese values are initialized to nil upon entering the prog, and are \lost" upon exiting the prog. Other things you might nd in a prog: the (return value) statement { causes the prog to be exited and allows a value to be returned form the prog. Also useful is the (go label) { which causes control to be passed to the label \label". 8 Functions as Arguments In lisp, functions are rst class objects. hat is, you can treat a function just like any other object. In particular, you can pass them as arguments to functions.

8 CIS4/681 { Articial Intelligence 8 Of course, when you do such a thing, you probably do it so you can use the function inside the function { so you need a method of calling a function which has been passed in as a value to another function. (apply fn-spec args-list) is the function you want! he rst argument to apply evaluates to a function (name), the second evaluates to the list containing the function arguments. > (apply '+ (list )) 10 > (apply '+ '( )) 10 > (apply 'cons '(a (b c))) (A B C) > (apply 'atom (list 'a)) Apply seems a little funny since the arguments are in a list. funcall takes a function (name) and a number of arguments to that function and applies the function to the arguments. > (funcall 'cons 'a '(b c)) (A B C) Why would you even want to use such function? Recall our insertion sort function and remember how I told you that lisp does no type checking... What if I wanted to sort into descending order instead of ascending order? Or, I wanted to sort characters instead of numbers? We could do all of this if we not only passed the function a list to be sorted, but also passed it the comparison function you wanted it to sort by. (defun insert-your-fun-sort (nums &optional (order-fn (function <))) takes a list and an ordering function which works on the elements in the list and sorts the list according to the sorting function using insertion sort'' (cond ((null nums) nil) ((insert-your-fun-into-sorted (car nums) (insert-your-fun-sort (cdr nums) order-fn) order-fn)))) (defun insert-your-fun-into-sorted (ele l ordering-fun) inserts ele into the sorted list l according to the ordering function''

9 CIS4/681 { Articial Intelligence 9 (cond ((null l) (list ele)) ((funcall ordering-fun ele (car l)) (cons ele l)) ((cons (car l) (insert-your-fun-into-sorted ele (cdr l) ordering-fun))))) > (insert-your-fun-sort '( ) (function <)) ( ) > (insert-your-fun-sort '( ) (function >)) ( ) Lisp also gives you ner control over the evaluation of functions { so much so that it allows you to call the evaluation! eval { is a function that takes one argument, it evaluates that argument and then evaluates it again. > (setf x '(cons 'a '(b c))) (CONS (QUOE A) (QUOE (B C))) > (eval x) (A B C) 9 Mapping Functions Suppose you want to do something (the same thing) to several sets of arguments (not just one). For instance, you want to add 1 to each memberofanentire list of numbers. Lisp allows you to do this with some special mapping functions. Input to these functions are a function specication and a list of arguments. he mapping function will apply the function to each argument on the list and do something with the results (that something is what makes one mapping function dierent from another). he most used mapping function is mapcar. E.g., > (mapcar '1+ '( )) ( ) Note that the list may beavariable which you get out of a computation { you need not know its length. (defun add-to-all (n-list) (mapcar '1+ n-list)) ADD-O-ALL > (add-to-all '( )) ( )

10 CIS4/681 { Articial Intelligence 10 mapcar can be used with functions requiring more than one argument. In this case you give one list for each argument. > (mapcar '+ '( ) '( ) '( )) ( ) (mapcar <fn-specification> l1... ln) where l1... ln are all lists of the same length fn-specification species a function of n arguments. he value: mapcar evaluates its arguments and then applies the rst argument to the cars of each of the latter arguments, then \cdr's" down each list. he value returned is a list containing the results of the function applications. What if we want to apply some function of, say, two arguments to a list of items, but want the second argument tobe the same in each case. For instance, in my dissertation at one point Ihave a special object obj. Part of the processing I have to do is to collect all objects in my knowledge base that have a special property p. I then want to test their similarity with my special object obj. I have a similarity function (similarity obj1 obj2). How can I do this with mapcar short of generating a list of n objects where n is the number of items returned from my gathering step? mapcar allows this kind of processing by essentially allowing you to specify a new function (which doesn't have a name). But rst, we have to know a little bit more about functions. 10 Mapcar and Lambda Expressions What does it mean to be a function? We use defun to dene functions. Defun takes a function name, formal-parameter-list, and function body and stores these things under the \function" property in the symbol table under the function-name. Really the name doesn't do anything but associate things { the formal parameters and the body { it gives us a shorthand for referring to things. Just in case you don't need that shorthand, it would be nice to be able to create a function without a name (for instance, to be used in mapcar). LAMBDA notation, gives us away of doing that. For instance, we might want a function which checks to see if the input is a list of length 2. (lambda (a) (and (listp a) (equal (length a) 2))) his is a lambda form. It is not a function CALL, but a FUNCION SPECIFICAION { it is a function itself. It can be put wherever you put function names. > ((lambda (a) (and (listp a) (equal (length a) 2))) '(a b))

11 CIS4/681 { Articial Intelligence 11 We could use lambda notation in our mapcar before. (defun foo (prop kb spec-obj)... (apply 'foo2 (mapcar (function (lambda (x) (similarity x spec-obj))) (gather-objs-with-prop-prop kb)) Here I will do a comparable numeric example. We really want a function like: (defun add-num (num list) (mapcar (function (lambda (x) (+ num x))) list)) > (tester 2 '( )) ( ) (Note we use the function function here { this function is similar to the quote function but it is used to quote functions. It causes \lexical closure" to take place. On this instance, lexical closure makes available the local variables in the calling function.) Lambda happens to be the basic internal mechanism with which functions are implemented. Defun actually builds a lambda form. he lambda is fetched for function application. Using defun hides this. Another example. Suppose that Iwanted to take a list of numbers, take the square root of each one and then add one to each (and return the results in a list). (defun list-sqrt-add1 (lis) (mapcar 'sqrt-add1 lis)) (defun sqrt-add1 (x) (1+ (sqrt x))) Is the above a valid helping function? Probably not. Lambda allows us to dene a function within another function { this function is not even given a name since we don't expect it to be used again (it is rather specic to our purposes). (defun new-list-sqrt-add1 (lis) (mapcar (function (lambda (x) (1+ (sqrt x)))) lis)) > (new-list-sqrt-add1 '(1 4 9)) ( ) Now write a function like the above, except it sums the results:

12 CIS4/681 { Articial Intelligence 12 (defun add-list-sqrt-add1 (lis) (apply + (mapcar (function (lambda (x) (1+ (sqrt x)))) lis))) > (add-list-sqrt-add1 '(1 4 9)) Let Statements Suppose we want to write a function longer-list which takes two lists. It returns the list that contains the most elements or the symbol equal if both lists are the same length. (defun longer-list (l1 l2) does as above says!'' (cond ((> (length l1) (length l2)) l1) ((> (length l2) (length l1)) l2) (t 'equal))) Problem { this function causes length to be evaluated a number of times. he let statement allows us to \set a local variable" and thus avoid that extra computation. (let list'' exps'') list'' is a possibly empty list of objects each having the form (symbol expression) { in parallel all expressions are evaluated and simultaneously bound to their corresponding symbols. Next, exps'' are evaluated (the last one evaluated is returned as the value of the let) and the symbols are returned to their previous values. (defun let-longer-list (l1 l2) like above but uses let'' (let ((len-l1 (length l1)) (len-l2 (length l2))) (cond ((> len-l1 len-l2) l1) ((> len-l2 len-l1) l2) (t 'equal)))) 12 Some Additional Lisp Functions Lisp lists are a convenient way to represent sets {acollection of 0 or more elements in which there are no duplicates. (defun setunion (s1 s2) (cond ((null s1) s2) ((our-member (car s1) s2)

13 CIS4/681 { Articial Intelligence 13 (setunion (cdr s1) s2)) ((cons (car s1) (setunion (cdr s1) s2))))) (defun setintersection (s1 s2) (cond ((or (null s1) (null s2)) nil) ((our-member (car s1) s2) (cons (car s1) (setintersection (cdr s1) s2))) ((setintersection (cdr s1) s2)))) (defun remove-all (x l) (cond ((null l) nil) ((equal (car l) x) (remove-all x (cdr l))) ((cons (car l) (remove-all x (cdr l)))))) (defun count-up (n) creates a list of numbers from 1 to n if n > 0, nil otherwise'' (count-up-rec 1 n)) (defun count-up-rec (start end) does the work for count-up and checks boundary conditions'' (cond ((> start end) ()) ((cons start (count-up-rec (1+ start) end))))) > (count-up 5) ( ) > (count-up 0) NIL (defun classify (l) takes a list of elements and returns a list made up of the original elements of l but all numbers have been put in the car and all identifiers in the cadr and all else is ignored'' (cond ((null l) (list nil nil)) ((numberp (car l)) (add-to-car (car l) (classify (cdr l)))) ((atom (car l))

14 CIS4/681 { Articial Intelligence 14 (add-to-cadr (car l) (classify (cdr l)))) ((classify (cdr l))))) (defun add-to-car (ele l) (cons (union (list ele) (car l)) (cdr l))) (defun add-to-cadr (ele l) (cons (car l) (list (union (list ele) (cadr l)))))

### Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

### Common LISP-Introduction

Common LISP-Introduction 1. The primary data structure in LISP is called the s-expression (symbolic expression). There are two basic types of s-expressions: atoms and lists. 2. The LISP language is normally

### CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

CS 480 Lisp J. Kosecka George Mason University Lisp Slides Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic

### Lecture Notes on Lisp A Brief Introduction

Why Lisp? Lecture Notes on Lisp A Brief Introduction Because it s the most widely used AI programming language Because Prof Peng likes using it Because it s good for writing production software (Graham

### Common Lisp. Blake McBride

Contents Common Lisp Blake McBride (blake@mcbride.name) 1 Data Types 2 2 Numeric Hierarchy 3 3 Comments 3 4 List Operations 4 5 Evaluation and Quotes 5 6 String Operations 5 7 Predicates 6 8 Math Predicates

### Lisp: Question 1. Dr. Zoran Duric () Midterm Review 1 1/ 13 September 23, / 13

Lisp: Question 1 Write a recursive lisp function that takes a list as an argument and returns the number of atoms on any level of the list. For instance, list (A B (C D E) ()) contains six atoms (A, B,

### Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Lecture #2 Kenneth W. Flynn RPI CS

Outline Programming in Lisp Lecture #2 Kenneth W. Flynn RPI CS Items from last time Recursion, briefly How to run Lisp I/O, Variables and other miscellany Lists Arrays Other data structures Jin Li lij3@rpi.edu

### Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Intro. Scheme Basics. scm> 5 5. scm>

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

### Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

### SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

### CS 314 Principles of Programming Languages. Lecture 16

CS 314 Principles of Programming Languages Lecture 16 Zheng Zhang Department of Computer Science Rutgers University Friday 28 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

### CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

CS61A Notes 02b Fake Plastic Trees Box and Pointer Diagrams QUESTIONS: Evaluate the following, and draw a box-and-pointer diagram for each. (Hint: It may be easier to draw the box-and-pointer diagram first.)

### 19 Machine Learning in Lisp

19 Machine Learning in Lisp Chapter Objectives Chapter Contents ID3 algorithm and inducing decision trees from lists of examples. A basic Lisp implementation of ID3 Demonstration on a simple credit assessment

### A Quick Introduction to Common Lisp

CSC 244/444 Notes last updated ug. 30, 2016 Quick Introduction to Common Lisp Lisp is a functional language well-suited to symbolic I, based on the λ-calculus and with list structures as a very flexible

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

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

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

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

### ALISP interpreter in Awk

ALISP interpreter in Awk Roger Rohrbach 1592 Union St., #94 San Francisco, CA 94123 January 3, 1989 ABSTRACT This note describes a simple interpreter for the LISP programming language, written in awk.

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

Homework Solutions: Problem Set Homework 2 Due uesday September 8, 2015 in class Be sure to follow the guidelines for Programming Assignments. Since these problems are simple, you may skip the Statement

### Introduction to Lisp

Last update: February 16, 2010 Introduction to Lisp Dana Nau Dana Nau 1 Outline I assume you know enough about computer languages that you can learn new ones quickly, so I ll go pretty fast If I go too

### A Genetic Algorithm Implementation

A Genetic Algorithm Implementation Roy M. Turner (rturner@maine.edu) Spring 2017 Contents 1 Introduction 3 2 Header information 3 3 Class definitions 3 3.1 Individual..........................................

### Project 2: Scheme Interpreter

Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

### A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

### An Introduction to Scheme

An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

### Building a system for symbolic differentiation

Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

### CSCI 3155: Principles of Programming Languages Exam preparation #1 2007

CSCI 3155: Principles of Programming Languages Exam preparation #1 2007 Exercise 1. Consider the if-then-else construct of Pascal, as in the following example: IF 1 = 2 THEN PRINT X ELSE PRINT Y (a) Assume

### Allegro CL Certification Program

Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects

### GPS: The general problem solver. developed in 1957 by Alan Newel and Herbert Simon. (H. Simon, 1957)

GPS: The general problem solver developed in 1957 by Alan Newel and Herbert Simon (H. Simon, 1957) GPS: The general problem solver developed in 1957 by Alan Newel and Herbert Simon - Was the first program

### Scheme Basics > (butfirst '(help!)) ()

Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst

### A short note on short differentiation programs in lisp, and a comment on logarithmic differentiation

A short note on short differentiation programs in lisp, and a comment on logarithmic differentiation Richard Fateman University of California, Berkeley September, 1998 1 Lisp and differentiation By tradition

### Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

### CSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10

CSCI 2210: Programming in Lisp ANSI Common Lisp, Chapters 5-10 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 1 Progn Progn Creates a block of code Expressions in body are evaluated Value

### Fifth Generation CS 4100 LISP. What do we need? Example LISP Program 11/13/13. Chapter 9: List Processing: LISP. Central Idea: Function Application

Fifth Generation CS 4100 LISP From Principles of Programming Languages: Design, Evaluation, and Implementation (Third Edition, by Bruce J. MacLennan, Chapters 9, 10, 11, and based on slides by Istvan Jonyer

### Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### Functional abstraction

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

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

STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? 2. How does memoization work? 3. Is a cons-stream a special form? Practice with Streams 1. Define a procedure (ones) that, when run

### (defvar *state* nil "The current state: a list of conditions.")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GPS engine for blocks world ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *dbg-ids* nil "Identifiers used by dbg") (defvar *state* nil "The current state: a list of conditions.")

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

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

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

Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy

### Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed

### Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

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

Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial

### Robot Programming with Lisp

4. Functional Programming: Higher-order Functions, Map/Reduce, Lexical Scope Institute for Artificial University of Bremen 9 of November, 2017 Functional Programming Pure functional programming concepts

### Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

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

STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? A stream is an element and a promise to evaluate the rest of the stream. Streams are a clever idea that allows one to use sequence

### CS 842 Ben Cassell University of Waterloo

CS 842 Ben Cassell University of Waterloo Recursive Descent Re-Cap Top-down parser. Works down parse tree using the formal grammar. Built from mutually recursive procedures. Typically these procedures

### Functional programming techniques

Functional programming techniques o Currying o Continuations o Streams. Lazy evaluation Currying o Haskell B. Curry. o Second-order programming: o Functions that return other functions. o Example: A two-arguments

### 6.001 Notes: Section 31.1

6.001 Notes: Section 31.1 Slide 31.1.1 In previous lectures we have seen a number of important themes, which relate to designing code for complex systems. One was the idea of proof by induction, meaning

### 1 CLWEB INTRODUCTION 1

1 CLWEB INTRODUCTION 1 1. Introduction. This is CLWEB, a literate programming system for Common Lisp by Alex Plotnick plotnick@cs.brandeis.edu. It is modeled after the CWEB system by Silvio Levy and Donald

### 6.001 Notes: Section 5.1

6.001 Notes: Section 5.1 Slide 5.1.1 In this lecture we are going to continue with the theme of building abstractions. Thus far, we have focused entirely on procedural abstractions: the idea of capturing

### Artificial Intelligence Programming

Artificial Intelligence Programming Rob St. Amant Department of Computer Science North Carolina State University Lisp basics NC State University 2 / 99 Why Lisp? Some recent Lisp success stories include

### MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

### MIDTERM EXAMINATION - CS130 - Spring 2005

MIDTERM EAMINATION - CS130 - Spring 2005 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 231 + 25 extra credit This exam counts for 25%

### CS A331 Programming Language Concepts

CS A331 Programming Language Concepts Lecture 10 Alternative Programming Languages (Functional LISP Declarative - PROLOG) March 24, 2014 Sam Siewert Functional PL Concepts Based on Lambda Calculus Output

### CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

### Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

### Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122 I. Logic 101 In logic, a statement or proposition is a sentence that can either be true or false. A predicate is a sentence in

### (Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

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

Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated

### This exam is worth 30 points, or 18.75% of your total course grade. The exam contains

CS 60A Final May 16, 1992 Your name Discussion section number TA's name This exam is worth 30 points, or 18.75% of your total course grade. The exam contains six questions. This booklet contains eleven

### Project 1: Scheme Pretty-Printer

Project 1: Scheme Pretty-Printer CSC 4101, Fall 2017 Due: 7 October 2017 For this programming assignment, you will implement a pretty-printer for a subset of Scheme in either C++ or Java. The code should

### Racket Style Guide Fall 2017

CS17 Integrated Introduction to Computer Science Hughes Racket Style Guide Fall 2017 Contents 1 Introduction 1 2 Naming 1 3 Formatting 1 4 Equality 3 5 Conditionals 4 5.1 Prefer Cond to If......................................

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

### Lecture #5 Kenneth W. Flynn RPI CS

Outline Programming in Lisp Lecture #5 Kenneth W. Flynn RPI CS We've seen symbols in three contexts so far: > (setf sym ) (let ((sym ))...) >'Sym SYM -- Context The first of these refers to a special (or

### CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018

CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018 Taken from assignments by Profs. Carl Offner and Ethan Bolker Part 1 - Modifying The Metacircular Evaluator

### Finite Set Theory. based on Fully Ordered Lists. Jared Davis UT Austin. ACL2 Workshop 2004

Finite Set Theory based on Fully Ordered Lists Jared Davis UT Austin ACL2 Workshop 2004 Motivation (1/2) Unique representation for each set No mutual recursion needed for membership, subset, and set equality

### Lisp legal move generators & search

Lisp legal move generators & search objectives 1. development of legal move generators 2. experimentation with search 3. exposure to pattern matching 4. exposure to new Lisp forms The work described here

### CSc 520 Principles of Programming Languages. Examining Lists. Constructing Lists... 7: Scheme List Processing

Constructing Lists CSc 520 Principles of Programming Languages 7: Scheme List Processing Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona The most important

### INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

### (defmacro while (condition &body body) `(iterate loop () (if,condition (loop)))))

; PARCIL - A Parser for C syntax In Lisp version 0.1a copyright (c) 1992 by Erann Gat, all rights reserved This program is free software; you can redistribute it and/or modify it under the terms of the

### Well, I hope you appreciate that we have inducted you into some real magic, the magic of

MITOCW Lecture 9B Well, I hope you appreciate that we have inducted you into some real magic, the magic of building languages, really building new languages. What have we looked at? We've looked at an

### MetacircularScheme! (a variant of lisp)

MetacircularScheme! (a variant of lisp) Lisp = Beauty Passed on through ages Basic Expressions (function arg1 arg2 ) To evaluate an expression, apply the functionto the arguments. (+ 1 2)? => 3 (sqrt4)?

### mk-convert Contents 1 Converting to minikanren, quasimatically. 08 July 2014

mk-convert 08 July 2014 Contents 1 Converting to minikanren, quasimatically. 1 1.1 Variations on a Scheme..................... 2 1.2 Racket to minikanren, nally.................. 8 1.3 Back to the beginning......................

### Department of Computer and information Science Norwegian University of Science and Technology

Department of Computer and information Science Norwegian University of Science and Technology http://www.idi.ntnu.no/ A Crash Course in LISP MNFIT272 2002 Anders Kofod-Petersen anderpe@idi.ntnu.no Introduction

### Functional Programming - 2. Higher Order Functions

Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

### Some Useful Lisp Algorithms: Part 1

MITSUBISHI ELECTRIC RESEARCH LABORATORIES http://www.merl.com Some Useful Lisp Algorithms: Part 1 Richard C. Waters TR91-04 December 1991 Abstract Richard C. Waters Chapter 3 Ïmplementing Queues in Lisp

### A LISP Interpreter in ML

UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

### Debugging in LISP. trace causes a trace to be printed for a function when it is called

trace causes a trace to be printed for a function when it is called ;;; a function that works like reverse (defun rev (list) (cons (first (last list)) (rev (butlast list)))) USER: (trace rev) ; note trace

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

1 File: regsim.scm Register machine simulator from section 5.2 of STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS This file can be loaded into Scheme as a whole. Then you can define and simulate machines

### Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

Homework Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25 Copyright c 2002 2017 UMaine Computer Science Department 1 / 33 1 COS 140: Foundations

### UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Fall, 2001 Prof. R. Fateman SUGGESTED S CS 164 Final Examination: December 18, 2001, 8-11AM

### Part II Composition of Functions

Part II Composition of Functions The big idea in this part of the book is deceptively simple. It s that we can take the value returned by one function and use it as an argument to another function. By

### Introduction to Artificial Intelligence CISC-481/681 Program 1: Simple Lisp Programs

CISC-481/681 Program 1: Simple Lisp Programs 1 Introduction to Artificial Intelligence CISC-481/681 Program 1: Simple Lisp Programs Reading: Handouts Summarizing Common Lisp Functions Paul Graham s ANSI

### Project 5 - The Meta-Circular Evaluator

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 2005 Project 5 - The Meta-Circular

### Working with recursion

Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

### 6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part,

1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 1998, Final Exam Your Name: Open

### Principles of Programming Languages

Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

### Project 5 - The Meta-Circular Evaluator

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 2005 Project 5 - The Meta-Circular

### UMBC CMSC 331 Final Exam Section 0101 December 17, 2002

0 / 0 1 / 20 UMBC CMSC 331 Final Exam Section 0101 December 17, 2002 Name: Student ID#: 2 / 25 3 / 20 4 / 25 5 / 20 6 /40 7 /40 You will have two hours to complete this closed book exam. We reserve the

### Trombone players produce different pitches partly by varying the length of a tube.

Trombone players produce different pitches partly by varying the length of a tube. 7 Variables A variable is a connection between a name and a value.* That sounds simple enough, but some complexities arise

### External aids allowed:

Midterm Duration: External aids allowed: 75 minutes None Make sure that your examination booklet has 8 pages of questions (excluding this one). Write your answers in the space provided. Write legibly.

### Allegro CL Certification Program

Allegro CL Certification Program Lisp Programming Series Level I Presented by 1 About David Margolies Manager, Documentation, Franz Inc Been working with Lisp since 1984 dm@franz.com 2 About Franz Inc.

### COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

COMPUTER SCIENCE IN THE NEWS CS6A Lecture 2 Scheme Jom Magrotker UC Berkeley EECS July 24, 202 http://spectrum.ieee.org/tech talk/robotics/artificial intelligence/a texas hold em tournament for ais 2 TODAY

Announcements 1 Today s Menu Sample A* Problem A* Code Traveling Salesman - Brute Force {See Traveling_Salesman.ppt } 2 Heuristic Searches The following figure shows a search tree with the state indicated

### Lisp: Lab Information. Donald F. Ross

Lisp: Lab Information Donald F. Ross General Model program source text stream What you need to write lexical analysis lexemes tokens syntax analysis is_id, is_number etc. + grammar rules + symbol table