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

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

### Functional programming with Common Lisp

Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

### 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

### Lisp Basic Example Test Questions

2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2

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

CS 6A Scheme Summer 207 Discussion 0: July 25, 207 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,

### 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

### CSCI337 Organisation of Programming Languages LISP

Organisation of Programming Languages LISP Getting Started Starting Common Lisp \$ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ +' / I 8 8 8 8 8 8 \ -+-' / 8 8 8 ooooo

### SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 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,

### 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

### Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have

### 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,

### 15 Unification and Embedded Languages in Lisp

15 Unification and Embedded Languages in Lisp Chapter Objectives Chapter Contents Pattern matching in Lisp: Database examples Full unification as required for Predicate Calculus problem solving Needed

### Lisp. Versions of LISP

Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major

### ;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

Homework 1 Due 13 September Handout 2 CSC 131: Fall, 2006 6 September Reading 1. Read Mitchell, Chapter 3. 2. The Scheme Tutorial and the Scheme Quick Reference from the Links web page, as needed for the

1 of 5 5/11/2006 12:10 AM CS 61A Spring 2006 Midterm 2 solutions 1. Box and pointer. Note: Please draw actual boxes, as in the book and the lectures, not XX and X/ as in these ASCII-art solutions. Also,

### Imperative, OO and Functional Languages A C program is

Imperative, OO and Functional Languages A C program is a web of assignment statements, interconnected by control constructs which describe the time sequence in which they are to be executed. In Java programming,

### CS61A Midterm 2 Review (v1.1)

Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

### 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

### 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

### 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

### 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

### Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

### 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

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

Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define

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

6.001, Fall Semester, 2002 Quiz II Sample solutions 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs

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

The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

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

Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

### 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

### 6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

### Homework 1. Reading. Problems. Handout 3 CSCI 334: Spring, 2012

Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2012 Reading 1. (Required) Mitchell, Chapter 3. 2. (As Needed) The Lisp Tutorial from the Links web page, as needed for the programming questions.

### 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,

### Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

### 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.)

### Functional Programming. Big Picture. Design of Programming Languages

Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

### Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 208 Discussion 8: October 24, 208 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

### Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

### Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

### INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017 Agenda 2 Previously Common

### Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator.

LISP NOTES #1 LISP Acronymed from List Processing, or from Lots of Irritating Silly Parentheses ;) It was developed by John MacCarthy and his group in late 1950s. Starting LISP screen shortcut or by command

### Functional Programming. Pure Functional Programming

Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

### 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

### User-defined Functions. Conditional Expressions in Scheme

User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

### Introduction to Scheme

How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

### (defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts))

PROBLEM NOTES Critical to the problem is noticing the following: You can t always replicate just the second node passed to fill-nodes. The node to be replicated must have a common parent with the node

### 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

### 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

### 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,

### Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial About this Document This document was written to accompany an in-person Lisp tutorial. Therefore, the information on this document alone is not likely to be sufficient

### 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:

### SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 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,

### An introduction to Scheme

An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

### Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process

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

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise If you re not already crazy about Scheme (and I m sure you are), then here s something to get

### by the evening of Tuesday, Feb 6

Homework 1 Due 14 February Handout 6 CSCI 334: Spring 2018 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, and

Announcements 1 Today s Menu Finish Introduction to ANNs (original material by Dr. Mike Nechyba) > Slides 58-60 > Adjusting the Learning Rate Loose Ends in > Lambda Expressions Review > I/O Functions >

### FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti L I S P - Introduction L I S P

### Functional Languages. Hwansoo Han

Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

### Documentation for LISP in BASIC

Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

### Midterm Examination (Sample Solutions), Cmput 325

Midterm Examination (Sample Solutions, Cmput 325 [15 marks] Consider the Lisp definitions below (defun test (L S (if (null L S (let ((New (add (cdar L S (test (cdr L New (defun add (A S (if (null S (cons

### Functional Programming

Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

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

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

### FP Foundations, Scheme

FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

### INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is

### 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

### 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.

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti Comments in Lisp ; comments

### Putting the fun in functional programming

CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional

### Notes on Higher Order Programming in Scheme. by Alexander Stepanov

by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

### A Small Interpreted Language

A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases

### Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2017 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, but

### Basic Scheme February 8, Compound expressions Rules of evaluation Creating procedures by capturing common patterns

Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns Previous lecture Basics of Scheme Expressions and associated values (or syntax and

### UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

### 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

### INF4820. Common Lisp: Closures and Macros

INF4820 Common Lisp: Closures and Macros Erik Velldal University of Oslo Oct. 19, 2010 Erik Velldal INF4820 1 / 22 Topics for Today More Common Lisp A quick reminder: Scope, binding and shadowing Closures

### PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

MITOCW Lecture 10A [MUSIC PLAYING] PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between all these high-level languages like Lisp and the query

### CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

### 6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

### CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is

### 6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

### 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

### FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší

### 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

### Review of Functional Programming

Review of Functional Programming York University Department of Computer Science and Engineering 1 Function and # It is good programming practice to use function instead of quote when quoting functions.

### 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..........................................

### Functional Programming Languages (FPL)

Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

### CS 61A Discussion 8: Scheme. March 23, 2017

CS 61A Discussion 8: Scheme March 23, 2017 Announcements Ants is due today. Finish it! Also turn it in! HW 6 is due tomorrow. Finish it! Also turn it in! HW party today from 6:30-8:30p in 247 Cory. Midterm

### Environments

Environments PLAI Chapter 6 Evaluating using substitutions is very inefficient To work around this, we want to use a cache of substitutions. We begin evaluating with no cached substitutions, then collect

### 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

### 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

### 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

### 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

### University of Massachusetts Lowell

University of Massachusetts Lowell 91.301: Organization of Programming Languages Fall 2002 Quiz 1 Solutions to Sample Problems 2 91.301 Problem 1 What will Scheme print in response to the following statements?

### Comp 311: Sample Midterm Examination

Comp 311: Sample Midterm Examination October 29, 2007 Name: Id #: Instructions 1. The examination is closed book. If you forget the name for a Scheme operation, make up a name for it and write a brief

### UNIVERSITY of CALIFORNIA at Berkeley Department of Electrical Engineering and Computer Sciences Computer Sciences Division

UNIVERSITY of CALIFORNIA at Berkeley Department of Electrical Engineering and Computer Sciences Computer Sciences Division CS61A Kurt Meinz Structure and Interpretation of Computer Programs Summer 2002

### Programming Languages

Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages