Lists CSC 358/458 4.3.2006. Outline Lab #1 / Homework #1 Lists A question List Internals of Lists List operations Extended Example.

Slides:



Advertisements
Similar presentations
CS 63 LISP Philip Greenspun's Tenth* Rule of Programming:
Advertisements

ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Functions Robin Burke CSC 358/
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.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
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)
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
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)
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
Introductory Lisp Programming Lecture # 2 Main Topics –Basic Lisp data types –Lisp primitives –Details of list handling Cons cells (boxes) & their representation.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
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.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
CSE 341, S. Tanimoto Lisp Data Structures - 1 Data Structures in Lisp 0. Collections of associations, association lists. 1. Creating graphs with conses.
Lisp by Namtap Tapchareon Lisp Background  Lisp was developed by John McCarthy in  Lisp is derives from List Processing Language. 
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.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Advanced Functions In CL, functions are often supplied as parameters to other functions –This gives us tremendous flexibility in writing functions whose.
Functional Programming 02 Lists
Alok Mehta - Programming in Lisp - Data Abstraction and Mapping Programming in Lisp Data Abstraction and Mapping.
PRACTICAL COMMON LISP Peter Seibel 1.
PRACTICAL COMMON LISP Peter Seibel 1.
Mitthögskolan 10/8/ Common Lisp LISTS. Mitthögskolan 10/8/2015 2Lists n Lists are one of the fundamental data structures in Lisp. n However, it.
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.
For Monday Read Chapter 3 Homework: –Lisp handout 2.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Lecture 2-1CS250: Intro to AI/Lisp Intelligent Agents Lecture 3-2 October 14 th, 1999 CS250.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
The Loop Macro Many of the CL “functions” are actually macros (let, progn, if, etc) The most complicated macro in CL is probably the Loop macro –The Loop.
COP4020 Programming Languages Functional Programming Prof. Xin Yuan.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Variables, Values, Atoms, Lists Variables in Lisp differ from other languages –They are not declared by type their type is determined at run-time, and.
PRACTICAL COMMON LISP Peter Seibel 1.
Control in LISP More on Predicates & Conditionals.
Operating on Lists Chapter 6. Firsts and Seconds n Transforming list of pairs into two lists –(firsts ‘((1 5) (2 6) (3 7)))  (1 2 3) –(seconds ‘((1 5)
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.
Basic Introduction to Lisp
Control Structures CSC 358/ Outline Midterm Lab #3 Homework #4 Sequential structures Conditional structures Unconditional branching Iteration.
Ch Ch jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (n-n-n-notes) Summer 2003 Dr. Carter Tiernan.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Functions CSC 358/
Section 15.4, 15.6 plus other materials
Intelligent Agents Lecture 3-2 October 14th, 1999 CS250 Lecture 2-1
Edited by Original material by Eric Grimson
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
LISP A brief overview.
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
Imperative Data Structures
Modern Programming Languages Lecture 21 Fakhar Lodhi
Data abstraction, revisited
Modern Programming Languages Lecture 20 Fakhar Lodhi
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Abstraction and Repetition
Common Lisp II.
More Scheme CS 331.
LISP primitives on sequences
Lists in Lisp and Scheme
Presentation transcript:

Lists CSC 358/

Outline Lab #1 / Homework #1 Lists A question List Internals of Lists List operations Extended Example

Lab #1 (defun add-car (lst1 lst2) (+ (car lst1) (car lst2))) (defun deal-hand (size deck) (let ((hand '())) (dotimes (i size) (push (pop deck) hand)) hand)) (defun count-face-cards (hand) (let ((counter 0)) (dolist (card hand) (if (face-cardp card) (incf counter))) counter)) (defun face-cardp (card) (not (numberp (card-rank card))))

Lab #1 (Extra credit) (defun average-face-cards (trials size) (let ((deck (make-deck)) (count 0)) (dotimes (k trials) (setf deck (shuffle-deck deck)) (incf count (count-face-cards (deal-hand size deck)))) (/ (float count) trials)))

Homework #1 ;; Cheating version (using case) (defun card-blackp (card) (case (card-suit card) ((H D) nil) ((S C) t))) ;; Non-cheating version (using cond) (defun card-blackp (card) (let ((suit (card-suit card))) (cond ((or (eq suit 'H) (eq suit 'D)) nil) (t t)))) ;; Functional version with boolean return value (defun card-blackp (card) (let ((suit (card-suit card))) (or (eq suit 'S) (eq suit 'C))))

Homework #1 (defun not-twenty-onep (card1 card2) (let ((rank1 (card-rank card1)) (rank2 (card-rank card2))) (if (and (= rank1 1) (= rank2 1)) ;; special case 12 (let ((value1 (card-points-bj rank1)) (value2 (card-points-bj rank2))) (let ((value-sum (+ value1 value2))) (if (= value-sum 21) nil value-sum)))))) (defun card-points-bj (rank) (case rank ((k q j) 10) (1 11) (otherwise rank)))

Homework #1 (defun card-points-skat (rank) (case rank (1 11) (10 10) (k 4) (q 3) (j 2) (otherwise 0))) (defun skat-trick (trick) (let ((score 0)) (dolist (card trick) (incf score (card-points-skat (card-rank card)))) score))

Homework #1 (XC) (defun can-buildp (hand center) (dolist (hand-card hand) (dolist (center-card center) (if (can-build-cards hand-card center-card hand) (return-from can-buildp (list hand-card center-card))))))) (defun can-build-cards (hand-card center-card hand) (let ((hand-value (card-points-cassino (card-rank hand-card))) (center-value (card-points-cassino (card-rank center-card)))) (let ((build-value (+ hand-value center-value))) (dolist (card hand) (if (= build-value (card-points-cassino (card-rank card))) (return-from can-build-cards t)))))) (defun card-points-cassino (rank) (case rank (k 13) (q 12) (j 11) (otherwise rank)))

Homework #1 (defun can-buildp (hand center) (let ((ans nil)) (dolist (hand-card hand) (dolist (center-card center) (if (can-build-cards hand-card center-card hand) (setf ans (list hand-card center-card))))) ans))

Last week How to deal with card games with different point values? One possibility lots of named functions ick Better approach be data-driven let the functions be defined by the data Problem don't want an extra argument to a comparison operator suppose I want to supply the comparison to a sort function?

Lisp solution Create an anonymous function using the data use this function for comparing Benefits can create as many as needed symbol table not filled with unnecessary stuff

card-comparator (defvar *default-card-values* '((K 13) (Q 12) (J 11))) (defvar *ace-high-values* '((1 14) (K 13) (Q 12) (J 11))) (defvar *skat-card-values* '((1 14) (10 13) (K 12) (Q 11) (J 10))) (defun rank-to-number2 (rank card-values) (let ((value-pair (assoc rank card-values))) (if value-pair (cadr value-pair) rank))) (defun card-comparator (&optional (card-values *default-card- values*)) #'(lambda (card1 card2) (let ((rank1 (card-rank card1)) (rank2 (card-rank card2))) (< (rank-to-number2 rank1 card-values) (rank-to-number2 rank2 card-values)))))

Some syntax: lambda lambda a lot more about this next week this is how we define an anonymous function defun is just a convenience (setf (function foo) #'(lambda (x y) (+ x y))) the same as (defun foo (x y) (+ x y)) lambda is fundamental

Optional arguments More about this next week I can specify in the parameter list that some arguments are optional and then supply default values Optional arguments must be at the end for obvious reasons

Closure Note the function I define using lambda refers to a parameter defined in the enclosing scope card-values the function is returned to the caller the enclosing scope disappears can I do this? Yes! technical term = "lexical closure" more about this next week

Lists

A Question Why can’t I really deal from my deck? Why does this function not change the value of its argument? (defun mypop (lst) (pop lst)) > (setf l1 '(a b c)) > (mypop l1) A > l1 (A B C)

Lists sequences of items atoms or lists car first element cdr rest cons builds a list

Other List Builders list a list containing the arguments append a list combining the arguments

Internals (a b c)

Nested List

Improper List

What Does It Do?* (setf l1 '(a (b c))) (setf l2 '((d) e)) (car l2) (cdr l1) (cons 'b l1) (list l2 'd) (append l1 l2)

What does it do? (pop l1) special form short for (setf l1 (cdr l1)) (defun mypop (lst) (pop lst)) (defun my pop (lst) (setf lst (cdr lst))) (mypop l1) l1 doesn't change why should it? it is still bound to the same thing

How can we achieve this? Global variable ick Game state structure pass in and out contents manipulated better

Example: Blackjack (defun make-bj-game (player-count) (list (shuffle-deck (make-deck)) (make-list player-count :initial-element nil))) (defun player-count (game) (length (hands game))) (defun deck (game) (cadr game)) (defun hands (game) (caddr game)) (defun hand (player game) (nth player (hands game)))

New function make-list note the function call :initial-element keyword argument we'll see this again later

Shared Structure It is easy to create lists that share structure (setf c (append a b)) Not a problem unless a or b is destructively modified

List Functions Accessors navigating around in lists Operations manipulate the whole list Destructive operations modify the list

List Accessors car, cdr positional first, second, third (nth i lst) (nthcdr i lst) end of the list last actually returns last cdr

List Operations Many! Mapping functions Boolean operations Finding Modifying (copy) Reduce

Mapping Functions that apply a function over and over across a list (mapcar #’fn lst) applies the function to each element in the list returns a list of the results Also works with multiple lists (mapcar #’fn lst1 lst2)

Example Matt's question What if I want to add 5 to everything in a list? (mapcar #'(lambda (x) (+ x 5)) '(1 2 3))

Other Mapping Functions maplist applies to successive cdrs mapcan joins results with append mapc, mapl like mapcar and maplist but doesn't return results

Boolean Operations logical summary of a list relative to a function (some #’fn lst) true if any element of lst returns true when the function is applied every false if any element returns false notany notevery

Example flushp is a poker hand a flush? 5-card hand, please logic all cards the same suit simple method all spades or all clubs or... better way?

Finding Operations (member elem lst) if elem is in list, returns the cdr headed by elem (position elem lst) if elem is in list, return position index both return nil is absent

Modifications (remove elem lst) returns a copy of lst with elem removed not “destructive” Also "if" version remove-if has a test instead of an element (substitute old new lst) returns a copy of lst with old replaced by new

Reduce “reduce” list into a single value (reduce #’fn lst) applies fn to first two elements applies fn to that result and next element etc. (reduce #’+ ‘( )) => 10

Example count-face-cards mapcar and reduce Original version (defun count-face-cards (hand) (let ((counter 0)) (dolist (card hand) (if (face-cardp card) (incf counter))) counter)) (defun face-cardp (card) (not (numberp (card-rank card))))

Destructive Operations I Most Lisp operations return “new” lists remove (setf lst ‘(b a b a b)) (remove ‘a lst) => (b b b) lst => (b a b a b) Use the result of the function New cons cells created not always what you want

Destructive Operations II Alter the contents of cons cells rplaca = replace the car rplacd = replace the cdr nconc = destructive append delete = destructive remove nsubst = destructive subst Others “n” means “non-consing”

Generalized Variables setf can be similarly used (setf (car lst) val) (setf (cdr lst) val) Main reason to use efficiency creating new cons cells creating garbage

Problems with Destructive Operations Shared structure Effects hard to predict Not necessary Main reason to use efficiency but remember Knuth “Premature optimization is the root of all evil.”

Example Look at deck after shuffle-deck

defsetf One principle of Lisp is that the programmer has the same power as the language designer You can create your own generalized variables use defsetf

Example (defun 3rd (lst) (nth 2 lst)) (defun set-3rd (lst value) (setf (nth 2 lst) value)) (defsetf 3rd set-3rd) (setf lst '( a b c d)) (setf (3rd lst) 'q) lst => (a b q d) (setf (3rd lst))

Association List Allows lookup of values associated with keys ((key1. val1) (key2. val2)... (keyn. valn)) OK for short associations large associations a hash table is better (assoc key alist) returns the pair (rassoc val alist) returns the pair

Keyword parameters what if the value is not an atom? (rassoc '(21 M) '((John 21 M) (Jane 19 F) (Joe 25 M))) doesn’t work because rassoc uses eq extra arguments to rassoc :test specifies which function to use instead of default (rassoc '(21 M) '((John 21 M) (Jane 19 F) (Joe 25 M)) :test #'equal)

Keyword Parameters Many functions have these Most common :test :key specifies a function to apply before testing (rassoc '21 '((John 21 M) (Jane 19 F) (Joe 25 M)) :key #'car) :start :end

Equality Operators = numerical equality only eq reference equality eql eq numbers and characters equal tests lists element by element can be expensive! Which one to use? if you know your data type, be specific (equal for lists, = for numbers, eql for everything else) if you really want reference equality, use eq

Defining Keyword Parameters (defun foo (a b &key c (d 5))...) 5 is the default value for d can be called (foo 1 2) (foo 1 2 :c 1 :d 3)

Example sorting hands by rank by suit allow different possibilities (sort-hand hand :test...)

Sequences Many of the list function also work on vectors lisp 1-D arrays The data type that covers both lists and vectors is called the "sequence" functions that take a sequence as an argument will operate on either

Extended Example blackjack