General pattern for selecting some elements of a list This negatives example illustrates a general pattern: If you want a function which selects some elements.

Slides:



Advertisements
Similar presentations
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Advertisements

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.
Writing LISP functions. 2 COND Rule 1: Unless the function is extremely simple, begin with a COND If you can write the function body in one line, do it.
Some non-recursive tricks. The Lambda expression. More on Let, Let*, apply and funcall.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
Lisp II. How EQUAL could be defined (defun equal (x y) ; this is how equal could be defined (cond ((numberp x) (= x y)) ((atom x) (eq x y)) ((atom y)
1 Programming Languages and Paradigms Lisp Programming.
Lisp II. How EQUAL could be defined (defun equal (x y) ; this is how equal could be defined (cond ((numberp x) (= x y)) ((atom x) (eq x y)) ((atom y)
מבוא מורחב 1 Lecture #7. מבוא מורחב 2 The rational number abstraction Wishful thinking: (make-rat ) Creates a rational number (numer ) Returns the numerator.
Tricks.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages It’s elegant, minimal, can be.
Helper functions: when extra arguments are needed Consider this problem: we want a function index_items that takes a list L and gives a number to each.
A function (negatives L) that takes a list of numbers L and returns a list containing only negative numbers from L. A recursive example to remind you (defun.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
(cons ) (defun pair_elements (A B) ) (cond ( (or (null A) (null B) ) ‘() ) ( t ) (list ) Pairing elements in two lists >(pair_elements ‘(jack bonnie romeo)
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
Common Lisp! John Paxton Montana State University Summer 2003.
Imperative programming public int factorial (int N){ int F = 1; for(X=N; X>1; X-- ){ F= F*X; } return F; } Functional programming (defun factorial(N) (cond.
Data Abstraction… The truth comes out…. What we’re doing today… Abstraction ADT: Dotted Pair ADT: List Box and Pointer List Recursion Deep List Recursion.
>(setf oldlist ) Constructing a list We know how to make a list in lisp; we simply write it: ‘4321( ) What if we want a new list with that list as a part?
CS 330 Programming Languages 11 / 20 / 2007 Instructor: Michael Eckmann.
CS 330 Programming Languages 11 / 18 / 2008 Instructor: Michael Eckmann.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester, 2010
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Spring 2008Programming Development Techniques 1 Topic 6 Hierarchical Data and the Closure Property Section September 2008.
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
Functional Programming 02 Lists
PRACTICAL COMMON LISP Peter Seibel 1.
1 Lists in Lisp and Scheme. 2 Lists are Lisp’s fundamental data structures. Lists are Lisp’s fundamental data structures. However, it is not the only.
Basic Lisp CIS 479/579 Bruce R. Maxim UM-Dearborn.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
Basic LISP Programming Common LISP follows the algorithm below when interacting with users: loop read in an expression from the console; evaluate the expression;
Function Design in LISP. Program Files n LISP programs are plain text –DOS extensions vary; use.lsp for this course n (load “filename.lsp”) n Can use.
Lisp Functional Language or Applicative Language –Achieves its effect by applying functions, either recursively or through composition Powerful, expressive,
Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
You can access the members of a list with the functions car (or first) and cdr (or rest): (setf list '(a b c)) (car list) ⇒ a (first list) ⇒ a (cdr list)
Recursive Data Structures and Grammars  Themes  Recursive Description of Data Structures  Recursive Definitions of Properties of Data Structures  Recursive.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Functional Programming: Lisp MacLennan Chapter 10.
CS 330 Programming Languages 11 / 28 / 2006 Instructor: Michael Eckmann.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Section 15.4, 15.6 plus other materials
Tail Recursion.
CS 550 Programming Languages Jeremy Johnson
Modern Programming Languages Lecture 20 Fakhar Lodhi
Racket CSC270 Pepper major portions credited to
Lists in Lisp and Scheme
CS 270 Math Foundations of CS Jeremy Johnson
6.001 SICP Data abstractions
Writing LISP functions
J.E. Spragg Mitthögskolan 1997
Lisp Tutorial Click on Xlisp icon – you enter the interpreter
Lecture #8 מבוא מורחב.
Modern Programming Languages Lecture 20 Fakhar Lodhi
topics mutable data structures
Lecture #7 מבוא מורחב.
List and list operations (continue).
Defining Functions with DEFUN
Abstraction and Repetition
Today’s topics Abstractions Procedural Data
Functional Programming: Lisp
Lecture # , , , , מבוא מורחב.
Lisp.
Lists in Lisp and Scheme
Presentation transcript:

general pattern for selecting some elements of a list This negatives example illustrates a general pattern: If you want a function which selects some elements from a list and drops others, you need a recursive function with two recursive conditions. (defun negatives(L) (cond ( (null L) ‘() ) ( (< (first L) 0 ) (cons (first L) (negatives (rest L))) ) ( t (negatives (rest L)) ) )) One recursive condition conses the current first element to the answer that’s being built up, because it matches the criterion The other recursive condition simply returns the answer built up for the rest of the list, “ignoring” the current first element

Under the bonnet:Cons makes “cons cells” The list ‘(doe ray mee) is really a chain of cons cells ending in a rest field with a nil Lists are implemented as building blocks called cons cells A cons cell is a data structure with two fields: a first field and a rest field The first field contains a pointer to the first element of the list. The rest field points to the next cons cell in the list

Representing embedded lists A lists with lists inside it: ‘((karl lewis) is a (runner))

Dotted pairs Proper lists end in Nil but you can have lists which have another atom in the rest location. > (cons ‘sonya ‘o-sullivan) These will print out as “dotted pairs”. (sonya.o-sullivan)

first or CAR, rest or CDR > (setf letters '(a (b (c)))) (A (B (C))) > (caadr letters) B > (first (first (rest letters))) B Generally, except when we benefit from using one of these compound expressions, we will stick to FIRST and REST In the early days of Lisp, people used car (pronounced "CAR") and cdr ("could-a") instead of first and rest. The only advantage car and cdr have is that you can combine them in a single function name; for example (cadr L) means (car (cdr L)); same as (first (rest L)) (cddr L) means (cdr (cdr L)); same as (rest (rest L))

Operations on lists: Append >(cons ‘( 1 2 3) ‘(4 5 6) ) ( (1 2 3) 4 5 6) Cons takes an element (atom or list) and a list and puts the element first in a new list with the list argument as the rest. Append takes two lists (has to be two lists) and joins them together making a single list. >(append ‘( 1 2 3) ‘(4 5 6) ) ( ) Append is a built-in function, like member. We can write append recursively, using cons. Lets see how.

Append as a recursive design example Append is a function that joins two lists together. Append takes two lists as arguments: (append A B) We first need to figure out the stopping condition for append. We’ll focus on A in getting the stopping condition. (a b c) >(append ‘() ‘(a b c) ) If asked to append an empty list A to any other list B, we can simply return the other list B without doing anything else. Unlike cons, append is recursive. We ask: what is the simplest, smallest version of A so that, asked (append A B), we can return the correct answer straight away without having to do anything much? (null A) is our stopping condition.

Append: the recursive condition Append takes two lists (append A B) and joins them together We know the stopping condition is (null A). What is the recursive condition going to be like? We will also need to do something with the bit of A that we’ve “left out” in this recursive call. So the recursive condition will contain the call (append (rest A) B) We also know that the recursive call will not reduce the size of the list B (since the stopping condition tests only A, not B). Since the stopping condition is a test on A, we know that in the recursive condition we’re going to have to make the list A smaller on each recursive call (to eventually hit the stopping condition).

(defun append(A B) ) (if ) (cons )(null A) Suppose A is ‘(1 2 3), B is ‘(4 5 6) and we call (append A B) What will (append (rest A) B) return? Append: Combining the current element with the recursive answer We know that in executing (append A B) we will do the recursive call (append (rest A) B) (append ) (rest A)BB(first A) ‘( ) So what do we need to do to get the correct answer for (append A B)? We need to add the missing first element from A to the answer from (append (rest A) B). Code for Append (using if rather than cond for a change):

Try tracing the execution of append yourself (as in the factorial and countdown trace examples) Append is a built-in function in lisp, as are useful functions like member, replace, substitute etc. To understand recursion it’s good to know how they work.

(cond ( ) ) ( t )(append )(list ) Another recursive example: (reverse L) (defun reverse(L) ) (reverse ) (reverse ‘(a b c d)) returns ‘(d c b a). Stopping condition? Recursive call? Suppose L = ‘(a b c d). What will (reverse (rest L)) return? (null L) (rest L) ‘() (first L) L is empty (null L) (reverse (rest L)) (d c b). What do we need to do to ‘(d c b) to get ‘(d b c a)? (append ‘(d c b) (list ‘a)) will return ‘(d b c a)

One way to think about writing functions like these Specifying the stopping conditions in a recursive function is very important; but it is usually easy. It is harder to write the recursive conditions, especially to say how the answer from the recursive “smaller” call is combined with the “left-behind” part of the argument. One trick: Take an example list argument. Assume the recursive call returns the correct answer for the “rest” part of that list. Figure out how to put that answer together with the left-behind “first” part of the list, to get the overall answer. This “assume the smaller call is correct” approach is called induction.