Structure Programming in Lisp. Shared Structure. Tailp. Shared Structure. Top-Level List Structure

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

(defvar *state* nil "The current state: a list of conditions.")

Object oriented programming

A little bit of Lisp

A Genetic Algorithm Implementation

A Brief Introduction to Common Lisp

AllegroCache: an Introduction

Object Oriented Programming (OOP)

Modern Programming Languages. Lecture LISP Programming Language An Introduction

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

CSCE476/876 Fall Homework 3: Programming Assignment Using Emacs and Common Lisp. 1 Exercises (15 Points) 2. 2 Find (6 points) 4

Debugging in LISP. trace causes a trace to be printed for a function when it is called

Homework #2. Source code with description. Tzewen Wang ECE578 Winter 2005

Common Lisp. Blake McBride

Lisp. Versions of LISP

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

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

Department of Computer and information Science Norwegian University of Science and Technology

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

GPS: The general problem solver. developed in 1957 by Alan Newel and Herbert Simon. (H. Simon, 1957)

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

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

LP/LispLite: Trivial Lisp Org Mode Conversion

Common Lisp Object System Specification. 1. Programmer Interface Concepts

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

Recursion & Iteration

Common LISP Tutorial 1 (Basic)

Imperative, OO and Functional Languages A C program is

1 CLWEB INTRODUCTION 1

Lecture #2 Kenneth W. Flynn RPI CS

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM

Allegro CL Certification Program

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

Lecture Notes on Lisp A Brief Introduction

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

COSI: Adding Constraints to the object-oriented paradigm

Common LISP-Introduction


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

Sample Final Exam Questions

Heap storage. Dynamic allocation and stacks are generally incompatible.

2. Reasons for implementing clos-unit

Lists in Lisp and Scheme

Functional programming with Common Lisp

CMSC Introduction to Algorithms Spring 2012 Lecture 7

Artificial Intelligence Programming

Using a waiting protocol to separate concerns in the mutual exclusion problem

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Streams and Lazy Evaluation in Lisp

Associative Database Managment

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Associative Database Managment WIlensky Chapter 22

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

Linked Structures. See Section 3.2 of the text.

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

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

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

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

Announcements. Today s Menu

John McCarthy IBM 704

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

(defmacro while (condition &body body) `(iterate loop () (if,condition (loop)))))

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

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

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

CSCI337 Organisation of Programming Languages LISP

19 Machine Learning in Lisp

1. Problem Representation

Structure and Interpretation of Computer Programs

Linked Lists and Abstract Data Structures A brief comparison

MIDTERM EXAMINATION - CS130 - Spring 2005

Custom Specializers in Object-Oriented Lisp

NST: A Unit Test Framework for Common Lisp

CS 314 Principles of Programming Languages

6.001 Notes: Section 31.1

Meet the Macro. a quick introduction to Lisp macros. Patrick Stein / TC Lisp Users Group /

INF4820. Common Lisp: Closures and Macros

This should prevent residual sexism, racism, favoritism lurking in the unconscious of your professor & TA from biasing grading!!

Lisp Basic Example Test Questions

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Documentation for LISP in BASIC

Implementing Symmetric Multiprocessing in LispWorks

Introduction to Lisp

Midterm Examination (Sample Solutions), Cmput 325

.:: UNIT 4 ::. STACK AND QUEUE

CSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10

A Small Interpreted Language

CMPUT325 Extensions to Pure Lisp. Extensions to Pure Lisp. Bob Price and Russ Greiner. 5th October 2004

CS 314 Principles of Programming Languages. Lecture 16

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

Tail Recursion and Accumulators

6.001 Notes: Section 8.1

Summer Final Exam Review Session August 5, 2009

Linked Lists, Stacks, and Queues

SCHEME AND CALCULATOR 5b

AllegroCache. Reference Manual. Franz Inc. version 3.1.2

Structure and Interpretation of Computer Programs

Data Structure. Recitation VII

Allegro CL Certification Program

Transcription:

Structure 66-2210-01 Programming in Lisp Lecture 6 - Structure; ase Study: locks World Lisp's use of pointers Let you put any value anywhere Details are taken care of by the Lisp interpreter What goes on "under the hood"? It's useful to know this sometimes Some functions let you get down to low level details of pointers Alok Mehta - Programming in Lisp - Lecture 6 1 Alok Mehta - Programming in Lisp - Lecture 6 2 Shared Structure Lists can share conses in common > (setf part (list 'b 'c)) > (setf whole (cons 'a part)) (A ) > (tailp part whole) T WHOLE PART A Tailp Definition of tailp (tailp object list) returns T if object is a tail of list Example implementation > (defun our-tailp (x y) (or (eql x y) (and (consp y) (our-tailp x (cdr y))))) An object is a tail of itself (base case) NIL is a tail of every proper list Recursively take cdr's of the list, until you test for (eql NIL NIL) Alok Mehta - Programming in Lisp - Lecture 6 3 Alok Mehta - Programming in Lisp - Lecture 6 4 Shared Structure Lists can share structure without either being a tail of the other > (setf part (list 'b 'c) whole1 (cons 1 part) whole2 (cons 2 part)) WHOLE1 PART Top-Level List Structure Sometimes want to treat data structure as a list Include only the conses that make up the list Don't recurse into conses that make up elements This is the top-level list structure Other times, want to treat data structure as a tree All conses are important and treated uniformly 1 WHOLE2 A D 2 Alok Mehta - Programming in Lisp - Lecture 6 5 Alok Mehta - Programming in Lisp - Lecture 6 6 1

opy-list vs. opy-tree opy-list vs. opy-tree (code) Original opy-list opy-tree A A D D Example implementation of copy-list > (defun our-copy-list (lst) (if (null lst) nil (cons (car lst) (our-copy-list (cdr lst))))) Example implementation of copy-tree > (defun our-copy-tree (lst) (if (atom tr) tr (cons (our-copy-tree (car tr)) (our-copy-tree (cdr tr))))) Lisp handles pointers automatically Then why do we care? ecause some Lisp functions can modify structures Alok Mehta - Programming in Lisp - Lecture 6 7 Alok Mehta - Programming in Lisp - Lecture 6 8 Setf revisited Operators > (setf whole (list 'a 'b 'c) tail (cdr whole)) > (setf (second tail) 'e) E > tail ( E) > whole (A E) WHOLE TAIL A Alok Mehta - Programming in Lisp - Lecture 6 9 Avoid modifying lists Operators like setf, pop, rplaca, If you need to (or want to) modify a list Make sure it's not shared Or, make sure the shared update works as expected Or, make changes to a copy of the list > (setf whole (list 'a 'b 'c) tail (cdr whole)) > (setf tail (cons (first tail) (cons 'e (rest (rest tail))))) > tail > whole (A E) Alok Mehta - Programming in Lisp - Lecture 6 10 Parameter passing Parameters are passed by value The value is copied into the function If the value is a list The entire list is not copied The reference to the list is copied A function can permanently alter a list passed in as a parameter! Similar to parameter passing in Java an cause unintentional errors ut, can also be useful Queues Queue data structure First in, First out ompare to stacks (last in, first out) Stacks are easy in Lisp Insert (push) / Retrieve (pop) happen at the same end of the list Queues are harder Insert (enqueue) / Retrieve (dequeue) happen at opposite ends Q1 A Alok Mehta - Programming in Lisp - Lecture 6 11 Alok Mehta - Programming in Lisp - Lecture 6 12 2

Sample implementation Implementation of Queue (Inefficient) > (defmacro dequeue (q) `(pop,q)) > (defmacro enqueue (o q) `(setf,q (append,q (cons,o nil)))) Implementation of Queue using LOS (Inefficient) > (defclass queue () ((front :accessor front :initform nil))) > (defmethod dequeue ((q queue)) (pop (front q))) > (defmethod enqueue (o (q queue) &aux (node (cons o nil))) (setf (front q) (append (front q) node))) Example usage > (setf a (make-instance 'queue)) > (enqueue 'a a) > (enqueue 'b a) > (dequeue a) Efficient Queue Implementation Efficient Implementation of Queue using LOS > (defclass queue () ((front :accessor front :initform nil) (back :accessor back :initform nil))) > (defmethod enqueue (o (q queue) &aux (node (cons o nil))) (if (eql (front q) nil) ; first one? (setf (front q) node (back q) node) (progn ; not first time (setf (cdr (back q)) node) (setf (back q) (cdr (back q)))) )) > (defmethod dequeue ((q queue)) (if (eql (cdr (front q)) nil) (setf back nil)) ;last one (pop (front q))) Alok Mehta - Programming in Lisp - Lecture 6 13 Alok Mehta - Programming in Lisp - Lecture 6 14 Destructive Functions Several functions update the lists passed to them Examples Delete (destructive version of remove) > (setf a '(a b a d a)) (A A D A) > (remove 'a a) ; Doesn't change A ( D) > (delete 'a A) ; hanges A ( D) Nconc (destructive version of append) > (defun our-nconc (x y) (if (consp x) (progn (setf (cdr (last x)) y) x) y)) ase Study: The locks World Rules There are three kinds of movable objects: bricks, wedges, balls. Robot has one hand. It can grasp any movable block that has nothing on top of it. Every block is either held by the hand or supported by exactly one brick or the table. No block can overhang from its support. Although a movable block can be moved to the top of a wedge or a ball, neither wedges nor balls can support anything. Supporting bricks can support more than one block, as long as there is room. The table is wide enough for all of the blocks to fit on it at once. Alok Mehta - Programming in Lisp - Lecture 6 15 Alok Mehta - Programming in Lisp - Lecture 6 16 ase Study: The locks World lass Hierarchy Several moves are required to put block 1 on block 2 Sample path Move W7; Move 4; Move 1 onto 2 Load-bearing-block asic-block Movable-block Hand Π <=== Robotic Hand 4 1 W7 2 3 W5 6 L8 Table rick Wedge all Table Alok Mehta - Programming in Lisp - Lecture 6 17 Alok Mehta - Programming in Lisp - Lecture 6 18 3

lass Definitions lass Definitions (cont.) asic-lock > (defclass basic-block() ((name :accessor block-name :initarg :name) (width :accessor block-width :initarg :width) (height :accessor block-height :initarg :height) (position :accessor block-position :initarg :position) (supported-by :accessor block-supported-by :initform nil))) Supported-by => What the block is supported by (what's underneath it) Movable-block > (defclass movable-block (basic-block) ()) Load-bearing-block Has new field > (defclass load-bearing-block (basic-block) ((support-for :accessor block-support-for :initform nil))) Support-for => What the block is a support for (what's on top of it) Alok Mehta - Programming in Lisp - Lecture 6 19 rick, wedge, ball, table > (defclass brick (movable-block load-bearing-block) ()) > (defclass wedge (movable-block) ()) > (defclass ball (movable-block) ()) Table > (defclass table (load-bearing-block) ()) Robotic Hand > (defclass hand () ((name :accessor hand-name :initarg :name) (position :accessor hand-position :initarg :position) (grasping :accessor hand-grasping :initform nil))) Alok Mehta - Programming in Lisp - Lecture 6 20 reating locks in locks World (defvar *blocks* (list (make-instance 'table :name 'table :width 20 :height 0 :position '(0 0)) (make-instance 'brick :name 'b1 :width 2 :height 2 :position '(0 0)) (make-instance 'brick :name 'b2 :width 2 :height 2 :position '(2 0)) (make-instance 'brick :name 'b3 :width 4 :height 4 :position '(4 0)) (make-instance 'brick :name 'b4 :width 2 :height 2 :position '(8 0)) (make-instance 'wedge :name 'w5 :width 2 :height 4 :position '(10 0)) (make-instance 'brick :name 'b6 :width 4 :height 2 :position '(12 0)) (make-instance 'wedge :name 'w7 :width 2 :height 2 :position '(16 0)) (make-instance 'ball :name 'L8 :width 2 :height 2 :position '(18 0)) )) (defvar *hand* (make-instance 'hand :name '*hand* :position '(0 6))) Π 1 2 3 4 Table W5 6 Alok Mehta - Programming in Lisp - Lecture 6 21 W7 L8 Initializing locks World reate other global variables for convenience > (dolist (l *blocks*) (set (block-name l) l)) This sets the global variables TALE, 1, 2, W7, L8 to their respective block All blocks rest on the table initially > (dolist (l (rest *blocks*)) ; For each, except table (setf (block-supported-by l) table) (push l (block-support-for table))) Load-bearing-block has a method block-support-for This was automatically generated reate a dummy stub for this method in basic-block > (defmethod block-support-for ((object basic-block)) nil) y default, basic-blocks do not have anything on top of them. Only Load-bearingblocks may have something on top of them. Alok Mehta - Programming in Lisp - Lecture 6 22 lock-support-for Put-On Returns Nil Returns value of Slot Support-For Load-bearing-block lock-support-for asic-block lock-support-for Movable-block Table rick Wedge all Hand Want a method, PUT-ON, that places one object on another Get space for the object (may have to move things around) Grasp object (may have to remove things on top of the object) Move object Ungrasp object asic Prototype > (defmethod put-on ((object movable-block) ) Alok Mehta - Programming in Lisp - Lecture 6 23 Alok Mehta - Programming in Lisp - Lecture 6 24 4

Put-On Implementation > (defmethod put-on ((object movable-block) (if (get-space object support) (and (grasp object) (move object support) (ungrasp object)) (format t "~&ouldn't get space to put ~a on ~a." (block-name object) (block-name support)))) get-space, grasp, move, ungrasp have yet to be defined Get-space either finds space or makes space > (defmethod get-space ((object movable-block) (or (find-space object support) (make-space object support))) find-space, make-space have yet to be defined (do this later) Alok Mehta - Programming in Lisp - Lecture 6 25 Grasp Grasp Puts desired object in robot's hand > (defmethod grasp ((object movable-block)) (unless (eq (hand-grasping *hand*) object) ; already holding? ; Make sure nothing else is on top of object (when (block-support-for object) (clear-top object)) ; Make sure robot isn't holding anything else (when (hand-grasping *hand*) (get-rid-of (hand-grasping *hand*))) (format t "~&Move hand to pick up ~a at location ~a." (block-name object) (top-location object)) (setf (hand-position *hand*) (top-location object)) (format t "~&Grasp ~a." (block-name object)) (setf (hand-grasping *hand*) object)) t) Need to define: lear-top, top-location Function returns T if successful Alok Mehta - Programming in Lisp - Lecture 6 26 Ungrasp Ungrasp Releases object, if object is being supported by something else > (defmethod ungrasp ((object movable-block)) (when (block-supported-by object) (format t "~&Ungrasping ~a" (block-name object)) (setf (hand-grasping *hand*) nil) T)) Get-rid-of puts object on the table (out of the way) > (defmethod get-rid-of ((object movable-block)) (put-on object table)) Make-space lear-top Gets rid of everything on top of an object > (defmethod clear-top ((support load-bearing-block)) (dolist (obstacle (block-support-for support) t) (get-rid-of obstacle))) Make-space lears away just enough room to put block Algorithm keeps getting rid of things on top of block Until the find-space function returns that there is enough space available > (defmethod make-space ((object movable-block) (dolist (obstruction (block-support-for support)) (get-rid-of obstruction) (let ((space (find-space object support))) (when space (return space))))) Alok Mehta - Programming in Lisp - Lecture 6 27 Alok Mehta - Programming in Lisp - Lecture 6 28 Move Moves an object on top of a support > (defmethod move ((object movable-block) (remove-support object) (let ((newplace (get-space object support))) (format t "~&Move ~a to top of ~a at location ~a." (block-name object) (block-name support) newplace) (setf (block-position object) newplace) (setf (hand-position *hand*) (top-location object))) (add-support object support) t) alls remove-support, add-support These are methods for bookkeeping They maintain the bi-directional links (support-for, supported-by) Remove-support removes the bi-directional links of an object Add-support adds bi-directional links for an object that is to be placed on top of a support Remove-support Remove-support This is a bookkeeping method that removes bi-directional links > (defmethod remove-support ((object movable-block)) (let ((support (block-supported-by object))) (when support (setf (block-support-for support) (remove object (block-support-for support))) (setf (block-supported-by object) nil) t))) Alok Mehta - Programming in Lisp - Lecture 6 29 Alok Mehta - Programming in Lisp - Lecture 6 30 5

Add-support Adding support, for general case This is just a stub (does no operation) an't really put an object on top of any basic-block > (defmethod add-support ((object movable-block) t) Adding support, for specific cases For load-bearing blocks, we can put an object on top ookkeeping needed for this is to update bi-directional pointers > (defmethod add-support ((object movable-block) (support load-bearing-block)) (push object (block-support-for support)) (setf (block-supported-by object support))) Top-location Returns the location of the top (center) of a block Example Usage > (block-position b3) (4 0) <-- Lower left position of block > (block-width b3) 4 > (block-height b3) 4 > (top-location b3) (6 4) <-- X = Pos.X + (width/2.0); Y = Pos.Y Implementation > (defmethod top-location ((object basic-block)) (list (+ (first (block-position object)) (/ (block-width object) 2)) (+ (second (block-position object)) (block-height object)))) Alok Mehta - Programming in Lisp - Lecture 6 31 Alok Mehta - Programming in Lisp - Lecture 6 32 Find-space Find-space asic algorithm 4 6 For each possible location on top of support that the object can be placed, Is the position occupied? If not, we've found the space; else continue > (defmethod find-space ((object basic-block) (dotimes (offset (+ 1 (- (block-width support) (block-width object)))) (unless (intersections-p object offset (first (block-position support)) (block-support-for support)) (return (list (+ offset (first (block-position support))) (+ (second (block-position support)) (block-height support))))))) Intersections-p is to be defined next 4 6 Intersections-p Intersections-p hecks for intersections (only checks the X dimension) > (defun intersections-p (object offset base obstacles) (dolist (obstacle obstacles) (let* ((ls_proposed (+ offset base)) (rs_proposed (+ ls_proposed (block-width object))) (ls_obstacle (first (block-position obstacle))) (rs_obstacle (+ ls_obstacle (block-width obstacle)))) (unless (or (>= ls_proposed rs_obstacle) (<= rs_proposed ls_obstacle)) (return t))))) Obstacle Proposed Object Location Alok Mehta - Programming in Lisp - Lecture 6 33 Alok Mehta - Programming in Lisp - Lecture 6 34 locks World Usage Sample usage of blocks world > (put-on b4 b1) > (put-on w7 b2) > (put-on b1 b2) Final Exam Next time Open book, open notes No calculators, computers, etc. No lisp interpreter! Mostly programming type questions Write a program to Exam may contain material from hapters 1-12, plus case studies: Expert Systems, locks World Anything from lecture notes Alok Mehta - Programming in Lisp - Lecture 6 35 Alok Mehta - Programming in Lisp - Lecture 6 36 6