CSCI337 Organisation of Programming Languages LISP

Similar documents
Common Lisp. Blake McBride

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

Common LISP Tutorial 1 (Basic)

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

Lisp. Versions of LISP

Functional programming with Common Lisp

Functional Programming. Pure Functional Languages

Lecture Notes on Lisp A Brief Introduction

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

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

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Programming

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Imperative, OO and Functional Languages A C program is

Common LISP-Introduction

Scheme: Strings Scheme: I/O

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

Functions, Conditionals & Predicates

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

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

Scheme Quick Reference

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

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

Lisp Basic Example Test Questions

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

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

Scheme Quick Reference

FP Foundations, Scheme

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

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

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

CS 360 Programming Languages Interpreters

Functional Programming

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

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

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

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

An Introduction to Scheme

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Introduction to Scheme

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

A Genetic Algorithm Implementation

Functional Languages. Hwansoo Han

Functional Programming. Big Picture. Design of Programming Languages

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

LECTURE 16. Functional Programming

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

CSC 533: Programming Languages. Spring 2015

Modern Programming Languages. Lecture LISP Programming Language An Introduction

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

Scheme: Expressions & Procedures

Organization of Programming Languages CS3200/5200N. Lecture 11

SCHEME AND CALCULATOR 5b

A Quick Introduction to Common Lisp

Project 2: Scheme Interpreter

Lecture #2 Kenneth W. Flynn RPI CS

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

Putting the fun in functional programming

A Brief Introduction to Scheme (II)

15 Unification and Embedded Languages in Lisp

Chapter 15. Functional Programming Languages

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

Allegro CL Certification Program

Artificial Intelligence Programming

Chapter 1. Fundamentals of Higher Order Programming

COP4020 Programming Assignment 1 - Spring 2011

CPS 506 Comparative Programming Languages. Programming Language Paradigm

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

User-defined Functions. Conditional Expressions in Scheme

CS 314 Principles of Programming Languages

Lecture #5 Kenneth W. Flynn RPI CS

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

Scheme as implemented by Racket

Evaluating Scheme Expressions

Robot Programming with Lisp

Introductory Scheme. Revision 1

A little bit of Lisp

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Documentation for LISP in BASIC

Announcements. Today s Menu

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

Reasoning About Programs Panagiotis Manolios

Introduction to Lisp

Lambda Calculus see notes on Lambda Calculus

Chapter 11 :: Functional Languages

INF4820. Common Lisp: Closures and Macros

Allegro CL Certification Program

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

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

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

CSCC24 Functional Programming Scheme Part 2

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

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

History. Functional Programming. Based on Prof. Gotshalks notes on functionals. FP form. Meaningful Units of Work


UMBC CMSC 331 Final Exam

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

Functional Programming Languages (FPL)

CS 314 Principles of Programming Languages. Lecture 16

Transcription:

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 8oooo `- -' 8 8 8 8 8 8 o 8 8 o 8 8 ------+------ ooooo 8oooooo ooo8ooo ooooo 8 Copyright (c) Bruno Haible, Michael Stoll 1992, 1993 Copyright (c) Bruno Haible, Marcus Daniels 1994-1997 Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998 Copyright (c) Bruno Haible, Sam Steingold 1999-2000 Copyright (c) Sam Steingold, Bruno Haible 2001-2004 [1]>

A Few CLISP Commands Lisp tries to evaluate anything you type into it. Constants: [1]> 1 1 [2]> 1.0 1.0 [3]> "one" "one"

Lisp Functions Functions are written with parentheses: [1]> (+ 1 2) 3 [2]> (- 1 2) -1 [3]> (* 1 2) 2 [4]> (/ 1 2) 1/2 [5]> (* 2 3 4) 24

Combining Functions We can combine LISP functions thus: [1]> (+ (* 2 3) 5) 11 evaluates the expression (2*3)+5 and [2]> (* 2 (+ 3 5)) 16 evaluates the expression 2*(3+5)

Stopping Evaluation We can use the quote character to stop LISP from evaluating an expression. Compare: [1]> (+ 1 2) 3 with [2]> '(+ 1 2) (+ 1 2) and [3]> "(+ 1 2)" "(+ 1 2)"

Another Form of Quote We can write a quoted expression in two equivalent ways. We can write either: [1]> '(+ 1 2) or (+ 1 2) [2]> (quote (+ 1 2)) (+ 1 2)

Evaluating Quoted Expressions The function eval can force evaluation of an expression: [1]> (eval 3) 3 [2]> (eval (+ 2 3)) 5 [3]> (eval '(+ 2 3)) 5 [4]> (eval "(+ 2 3)") "(+ 2 3)"

Types in LISP Every expression in LISP has a type. We have seen some of these types already: Integer 1-3 0 Ratio 1/2-3/4 Float 1.2-3.4 String "a b c"

Hierarchy of Types in LISP Types in LISP form a heirarchy t [top level type (all other types are a sub-type)] sequence list array vector string number float rational integer ratio complex character symbol structure function hash-table nil

Booleans in LISP Note that LISP does not have an explicit Boolean data type. Instead it has two constants: T or t (equivalent to logical true) and NIL or nil (equivalent to logical false) T is the most general type. NIL is the least general type the empty set.

Testing Types We can test what the type of an expression is in LISP by using the typep function: [1]> (typep 5 'integer) T [2]> (typep 5 'float) NIL [3]> (typep 2 'rational) T [4]> (typep 2/3 'rational) T [5]> (typep 2/3 'ratio) T [6]> (typep 2 'ratio) NIL

Testing Types We can also use a shorthand version of typep: [1]> (integerp 5) T [2]> (floatp 5) NIL [3]> (rationalp 2) T [4]> (rationalp 2/3) T

Testing Types Not all types work, however. [5]> (ratiop 2/3) ** - Continuable Error EVAL: undefined function RATIOP... There is no function ratiop. This can be remedied as we will see later.

LISTS Lists are one of the critical LISP data types. We represent a list as a sequence of elements contained in parentheses. Thus: [1]> '(1 2 3) (1 2 3) is a list with three elements. Note: so is (+ 2 3)

LISTS We can demonstrate this as follows: [1]> (typep '(1 2 3) 'list) or T [2]> (listp '(+ 2 3)) T

Manipulating LISTS A list consists of two parts: A head accessible via the car function: [1]> (car '(1 2 3)) 1 A tail accessible via the cdr function: [2]> (cdr '(1 2 3)) (2 3)

Manipulating LISTS We can combine car and cdr to extract elements from a list. Thus: [1]> (car (cdr '(1 2 3))) 2 extracts the second element. We can combine sequences of car and cdr into a single function: [2]> (cadr '(1 2 3)) 2

Lists of Lists A List can contain a list as an element. Thus: [1]> '(1 (2 3) (4 5)) (1 (2 3) (4 5)) is a list of three elements: an integer, [2]> (car '(1 (2 3) (4 5))) 1 a list, [3]> (cadr '(1 (2 3) (4 5))) (2 3) and another list, [4]> (caddr '(1 (2 3) (4 5))) (4 5)

Testing for Equality We can test the equality of two expressions with the equal function. Thus: [1]> (equal 3 3) T [2]> (equal 3 4) NIL [3]> (equal (+ 2 4) (* 2 3)) T

Testing for Equality As we would expect: [1]> (equal 3 (+ 1 2)) T and [2]> (equal '3 (+ 1 2)) T but [3]> (equal 3 '(+ 1 2)) NIL

Equality of Lists As you might expect: [1]> (equal '(1 2 3 4) '((1 2) (3 4))) NIL The first is a list of 4 atoms, the second a list of two lists.

Complex Lists A list can contain multiple data types. Thus: [1]> '((1 "fred") (2 "bill") (3 "jane")) ((1 "fred") (2 "bill") (3 "jane")) is a list of lists where each sub-list contains an integer and a string.

Building Lists There are a number of functions for building lists. These include: list cons append as well as simply quoting the list Each works in a different way.

The list Function This function builds a list from a sequence of elements. Thus: [1]> (list 1 2 3) (1 2 3) and [2]> (list (list 1 2) (list 2 3)) ((1 2) (2 3))

The list Function This function is equivalent to quoting the list. Thus: [1]> (list 1 2 3) (1 2 3) and [1]> '(1 2 3) (1 2 3) are equivalent.

The cons Function This function adds an element to the head of a list. Thus: [1]> (cons 1 (list 2 3)) or (1 2 3) [2]> (cons 1 '(2 3)) (1 2 3)

The append Function This function adds the contents of two lists together to form a single list. Thus: [1]> (append (list 1 2) (list 3 4)) or (1 2 3 4) [2]> (append '(1 2) '(3 4)) (1 2 3 4)

More About the cons Function As we would expect: [1]> (cons 1 '(2)) (1 2) However: [2]> (cons 1 2) (1. 2) What is going on here? Where did the dot come from?

How Lists Are Built A list is built as a sequence of words. The first half of each word contains the head of the list. The second half contains a pointer to the tail of the list. The last word contains the last element of the list and NIL.

How Lists Are Built Graphically: The list (1 2 3) is built as follows. 1 2 3 nil We can also write this as follows: (1. (2. (3. NIL)))

How Lists Are Built Thus the list: (1 2) is really shorthand for: (1. (2. nil)) 1 2 nil Which is clearly different from: (1. 2) 1 2

How Lists Are Built We can verify this as follows: [1]> '(1. nil) and (1) [2]> '(1. (2. (3. nil))) (1 2 3)

Accessing Lists Elements The function nth extracts the n th element of a list. Thus: [1]> (nth 0 '(1 (2 3) (4 5))) 1 [2]> (nth 1 '(1 (2 3) (4 5))) (2 3) [3]> (nth 2 '(1 (2 3) (4 5))) (4 5) [4]> (nth 1 (nth 2 '(1 (2 3) (4 5)))) 5

Vectors Lists are easy to use but inefficient. We can only get to a list element by following chains of pointers. An alternative to a list is a vector, a directly indexed sequence of values. A vector in LISP can be a sequence of any data type.

Making Vectors We can construct a vector using the vector function. Thus: [1]> (vector 1 2 3) #(1 2 3) Note the notation for a vector. We can also create a vector in this way: [2]> #(1 2 3) #(1 2 3)

Complicated Vectors A vector can contain multiple data types. For example: [1]> (vector 1 '(2 3) #(2 3) 2/3) #(1 (2 3) #(2 3) 2/3) is a vector containing: An integer 1 A list (2 3) A vector #(2 3) A ratio 2/3

Vectors vs. Lists A vector is not a list. Consider: [1]> (listp '(1 2 3)) T Compared with: [2]> (listp #(1 2 3)) NIL This means we cannot use car, cdr and nth with vectors.

Vectors vs. Lists Both vectors and lists are sequences however. Consider: [1]> (typep '(1 2 3) 'sequence) T [2]> (typep #(1 2 3) 'sequence) T

Arrays An array is a generalisation of a vector to more than one dimension. We construct an array thus: [1]> #2a((1 2 3)(4 5 6)) or #2A((1 2 3) (4 5 6)) [2]> #2a((1 2)(3 4)(5 6)) #2A((1 2) (3 4) (5 6)) Note the number of dimensions.

Vectors are Arrays A vector is a 1-dimensioned array: [3]> #1a(1 2 3) #(1 2 3) Note: an array is not a vector of vectors. [1]> (equal #2a((1 2)(2 3)) #(#(1 2)#(2 3))) NIL

Accessing Array Elements We can access an array element with the aref function: [1]> (aref #(1 2 3) 1) 2 [2]> (aref #2a((1 2 3)(4 5 6)) 1 0) 4

Strings Any LISP program is likely to involve character strings. In LISP, a string is a sub-type of vector. Specifically a vector of characters. String are specified with double quotes. [1]> "This is a string." "This is a string."

Combining Strings Strings can be joined with the concatenate function. Thus: [1]> (concatenate 'string "This is " "a string.") "This is a string. and [2]> (concatenate 'string "This " "is" " another " "string.") "This is another string."

Searching Strings We can look for a substring using the search function. Thus: [1]> (search "c" "abcde") or 2 [2]> (search "xyz" "abcde") NIL

Extracting Substrings We can use the subseq function to extract a substring from a string. The function has two forms: [1]> (subseq "This is a string" 8) and "a string (extract from character 8 onwards) [2]> (subseq "this is a string" 5 7) "is" (extract from character 5, stop at character 7)

Extracting Characters The char function can be used to extract a single character from a string: [1]> (char "this is a string" 3) #\s [2]> (char "this is a string" 4) #\Space

The Character Type The sequence "x" refers to a string of length one. This is not the same as a single character. We can specify a single character in LISP as follows: [1]> #\a #\a [2]> #\space #\Space Note that we use the keyword space to refer to a space character.

Trimming Strings The string-trim function can be used to remove unwanted characters (often space) from the ends of a string. [3]> (string-trim '(#\space) " this string needs trimming ") or "this string needs trimming" [4]> (string-trim '(#\a #\z) "azaabbbzzbbbzaza") "bbbzzbbb Note that interior characters are not removed.

String Case Two functions allow the manipulation of the case of letters in strings: [8]> (string-upcase "This is a string!") "THIS IS A STRING! and [9]> (string-downcase "SO is THIS!") "so is this!"

More on equality LISP distinguishes between four different equality tests: eq eql equal and equalp Each behaves in a slightly different way.

The eq Function (eq x y) is true if and only if x and y are the same identical object. Effectively this means that x and y point at the same memory location. The result of the eq function is often not what you expect: [1]> (eq "abc" "abc") NIL

The eql Function (eql x y) is true if (eq x y) is true, or if x and y are numbers of the same type with the same value, or if they are character objects that represent the same character. [1]> (eql "abc" "abc") NIL Both eq and eql have implementation-dependent results for some tests. The eql function has slightly less implementationdependence. (eq 3 3) vs. (eql 3 3)

The equal Function (equal x y) is true if x and y are structurally similar (isomorphic) objects. A rough rule of thumb is that two objects are equal if and only if their printed representations are the same. [1]> (equal "abc" "abc") T

The equalp Function (equalp x y) if (equal x y); if x and y are characters and satisfy char-equal, which ignores alphabetic case and certain other attributes of characters; if they are numbers and have the same numerical value, even if they are of different types; or if they have components that are all equalp. [4]> (equalp Abc" "abc") T

LISP Functions LISP supports two types of functions: unnamed (lambda) functions and named functions. We will look at these in turn.

Lambda Functions Lisp allows us to define an anonymous function using the lambda form. This looks like: (lambda (parameter_list) (function_body)) where (parameter_list) is the list of formal parameters for the function and (function_body) is the code of the function.

Lambda Functions E.g. [1]> '(lambda (x) (* 2 x)) (LAMBDA (X) (* 2 X)) which can be compared with λx. 2x

Evaluating Lambda Functions Because they are equivalent to any other LISP functions, lambda functions are evaluated in the same way. Thus: [2]> ((lambda (x) (* 2 x)) 4) 8 is equivalent to ((λx. 2x) 4)

Multivariate Lambda Functions We can define a function of more than one variable as follows: [1]> '(lambda (x y) (+ (* x y) y)) (LAMBDA (X Y) (+ (* X Y) Y)) and evaluate it thus: [2]> ((lambda (x y) (+ (* x y) y)) 2 3) 9

More Complex Lambda Functions Let us construct a lambda function to evaluate the roots of the quadratic equation: ax 2 + bx + c = 0 using the formula: x = (-b ± (b 2-4ac))/2a Thus: [1]> '(lambda (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a))) ) (LAMBDA (A B C) (LIST (/ (+ (- B) (SQRT (- (* B B) (* 4 A C)))) (* 2 A)) (/ (- (- B) (SQRT (- (* B B) (* 4 A C)))) (* 2 A))))

More Complex Lambda Functions We can use this function to solve the equation: x 2 x 6 = 0 as follows: [1]> ((lambda (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)))) 1-1 -6) (3-2) giving the results: x = 3, x = -2

Named Functions While the lambda form of a function is useful for single evaluations, it is not ideal where we need to use the same function repeatedly. For this purpose we need to be able to construct a named function: [1]> (defun quad (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)))) QUAD Note: we simply replace lambda with defun name.

Using Named Functions Once we have defined the function quad we can use it like any other LISP function: [2]> (quad 1 0-4) and (2-2) [3]> (quad 1-2 -6) (3.6457512-1.6457512)

The if Function In LISP, a choice between two alternatives is made with the if construct. Its form is: (if Boolean-expression true-expression false-expression) Thus: [5]> (if (equal 2 2) 1 2) 1 and [6]> (if (equal 2 3) 1 2) 2

The if Function We can use if to refine the quad function: [1]> (defun quad (a b c) (if (< (* b b) (* 4 a c)) "Error: no real solutions" (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) ))) QUAD to avoid errors with complex roots.

The if Function We can now use our new version of the quad function: [2]> (quad 1-2 -6) (3.6457512-1.6457512) [3]> (quad 1 2-6) (1.6457512-3.6457512) [4]> (quad 1 2 6) "Error: no real solutions"

Recursion LISP allows the definition of recursive functions. E.g the factorial function can be defined as: [1]> (defun fact (x) (if (equal x 1) 1 (* x (fact (- x 1))))) FACT and used: [2]> (fact 5) 120

Output As we have already seen we get the value of an expression as output from LISP. This is not always what we want. Consider the following function to count from i to j: [1]> (defun count (x y) (if (> x y) nil (count (+ x 1) y))) COUNT [2]> (count 1 5) NIL This is probably not what we wanted.

Output We need a way to see the count proceeding. Consider: [1]> (defun count (x y) (if (> x y) nil (count (+ (print x) 1) y))) COUNT [2]> (count 1 5) 1 2 3 4 5 NIL The print function does the job nicely.

Variations of the print Function. There are a few versions of print that produce slightly different output: [1]> (print "abc") "abc" "abc" [2]> (prin1 "abc") "abc" "abc" [3]> (princ "abc") abc "abc"

Editing, Loading and Compiling LISP Let us create a file called quad.lisp containing the following code: (defun quad (a b c) (if (< (* b b) (* 4 a c)) "Error: no real solutions" (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) )))

Editing, Loading and Compiling LISP We can the start LISP and load this code: [1]> (load "quad.lisp") ;; Loading file quad.lisp... ;; Loaded file quad.lisp T We can now use the quad function defined in the file: [2]> (quad 1-3 2) (2 1) [3]> (quad 1 1 2) "Error: no real solutions"

Editing, Loading and Compiling LISP We can now compile the file: [1]> (compile-file "quad.lisp") Compiling file /home/ian/quad.lisp... Wrote file /home/ian/quad.fas 0 errors, 0 warnings #P"/home/ian/quad.fas" ; NIL ; NIL

Editing, Loading and Compiling LISP Now we can load and use the compiled version of the program: [1]> (load "quad.fas") ;; Loading file quad.fas... ;; Loaded file quad.fas T [2]> (quad 1-3 4) "Error: no real solutions" [3]> (quad 1-3 2) (2 1)

Input in LISP The LISP read function reads one LISP object (a number, list, string etc.) and returns the object as its value. E.g. Number: [1]> (read) 3 3 Note the entry does not need to be quoted.

Input in LISP String: [2]> (read) "ab cd ef" List: "ab cd ef" [3]> (read) (1 2 (3 4)) (1 2 (3 4))

Input in LISP We can also input a string using the LISP read-line function: [11]> (read-line) abc def "abc def" ; NIL The value of (read-line) is the string entered.

An Alternative to the if Function. LISP supports a more general conditional function than if. This is the cond function. Its syntax is: (cond (condition_1 expression_1) (condition_2 expression_2) (condition_n expression_n) ) where each condition is a Boolean expression and each expression is an associated function.

An Alternative to the if Function. The cond function works in a similar fashion to the case or switch statements of imperative languages. We can implement if as a two-way cond: (if x a b) is equivalent to: (cond (x a) (T b)) Traditionally, LISP programmers always used cond rather than if.

An Example LISP Program - primes The following slides will examine the construction of a LISP function primes which will: take no arguments; read an integer upper bound and return an ordered list of primes less than or equal to the input bound. We will build the function bottom-up.

An Example LISP Program - primes We first need a Boolean function to decide whether one number is divisible by a second: (defun test-div (x y) (integerp (/ x y))) We can test this function: [1]> (test-div 4 2) T [2]> (test-div 17 5) NIL We are OK so far

An Example LISP Program - primes We can use this to build a function to determine whether a candidate is a prime number by repeated test divisions: (defun test-prime (cand div) (cond ((= cand div) t) ((test-div cand div) nil) (t (test-prime cand (+ div 2))))) Here cand is the possible prime and div is the next trial divisor. Note the recursive call of test-prime.

An Example LISP Program - primes Again, we can test this function: [1]> (test-prime 23 3) T [2]> (test-prime 25 3) NIL Once more, this seems fine

An Example LISP Program - primes Next we need a utility function, is-prime, to kickstart the test-prime function: (defun is-prime (cand) (test-prime cand 3)) We can test this: [1]> (is-prime 19) T [2]> (is-prime 21) NIL Still looking good

An Example LISP Program - primes Now we need a function which, given a (possibly prime) candidate, returns the next prime: (defun next-prime (cand) (cond ((is-prime cand) cand) (t (next-prime (+ cand 2))))) We could have used if here instead of cond. This is our second recursive function.

An Example LISP Program - primes Testing the next-prime function: [1]> (next-prime 19) 19 [2]> (next-prime 21) 23 Still on track

An Example LISP Program - primes We now need a function that will add to a list of prime numbers until we reach an upper bound: (defun list-primes (limit list) (cond ((> (next-prime (+ (car list) 2)) limit) list) (t (list-primes limit (cons (next-prime (+ (car list) 2)) list))))) Note that this function expects as input the upper bound (limit) and a partial list of primes (list). We will need to prime the list-primes function with a list like (3 2) because we need the first odd prime and because the list is constructed in reverse order.

An Example LISP Program - primes Testing this function: [12]> (list-primes 20 '(3 2)) (19 17 13 11 7 5 3 2) We are nearly there

An Example LISP Program - primes Finally, we can write the primes function: (defun primes () (reverse (list-primes (read) '(3 2)))) Which we can test: [13]> (primes) 40 (2 3 5 7 11 13 17 19 23 29 31 37) And we are done.

An Example LISP Program - primes Notes: this is not the most efficient way to calculate the prime numbers; it has a less than elegant starting point; It has a load of external functions we really shouldn t be able to see. However, it does illustrate the usual method of program development in LISP: start at the bottom; build up gradually; test as you go.

Sequential Code LISP allows the evaluation of a sequence of functions. The value of the sequence is the value of the last evaluated expression. This is not generally useful unless we introduce variables. However, there is one case in which this can be used without them.

The prompt Function Let us define a function, prompt, which solicits and reads an input: (defun prompt (x) (print x) (read)) The body of the prompt function is the sequence of functions: (print x) and (read)

Revisiting primes We can use prompt to pretty up the primes function: (defun primes () (reverse (list-primes (prompt "Enter the upper limit for primes:") '(3 2)))) Which we run: [14]> (primes) "Enter the upper limit for primes:" 40 (2 3 5 7 11 13 17 19 23 29 31 37)

Revisiting primes We could improve primes by (among other things): replacing the list with an array; creating the array in order; testing divisibility only against the primes we have already found; stopping the test earlier. Some of these changes would be trivial to code. Others would be almost impossible at least impossible without variables.

Variables in LISP We can always write a LISP program without the use of variables other than formal parameters of functions. However, this can lead to significant inefficiency. Consider the list-primes function: the expression (car list) appears twice. This is a minor example of what can be a major problem.

Variables in LISP Consider the following pseudo code: (defun func (x) (cond ((< 0 (expr0)) (expr1)) ((= 0 (expr0)) (expr2)) ((> 0 (expr0)) (expr3)))) where each of the tests involves a complex common expression, expr0. In the worst case we would evaluate the common expression three times.

Variables in LISP Compare that with the following: (defun func (x) (let ((v (expr0))) (cond ((< 0 v) (expr1)) ((= 0 v) (expr2)) ((> 0 v) (expr3))))) By pre-evaluating expr0 and saving the result in a variable v we have saved the repeated evaluation of the expression.

Variables in LISP The syntax of let is as follows: (let (list-of-associations) code-using-associations) where: list-of-associations is a list of pairs of the form: (name value) and code-using-associations is a sequence of one or more expressions using the names.

Variables in LISP A simple example: [1]> (defun f (x) (let ((a 1) (b 2) (c 3)) (+ (* a x x) (* b x) c))) F evaluates ax 2 + bx + c for (a = 1, b = 2, c = 3) [2]> (f 5) 38 Note that a, b and c are local to the let function.

Variables in LISP Compare this with: [1]> (let ((a 1)(b 2)(c 3)) (defun f (x) (+ (* a x x)(* b x) c))) F What has changed? [2]> (f 5) 38 Why does this still work?

Variables in LISP How about: [3]> (let ((a 2)(b 3)(c 4)) (f 5)) 38 Why isn t the answer 69? Note that: [4]> a *** - EVAL: variable A has no value etc. a is, as expected, undefined.

Scope of Variables The behaviour seen on the last slide is due to the scoping and evaluation time of variables in LISP. Thus, although a, b and c are undefined the values associated with them at the time f was defined are locked in.

Global Variables As we have seen, variables defined with let are local. We can define global variables using the setf function. E.g. [1]> (setf a 1) 1 [2]> a 1

Local and Global Together Care must be taken to ensure that the variable used is the right one. Consider: [1]> (setf a 'one) ONE [2]> (defun test (a) a) TEST [3]> (test 'two) TWO [4]> a ONE

Local and Global Together We can access the global version of a variable with the symbol-value function: [5]> (defun test (a) (list a (symbol-value 'a))) TEST [6]> (test 'three) (THREE ONE)

More Scope Issues Consider: [1]> (setf a 1) 1 [2]> (defun f () a) F [3]> (let ((a 5)) (f)) 1 Confused yet? By default, CLISP used lexical scope.

Lexical Scope With lexical scope, a variable within a function is bound at function definition time. Thus: (defun f () a) binds the free variable a to the global symbol (even if one does not yet exist). While: (let ((a 5)) (defun f () a)) binds the free variable a to the local variable (or its value).

Dynamic Scope We can force a variable to have dynamic scope with the defvar function. Consider the following sequence: [1]> (defvar a) A [2]> (setf a 1) 1 [3]> (defun f () a) F [4]> (let ((a 2)) (f)) 2 [5]> (f) 1

Closures Because Common Lisp is lexically scoped, when we define a function containing free variables, the system must save copies of the bindings of those variables at the time the function was defined. Such a combination of a function and a set of variable bindings is called a closure. We will come back to closures in a moment.

More on Functions A language which allows functions as data objects must also provide some way of calling them. In Lisp, this function is apply. Generally, we call apply with two arguments: a function and a list of arguments for it.

More on Functions The following four expressions all have the same effect: (+ 1 2) (apply # + (1 2)) (apply (symbol-function +) (1 2)) (apply # (lambda (x y) (+ x y)) (1 2)) We can avoid specifying the function arguments as a list (as in the second example) by using the funcall function. (funcall # + 1 2)

The # Operator The # operator quotes a function in a similar way to the operator quoting a symbol. Thus, in the same way we can set a variable to a list: (setf a (1 2)) we can set a variable to a function: (setf b # cons)

The # Operator, funcall and apply If we set a variable to a function: [1]> (setf a #'cons) #<SYSTEM-FUNCTION CONS> We can invoke it with funcall: [2]> (funcall a 1 2) (1. 2) We can also invoke it with apply: [3]> (apply a '(1 2)) (1. 2)

Direct Call with # We cannot use it directly, however: [4]> (a '(2 3)) ** - Continuable Error EVAL: undefined function A... The reason for the error in the last example is that, although a evaluates to a function, a is not the name of any defined function.

Functions That Make Functions Suppose we want a set of similar functions: addone addtwo addthree We could do this by direct definition: (defun addone (x) (+ x 1)) (defun addtwo (x) (+ x 2)) (defun addthree (x) (+ x 3))

Functions That Make Functions An alternative approach is to define a generic function: (defun addsome (n) # (lambda (x) (+ n x))) We can then define functions with setf: (setf addone (addsome 1)) (setf addtwo (addsome 2)) (setf addthree (addsome 3)) which can be accessed with funcall. So what?

List Functions Let us define a function to square a number: [1]> (defun square (x) (* x x)) SQUARE We can use it to square a single number but not a list of numbers. We can apply the function to each element of a list using the mapcar function: [2]> (mapcar #'square '(1 2 3 4 5)) (1 4 9 16 25)

List Functions We could also combine mapcar and lambda to create list functions: [3]> (defun listtimes (lst n) (mapcar #'(lambda (x) (* x n)) lst)) LISTTIMES Which can be called: [4]> (listtimes '(1 2 3 4 5) 3) (3 6 9 12 15)

List Functions Another list (applicative) function is find-if. Given a Boolean predicate and a list, find-if returns the first list element that satisfies the Boolean predicate: [1]> (find-if #'integerp '(a b c 1 2 3)) 1 [2]> (find-if #'(lambda (x) (> x 3)) '(1 2 3 4 5)) 4

List Functions We can also use find-if with our own named functions: [1]> (find-if #'is-prime '(20 21 22 23 24 25 26 27)) 23

More Applicative Functions The function remove-if eliminates values from a list that satisfy a Boolean predicate: [1]> (remove-if #'evenp '(1 2 3 4 5 6 7 8)) (1 3 5 7) Similar is the remove-if-not function: [2]> (remove-if-not #'evenp '(1 2 3 4 5 6 7 8)) (2 4 6 8)

More Applicative Functions Some applicative functions are not list-valued. One such function is reduce. The first argument to reduce must be a function that takes two arguments. The reduce function progressively applies this bivariate function to the list: [3]> (reduce #'+ '(1 2 3 4 5)) 15

More Applicative Functions Another applicative function is every. This returns T if every element of the list satisfies the predicate: [5]> (every #'numberp '(0 1 2 3 4)) T [6]> (every #'numberp '(O 1 2 3 4)) NIL That second zero was really an oh.

More on mapcar If we specify a bivariate function to mapcar, we can use it to operate on two lists in synchronisation: [7]> (mapcar #'* '(1 2 3 4) '(2 3 4 5)) (2 6 12 20)

Local Functions Remember one of our objections to the primes solution? We have a load of external functions that we really should not be able to call. Nesting defun s does not solve this problem. Any function defined by defun is global. There is a way to make functions local. Use labels in place of defun.

Local Functions As an example: [1]> (defun count-up (n) (labels ((r-count-up (cnt) (if (> cnt n) nil (cons cnt (r-count-up (+ cnt 1)))))) (r-count-up 1))) count-up [2]> (count-up 5) (1 2 3 4 5) The r-count-up function is only defined within count-up.

The labels Function The form of the labels function is: (labels ((fn-1 args-1 body-1)... (fn-n args-2 body-2)) body) where we define a series of named local functions fn-1 to fn-n which can be called within the function defined in body. The local functions can also call each other. They can also reference their parent s variables.

Some More I/O The format function allows the output of formatted output. The form of the function is: (format t "format-string" value-1... value-n) The format-string is a literal string which may include special character sequences. These escape sequences are preceded with the ~ character.

Escape Sequences for format Among the escape sequences for format are: ~% start a new line; ~& start a new line if not at start of line; ~s insert a value here; ~a insert a value without escape characters

Using format The following is an example of format in use: [1]> (defun test (x) (format t "~%With escapes: ~s" x) (format t "~&No escapes: ~a" x)) TEST [2]> (test "Hello World!") With escapes: "Hello World!" No escapes: Hello World! NIL Note that format evaluates to NIL.

The y-or-n-p function. You can ask a yes/no question with the y-or-n-p function: [1]> (defun riddle () (if (y-or-n-p "Do you know the nature of Zen?") (format t "Then do not ask!") (format t "You have found it!"))) RIDDLE [2]> (riddle) Do you know the nature of Zen? (y/n) yes Then do not ask! NIL [3]> (riddle) Do you know the nature of Zen? (y/n) N You have found it! NIL

Primes Again Here is a revised version of the primes program: (defun primes () ( labels ( (test-prime (cand div) (cond ((= cand div) t) (((lambda (x y) (integerp (/ x y))) cand div) nil) (t (test-prime cand (+ div 2))))) (next-prime (cand) (cond (((lambda (cand) (test-prime cand 3)) cand) cand) (t (next-prime (+ cand 2))))) (list-primes (limit l) (cond ((> (next-prime (+ (car l) 2)) limit) l) (t (list-primes limit (cons (next-prime (+ (car l) 2)) l)))))) (reverse (list-primes ((lambda (x) (print x) (read)) "Enter the upper limit for primes:") '(3 2)))))