# A Quick Introduction to Common Lisp

Size: px
Start display at page:

Transcription

1 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 basic data type; programs are themselves list structures, and thus can be created and manipulated just like other data. This introduction isn t intended to give you all the details, but just enough to get across the essential ideas, and to let you get under way quickly. The best way to make use of it is in front of a computer, trying out all the things mentioned. Basic characteristics of Lisp and Common Lisp: Lisp is primarily intended for manipulating symbolic data in the form of list structures, e.g., (THREE (BLIND MICE) SEE (HOW (THEY RUN))!) rithmetic is included, e.g., (SQRT (+ (* 3 3) (* 4 4))) or (sqrt (+ (* 3 3) (* 4 4))) (Common Lisp is case-insensitive, except in strings between quotes "... ", specially delimited symbols like Very Unusual Symbol!, and for characters prefixed with \ ). Common Lisp (unlike John McCarthy s original pure Lisp) has arrays and record structures; this leads to more understandable and efficient code, much as in typed languages, but there is no obligatory typing. ll computation consists of expression evaluation. For instance, typing in the above (SQRT...) expression and hitting the enter key immediately gives 5. Lisp is a functional language based on lonzo Church s λ-calculus (which like Turing machines provides a complete basis for all computable functions). For instance, a function for the square root of the sum of two squares can be expressed as (lambda (x y) (sqrt (+ (* x x) (* y y)))). We can save this function by giving it a name using defun (examples will be seen soon), or we can apply it directly, as in ((lambda (x y) (sqrt (+ (* x x) (* y y)))) base height), where base and height are assumed to be variables that have been assigned some numerical values. Since data are list structures and programs are list structures, we can manipulate programs just like data. We can also easily define special-purpose list-structured 1

2 languages (e.g., for planning or for NLP) and write interpreters for these languages in Lisp. List structures are a very flexible data type it s hard to think of any types of information that can t be easily represented as list structures. nd as long as we re using list structures as our data types, we can enter data just by supplying list structures we need not write special reading or structure-building functions. For instance, (SETQ X (THREE (BLIND MICE) SEE (HOW (THEY RUN))!)) sets the variable X to the indicated list structure value; and (RED) will read in any list structre. Similarly printing out list structures requires no special printing functions (the functions PRINT and FORMT do almost everything we need). Common Lisp arrays and record structures are also pretty easy to handle in I/O. The simplicity and elegance of Lisp, and its unmatched flexibility and ease of use for I applications, have made it very durable: it is the second-oldest high-level programming language (after FORTRN), yet is still in common use. (See an assessment by Peter Norvig, director of Google Research, at Getting started Go to the directory where you want to work (and where you ll typically have various program files and data files), and type lisp (or acl on the grad network). The system will respond with loading and initialization messages, followed by a prompt like CL-USER(1): You can now type in expressions and have them evaluated. Whenever you ve got balanced brackets and hit enter, the value (or an error message) is printed, and then you re prompted for further input. Getting out To escape from Common Lisp, type (exit), or :exit or just :ex Saying Hello ccording to N. Wirth (author of LGOLW and Pascal), a good way to get an initial glimpse of a language is to see a program that prints hello. Here s the Lisp version (just one quoted symbol!): 2

3 hello When you hit enter, you ll get HELLO which is the result of evaluating hello. If you want lower case, you can use the character string "hello" which yields "hello" (still in quotes) i.e., strings evaluate to themselves. If you want the quotes to be invisible, you can use (format t "hello") However, besides getting hello without quotes you ll now also get NIL on a new line; that s because the format function is special, having both an effect and a value: the effect is to print out the material in quotes (plus possibly values of variables see example below), and the value is NIL. But suppose we want a more elaborate greeting, wherein the user is asked for her/his name. Then we could define a hello-function as follows: (defun hello () (format t "Hello, what s your first name?~%") (setq *name* (read)) (format t "Nice to meet you, ~a" *name*) ) Note that the first argument of defun is a function name, the second is a list of arguments (here, none), and after that we have any number of expressions which will be evaluated in sequence, and which comprise the body of the definition. In effect, defun just makes a λ-expression out of the argument list and the body, and makes this lambda expression the function-value of the first argument (the function name). In other words, it provides a way of naming a λ-expression. (Note that the function value of a symbol won t interfere with other ordinary values we might associate with it; but generally it s wise to steer away from such multiple uses of a symbol.) The ~% in the first format statement means go to new line. The setq expression sets the global value of *name* to be whatever Lisp expression is read in by (read). symbol can have both a global value, and a value local to a particular function call. But it s conventional to use an initial and final * for global variables, and to avoid using these as local variables. (We ll see local variables in later examples.) The ~a in the second format statement means print the value of the next expression given as additional argument of format and in this case the next argument is *name*, and its value is whatever name the user supplied. When we type in this function definition and hit enter, we get HELLO which is just the name of the function we ve defined. (So even an expression that defines a function gets a value.) However, defun is primarily evaluated for its effect, not its value, and the effect as indicated is that Lisp will now remember the definition of the hello function. 3

4 To execute the hello function, we type (hello) and hit enter, with the result Hello, what s your first name? Joe (assumed as user input) Nice to meet you, JOE NIL The final NIL is the value returned by the hello function when it terminates. Of course, we can also use the expression (hello) as part of another program, which does not immediately terminate after the greeting. In general, we can evaluate functions for particular arguments by writing (function-name arg 1 arg 2... arg n ) Since hello had no arguments, we wrote (hello). Except for certain functions like defun, setq, and a few others, arguments are first evaluated, and only then is the function applied to the argument values. Loading Lisp code from a file If you have placed Lisp code (a series of symbolic expressions) in a file my-file.lisp, you can run this code and then continue on-line as follows (assuming you are already in Lisp, having typed lisp at some point): (load "myfile.lisp") assuming that this file is in the same directory as the one from which you are running Lisp. You can also use the shorter version (load "myfile"), i.e., without the.lisp extension but this will use a compiled version of the file if one exists. If you are user smith and the desired file my-file is in a directory lisp-programs, you could also use (load "/u/smith/lisp-programs/my-file.lisp") (or without the.lisp ), no matter what directory you are currently in. fter this is evaluated, you can use functions and constants that were defined in my-file.lisp. 4

5 Data types The smallest symbolic expressions are atoms, and we build larger expressions out of these. toms come in several varieties, as indicated in the following tree: atoms numeric symbols (literal atoms) fixed point, e.g., fractions (ratios), e.g., floating point, e.g., boolean values: 17, 3400,... 1/2, 8/3, , 34.5, 2.3E15,... T, NIL (= ()) nonboolean, e.g., John, LOVES, Mary123, 123Mary?!, Strange >, \(op\.cit\.\) characters, e.g., #\a, #\, #\b, #\B, #\!, #\#, #\Space,... (can be printed as a,, b,!, #,,... ) strings, e.g., "This is a long string" s an oddball category of literal atoms we should also mention keywords; these start with a colon (e.g., :key) and have very special uses. colon in the middle of an atom also has a special meaning: the part before the colon is a package name, and the part after it is the name of a function in the package referred to. But we won t go into that here. Dotted pairs discussed below List structures e.g., (3 "blind" mice) ( B (C D E)) NIL (same as ( )) (this (list (is (nested to (depth 5) see?)))) Note: In general, expressions are evaluated when they occur as an argument (non-initial list element). However, T, NIL, numbers, characters, strings and keywords evaluate to themselves. In addition, quotation e.g., THIS or (a b) prevents evaluation of the expression quoted (in the two examples we just get back THIS and ( B)). lso as previously noted, certain special functions prevent evaluation of (some of) their arguments (e.g., defun, setq, etc.). Initial list elements are interpreted as functions, unless the list is inside a quoted context. So for instance (+ x y) evaluates to the sum of values 5

6 associated with x and y, but (+ x y) just evaluates to the expression (+ x y). rrays e.g., we can define an array using (setq (make-array (3 4) :initial-contents ((a b c d) 2 3 4) ("this" 5 6 7) (#\C )) )) Retrieving a value: (setq value (aref 2 3)) 6 Changing a value: (setf (aref 2 3) 12) The :initial-contents keyword, together with the expression following it supplying the initial contents of the array, is optional. Optional parameters are standardly indicated with keywords, which as mentioned start with a colon and evaluate to themselves. Hash tables e.g., (setq (make-hash-table :test equal)) ; creates it, allows lists as keys (setf (gethash color ) brown) ; sets value of an entry (setf (gethash name ) fred) ; sets value of an entry (gethash color ) ; yields BROWN (gethash name ) ; yields FRED (gethash pointy ) ; yields NIL Record structures e.g., (defstruct course name time credits room instructor) (setq CSC242 (make-course :name "rtificial Intelligence" :time TR3\:00-4\:15 :credits 4 :room CSB601 :instructor "John McCarthy")) (setf (course-instructor CSC242) "Marvin Minsky") ; changes instructor (course-time CSC242) ; yields TR3:00-4:15 Other data structures: functions, packages, streams,... 6

7 Dotted pairs and binary trees It s usually most convenient to think of our data (and programs) as atoms and lists. However, list structures are actually built out of dotted pairs. You can think of these as pairs of storage locations (cells) where each location contains a pointer either to an atom or to another dotted pair. In this way we can build up arbitrary binary trees, and these can be used to represent list structures. (But while all list structures can be represented as binary trees, not all binary trees represent list structures; so dotted pairs in principle provide slightly more flexibility than list structures.) Here are examples of how we build list structures out of dotted pairs: () is really (. NIL), or internally, Here denotes a pointer to NIL ( B) is really (. (B. NIL)), or internally, as tree B drawn more like a list: B ( B C) is really (. (B. (C. NIL))), i.e., B C ( B (C D E)) suppose this is the value of X; then we have X B C D E n example showing that not all binary trees are lists is the following tree: s a dotted pair structure this is B C (. (B. C)) (also written as ( B. C)), where we can t get rid of all the dots The left part of a dotted pair (i.e., the destination of the left pointer) is called its CR, and the right part its CDR (pronounced could r ). CR also has the alternative name 7

8 first, since it picks out the first element of a list, as seen in the following. (car ()) is the same as (car (. NIL)) which yields (cdr ()) is the same as (cdr (. NIL)) which yields NIL (car ( B)) is the same as (car (. (B. NIL)) which yields (cdr ( B)) is the same as (cdr (. (B. NIL)) which yields (B. NIL), i.e., (B) Similarly (car ( B C)) yields "first of list" (cdr ( B C)) yields (B C) "rest of list" There are also functions second, third,..., tenth for easy access to the first few elements of a list, though we could also use (car (cdr...)), (car (cdr (cdr...))), etc. dditional easy access functions you should know about are caar, cadr, cdar, cddr, caaar,... cddddr as well as nth, nthcdr, and last (which does not give the last element of a list, but rather the last dotted pair, i.e., a list containing just the last element). Here are some more examples, assuming that we have defined x by the indicated setq: (setq x ( B (C D E))) (car x) ==> (cdr x) ==> (B (C D E)) (car (cdr x)) = (cadr x) ==> B (cdr (cdr x)) = (cddr x) ==> ((C D E)) (car (cdr (cdr x))) = (caddr x) ==> (C D E) (cdr (cdr (cdr x))) = (cdddr x) ==> NIL (first (third x)) = (caaddr x) ==> C (second (third x)) ==> D (last (third x)) ==> (E) Constructing a dotted pair CONS constructs a new dotted pair and returns a pointer to it. Examples: (cons B) ==> (. B) (cons NIL) ==> (. NIL) = () When the second argument of a CONS is a list, we can think of its operation as inserting the first argument at the head of the list given as second argument. Thus 8

9 (CONS (B C)) yields ( B C) new dotted pair (CONS ( B) (C (D E))) yields (( B) C (D E)) B C (CONS ( ) ( )) yields (( )) = (NIL) etc. Basic mechanism: expression evaluation Note that expressions like yielding ~~~~~~~~ hello HELLO (load "my-file") NIL (setq n 5) 5 (car (a b c)) (cons 3 n) (3. 5) are complete stand-alone programs. This is in contrast with other programming languages, where expressions analogous to these could only occur within the body of some function or procedure definition (well, except for the load statement). However, only the second and third of the above statements have any lasting effect. In particular, the second statements (as you ve learned) loads a file, and this file may contain function definitions, etc., that can be used thereafter. The third statement, as discussed before, sets the global value of a variable. Note again that setq does not evaluate its first argument; it does evaluate the second, but since this is a number, it evaluates to itself. (Recall that the boolean literals T, NIL (or ( )), characters, strings, and keywords also evaluate to themeselves.) Of course, an extremely important type of expression is defun, whose evaluation makes a function available for subsequent use. We now look at some simple examples. Some simple examples of functions true-listp a function that checks whether its argument is a true list at the top level (its elements need not be lists). Note the use of tail-recursion (recursion on the cdr of the input). Note: The predefined function LISTP just checks if its argument is nil or a cons (i.e., a dotted pair); e.g., (listp (a. b)) = T. lso note that we can put 9

10 comments after a semicolon the Lisp reader ignores semicolons and everything following them. (defun true-listp (x) ;~~~~~~~~~~~~~~~~~~~~ (or (null x) (and (listp x) (true-listp (cdr x)))) ) e.g., (true-listp (a (b. c) c)) ==> T (true-listp (a. b)) ==> NIL (true-listp 3) ==> NIL (true-listp NIL) ==> T (true-listp (a. (b c))) ==> T list-structure a function that checks whether its argument is a true list structure (i.e., it s not an atom other than NIL and prints without dots ). gain we use tail-recursion. (defun list-structure (x) ;~~~~~~~~~~~~~~~~~~~~ (or (null x) (and (not (atom x)); we could use (listp x) instead (or (atom (car x)) (list-structure (car x))) (list-structure (cdr x)) ))) e.g., (list-structure a) ==> NIL (list-structure (a b c)) ==> T (list-structure (a (b. c) c)) ==> NIL (list-structure (a. (b c))) ==> T standard-dev a function for computing the standard deviation (root mean square deviation from the mean) of a list of numbers. This illustrates the use of the fell swoop functions reduce and mapcar, as well as direct use of a lambda-expression. (defun standard-dev (data) ;~~~~~~~~~~~~~~~~~~~~~~~~~ ; data: a list of numbers ; RESULT: the root mean square deviation from the mean of the data ; (let ((n (length data)) mean); define 2 local variables, supplying ; initial value = (length data) for n (if (zerop n) (return-from standard-dev nil)) (if (= n 1) (return-from standard-dev 0)) 10

11 (setq mean (/ (reduce # + data) n)) (sqrt (/ (reduce # + (mapcar # (lambda (x) (expt (- x mean) 2)) data )) n )))); end of standard-dev e.g., (standard-dev ()) ==> NIL (standard-dev (1)) ==> 0 (standard-dev (2 6)) ==> 2 (standard-dev ( )) ==> (cf., 5/sqrt(3) = 2.89 :-) Some debugging hints Probably the most useful debugging commands in llegro CL are :dn list most recent evals (most recent first) :loc give values of local variables :help list all debugging commands (which includes the others here) Of course, format statements are very useful for printing out values of variables at any point in a program. lso the trace function lets you see the inputs and outputs of function calls for the functions you are tracing. For example, you can say (trace list-structure standard-dev) to trace the inputs and outputs of the above functions (note that you don t quote the function names given to trace ). Now, trace can give you far more detail than you want to see. trick for tracing only the calls to a function in certain places is to temporarily create a synonym for the function, replace the occurrence of interest with the synonym, and trace the synonym. For example, if for some reason you want to trace only the first recursive call in liststructure, you could write (defun list-structure1 (x) (list-structure x)) (defun list-structure (x) ;~~~~~~~~~~~~~~~~~~~~ (or (null x) (and (not (atom x)); we could use (listp x) instead (or (atom (car x)) (list-structure1 (car x))) 11

12 (trace list-structure1) (list-structure (cdr x)) ))) So then running list-structure for some argument will just print I/O for list-structure1. Something that easily happens in Lisp is that you re missing a bracket somewhere in a Lisp file you re trying to load, causing the Lisp reader to run to the end of the file, and complain, Error: eof encountered on stream #<FILE-SIMPLE-STREM...>... [condition type: END-OF-FILE] You might then wonder exactly where the problem lies. You can check which of your functions or parameters actually got defined before Lisp crashed by using commands like (fboundp my-func1) for a function or (boundp *my-global-par1*) for a parameter. You can also tell if a structured type such as personal-record (perhaps with fields like name, age, occupation, etc.) was successfully defined by typing, e.g., (fboundp personal-record-name), which is the access function to the name field automatically defined if the record type has been defined. Finally, a very useful method of saving everything that is printed in the course of an execution run (including traces) is to create a dribble file before you start the execution. For example, before applying list-structure to an argument, we could say (dribble "trial-run") (trace list-structure) (list-structure (a. (b c))) (dribble) Note: the final (dribble) closes the dribble file. You can then look in the trial-run file to see exactly what happened with the advantage that you can use a file search command to quickly find events of interest. 12

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

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

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

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

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

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

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

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

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

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

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

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

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

### Introduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V.

Introduction to LISP York University Department of Computer Science and Engineering York University- CSE 3401- V. Movahedi 11_LISP 1 Introduction to LISP Evaluation and arguments S- expressions Lists Numbers

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

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

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

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

### SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME COMPUTER SCIENCE 6A October 29th, 202 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, we will eventually

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

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

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

### Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

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

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

### CMSC 331 Final Exam Fall 2013

CMSC 331 Final Exam Fall 2013 Name: UMBC username: You have two hours to complete this closed book exam. Use the backs of these pages if you need more room for your answers. Describe any assumptions you

### Discussion 4. Data Abstraction and Sequences

Discussion 4 Data Abstraction and Sequences Data Abstraction: The idea of data abstraction is to conceal the representation of some data and to instead reveal a standard interface that is more aligned

### Lists in Lisp and Scheme

Lists in Lisp and Scheme a Lists in Lisp and Scheme Lists are Lisp s fundamental data structures, but there are others Arrays, characters, strings, etc. Common Lisp has moved on from being merely a LISt

### Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Pairs and Lists in Racket. Box-and-pointer diagrams for cons trees

The Pros of cons: in Racket CS251 Programming Languages Fall 2018, Lyn Turbak Department of Computer Science Wellesley College booleans: #t, #f numbers: integers: 42, 0, -273 ra3onals: 2/3, -251/17 floa3ng

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

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

### LECTURE 16. Functional Programming

LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

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

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

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

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

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

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

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

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

### John McCarthy IBM 704

How this course works SI 334: Principles of Programming Languages Lecture 2: Lisp Instructor: an arowy Lots of new languages Not enough class time to cover all features (e.g., Java over the course of 34-36:

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

SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

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

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

### COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

### Project 1: Part 1. x = b± b 2 4ac., x 2 = b b 2 4ac.

Project 1: Part 1 Project 1 will be to calculate orthogonal polynomials. It will have several parts. Note: The scheme code in this writeup is available in the file project1.scm, available from the course

### Lecture #24: Programming Languages and Programs

Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware

### Repetition Through Recursion

Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something

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

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

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

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

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

### CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

CS61A Notes Week 6B: Streams Streaming Along A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the

### Project 1: Part 1. Project 1 will be to calculate orthogonal polynomials. It will have several parts. x = b± b 2 4ac., x 2 = b b 2 4ac.

Project 1: Part 1 Project 1 will be to calculate orthogonal polynomials. It will have several parts. Warmup: Solving quadratic equations The quadratic formula says that the solutions of ax 2 +bx+c = 0

### Introduction to Functional Programming and basic Lisp

Introduction to Functional Programming and basic Lisp Based on Slides by Yves Lespérance & Peter Roosen-Runge 1 Functional vs Declarative Programming declarative programming uses logical statements to

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

### A little bit of Lisp

B.Y. Choueiry 1 Instructor s notes #3 A little bit of Lisp Introduction to Artificial Intelligence CSCE 476-876, Fall 2017 www.cse.unl.edu/~choueiry/f17-476-876 Read LWH: Chapters 1, 2, 3, and 4. Every

### CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian

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

### 1.3. Conditional expressions To express case distinctions like

Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

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

### 6.001: Structure and Interpretation of Computer Programs

6.001: Structure and Interpretation of Computer Programs Symbols Quotation Relevant details of the reader Example of using symbols Alists Differentiation Data Types in Lisp/Scheme Conventional Numbers

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

### Jatha. Common Lisp in Java. Ola Bini JRuby Core Developer ThoughtWorks Studios.

Jatha Common Lisp in Java Ola Bini JRuby Core Developer ThoughtWorks Studios ola.bini@gmail.com http://olabini.com/blog Common Lisp? Common Lisp? ANSI standard Common Lisp? ANSI standard Powerful Common

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

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

### An Explicit-Continuation Metacircular Evaluator

Computer Science (1)21b (Spring Term, 2018) Structure and Interpretation of Computer Programs An Explicit-Continuation Metacircular Evaluator The vanilla metacircular evaluator gives a lot of information

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

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

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

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

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

### Fundamentals of Programming. Lecture 3: Introduction to C Programming

Fundamentals of Programming Lecture 3: Introduction to C Programming Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department Outline A Simple C

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

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

### Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Programming with Pairs and Lists. Box-and-pointer diagrams for cons trees

The Pros of cons: Programming with CS251 Programming Languages Fall 2017, Lyn Turbak Department of Computer Science Wellesley College booleans: #t, #f numbers: integers: 42, 0, -273 ra3onals: 2/3, -251/17

### Discussion 12 The MCE (solutions)

Discussion 12 The MCE (solutions) ;;;;METACIRCULAR EVALUATOR FROM CHAPTER 4 (SECTIONS 4.1.1-4.1.4) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;from section 4.1.4 -- must precede def of

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

### CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages 3: Scheme Introduction Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg [1]

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