Lists in Lisp and Scheme

Similar documents
Lists in Lisp and Scheme

CS201 Discussion 10 DRAWTREE + TRIES

COMP 423 lecture 11 Jan. 28, 2008

Section 3.1: Sequences and Series

Functor (1A) Young Won Lim 8/2/17

Functor (1A) Young Won Lim 10/5/17

Lecture Overview. Knowledge-based systems in Bioinformatics, 1MB602. Procedural abstraction. The sum procedure. Integration as a procedure

A Tautology Checker loosely related to Stålmarck s Algorithm by Martin Richards

Fig.25: the Role of LEX

box Boxes and Arrows 3 true 7.59 'X' An object is drawn as a box that contains its data members, for example:

George Boole. IT 3123 Hardware and Software Concepts. Switching Algebra. Boolean Functions. Boolean Functions. Truth Tables

10.5 Graphing Quadratic Functions

Suffix trees, suffix arrays, BWT

Basics of Logic Design Arithmetic Logic Unit (ALU)

1.1. Interval Notation and Set Notation Essential Question When is it convenient to use set-builder notation to represent a set of numbers?

Agenda & Reading. Class Exercise. COMPSCI 105 SS 2012 Principles of Computer Science. Arrays

COMPUTER SCIENCE 123. Foundations of Computer Science. 6. Tuples

In the last lecture, we discussed how valid tokens may be specified by regular expressions.

Information Retrieval and Organisation

Subtracting Fractions

Tries. Yufei Tao KAIST. April 9, Y. Tao, April 9, 2013 Tries

Lecture 10 Evolutionary Computation: Evolution strategies and genetic programming

MIPS I/O and Interrupt

2 Computing all Intersections of a Set of Segments Line Segment Intersection

Introduction to Integration

ΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών

Definition of Regular Expression

Unit #9 : Definite Integral Properties, Fundamental Theorem of Calculus

From Dependencies to Evaluation Strategies

Spring 2018 Midterm Exam 1 March 1, You may not use any books, notes, or electronic devices during this exam.

Very sad code. Abstraction, List, & Cons. CS61A Lecture 7. Happier Code. Goals. Constructors. Constructors 6/29/2011. Selectors.

CS412/413. Introduction to Compilers Tim Teitelbaum. Lecture 4: Lexical Analyzers 28 Jan 08

1 Quad-Edge Construction Operators

Quiz2 45mins. Personal Number: Problem 1. (20pts) Here is an Table of Perl Regular Ex

Mid-term exam. Scores. Fall term 2012 KAIST EE209 Programming Structures for EE. Thursday Oct 25, Student's name: Student ID:

CSCI 3130: Formal Languages and Automata Theory Lecture 12 The Chinese University of Hong Kong, Fall 2011

Fig.1. Let a source of monochromatic light be incident on a slit of finite width a, as shown in Fig. 1.

Section 10.4 Hyperbolas

Discussion 1 Recap. COP4600 Discussion 2 OS concepts, System call, and Assignment 1. Questions. Questions. Outline. Outline 10/24/2010

Reference types and their characteristics Class Definition Constructors and Object Creation Special objects: Strings and Arrays

4452 Mathematical Modeling Lecture 4: Lagrange Multipliers

COMBINATORIAL PATTERN MATCHING

Systems I. Logic Design I. Topics Digital logic Logic gates Simple combinational logic circuits

If you are at the university, either physically or via the VPN, you can download the chapters of this book as PDFs.

CS321 Languages and Compiler Design I. Winter 2012 Lecture 5

ΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών. Lecture 3b Lexical Analysis Elias Athanasopoulos

Simplifying Algebra. Simplifying Algebra. Curriculum Ready.

Reducing a DFA to a Minimal DFA

Compilers Spring 2013 PRACTICE Midterm Exam

this grammar generates the following language: Because this symbol will also be used in a later step, it receives the

INTRODUCTION TO SIMPLICIAL COMPLEXES

CS481: Bioinformatics Algorithms

L2-Python-Data-Structures

Fall 2017 Midterm Exam 1 October 19, You may not use any books, notes, or electronic devices during this exam.

Matrices and Systems of Equations

Angle Properties in Polygons. Part 1 Interior Angles

Intermediate Information Structures

Naming 3D objects. 1 Name the 3D objects labelled in these models. Use the word bank to help you.

MA1008. Calculus and Linear Algebra for Engineers. Course Notes for Section B. Stephen Wills. Department of Mathematics. University College Cork

6.2 Volumes of Revolution: The Disk Method

Today s Lecture. Basics of Logic Design: Boolean Algebra, Logic Gates. Recursive Example. Review: The C / C++ code. Recursive Example (Continued)

CS311H: Discrete Mathematics. Graph Theory IV. A Non-planar Graph. Regions of a Planar Graph. Euler s Formula. Instructor: Işıl Dillig

UT1553B BCRT True Dual-port Memory Interface

Small Business Networking

Symbol Table management

CPSC 213. Polymorphism. Introduction to Computer Systems. Readings for Next Two Lectures. Back to Procedure Calls

CMPUT101 Introduction to Computing - Summer 2002

12-B FRACTIONS AND DECIMALS

CIS 1068 Program Design and Abstraction Spring2015 Midterm Exam 1. Name SOLUTION

Small Business Networking

Small Business Networking

Small Business Networking

Pointers and Arrays. More Pointer Examples. Pointers CS 217

CS 241 Week 4 Tutorial Solutions

cisc1110 fall 2010 lecture VI.2 call by value function parameters another call by value example:

such that the S i cover S, or equivalently S

Dynamic Programming. Andreas Klappenecker. [partially based on slides by Prof. Welch] Monday, September 24, 2012

Network Interconnection: Bridging CS 571 Fall Kenneth L. Calvert All rights reserved

CS 340, Fall 2014 Dec 11 th /13 th Final Exam Note: in all questions, the special symbol ɛ (epsilon) is used to indicate the empty string.

1. SEQUENCES INVOLVING EXPONENTIAL GROWTH (GEOMETRIC SEQUENCES)

Midterm 2 Sample solution

Improper Integrals. October 4, 2017

EECS150 - Digital Design Lecture 23 - High-level Design and Optimization 3, Parallelism and Pipelining

a(e, x) = x. Diagrammatically, this is encoded as the following commutative diagrams / X

Summer Review Packet For Algebra 2 CP/Honors

CS143 Handout 07 Summer 2011 June 24 th, 2011 Written Set 1: Lexical Analysis

Grade 7/8 Math Circles Geometric Arithmetic October 31, 2012

Unit 5 Vocabulary. A function is a special relationship where each input has a single output.

6.3 Volumes. Just as area is always positive, so is volume and our attitudes towards finding it.

What are suffix trees?

SOME EXAMPLES OF SUBDIVISION OF SMALL CATEGORIES

The notation y = f(x) gives a way to denote specific values of a function. The value of f at a can be written as f( a ), read f of a.

Example: 2:1 Multiplexer

Outline. Tiling, formally. Expression tile as rule. Statement tiles as rules. Function calls. CS 412 Introduction to Compilers

P(r)dr = probability of generating a random number in the interval dr near r. For this probability idea to make sense we must have

The Math Learning Center PO Box 12929, Salem, Oregon Math Learning Center

Algorithm Design (5) Text Search

Math 464 Fall 2012 Notes on Marginal and Conditional Densities October 18, 2012

Graphing Conic Sections

Physics 152. Diffraction. Difrraction Gratings. Announcements. Friday, February 2, 2007

Transcription:

Lists in Lisp nd Scheme Lists in Lisp nd Scheme Lists re Lisp s fundmentl dt structures, ut there re others Arrys, chrcters, strings, etc. Common Lisp hs moved on from eing merely LISt Processor However, to understnd Lisp nd Scheme you must understnd lists common func?ons on them how to uild other useful dt structures with them Lisp Lists Lists in Lisp nd its descendnts re very simple linked lists Represented s liner chin of nodes Ech node hs (pointer to) vlue (cr of list) nd pointer to the next node (cdr of list) Lst node s cdr pointer is to null Lists re immutle in Scheme Typicl ccess phern is to trverse the list from its hed processing ech node In the eginning ws the cons (or pir) Wht cons relly does is comines two ojects into two- prt oject clled cons in Lisp nd pir in Scheme Conceptully, cons is pir of pointers - - the first is the cr, nd the second is the cdr Conses provide convenient represent?on for pirs of ny type The two hlves of cons cn point to ny kind of oject, including conses This is the mechnism for uilding lists (pir? (1 2) ) => #t null 1

Pirs Lists in Lisp nd Scheme re defined s pirs Any non empty list cn e considered s pir of the first element nd the rest of the list We use one hlf of cons cell to point to the first element of the list, nd the other to point to the rest of the list (which is either nother cons or nil) () ( c) Box nd pointer not:on A one element list () c A list of three elements ( c) null Common nottion: use digonl line in cdr prt of cons cell for pointer to null Z Wht sort of list is this? Pir? Z is list with three elements: (i) the tom, (ii) list of two elements, & c nd (iii) the tom d. c > (define Z (list (list c) d)) > Z ( ( c) d) > (cr (cdr z))?? d The func?on pir? returns true if its rgument is cons cell The equivlent func?on in CL is consp So list? could e defined: (define (list? x) (or (null? x) (pir? x))) Since everything tht is not pir is n tom, the predicte tom could e defined: (define (tom? x) (not (pir? x))) 2

Ech?me you cll cons, Scheme lloctes new cons cell from memory with room for two pointers If we cll cons twice with the sme rgs, we get two vlues tht look the sme, ut re dis?nct ojects Equlity (define L1 (cons ' null)) L1 (A) (define L2 (cons ' null))) L2 (A) (eq? L1 L2) #f (equl? L1 L2) #t (nd (eq? (cr L1)(cr L2)) (eq? (cdr L1)(cdr L2))) #t Equl? Do two lists hve the sme elements? Scheme provides predicte equl? tht is like Jv s equl method Eq? returns true iff its rguments re the sme oject, nd Equl?, more or less, returns true if its rguments would print the sme. > (equl? L1 L2) #t Note: (eq? x y) implies (equl? x y) Equl? (define (myequl? x y) ; this is ~ how equl? could e defined (cond ((numer? x) (= x y)) ((not (pir? x)) (eq? x y)) ((not (pir? y)) #f) ((myequl (cr x) (cr y)) (myequl? (cdr x) (cdr y))) (#t #f))) Use trce to see how it works > (require rcket/trce) > (trce myequl?) > (myequl? '( c) '( c)) >(myequl? ( c) ( c)) > (myequl? ) < #t >(myequl? ( c) ( c)) > (myequl? ) < #t >(myequl? (c) (c)) > (myequl? c c) < #t >(myequl? () ()) <#t Trce is deugging pckge showing wht rgs userdefined function is clled with nd wht it returns The require function lods the pckge if needed #t 3

Does Lisp hve pointers? Vriles point to their vlues A secret to understnding Lisp is to relize tht vriles hve vlues in the sme wy tht lists hve elements As pirs hve pointers to their elements, vriles hve pointers to their vlues Scheme mintins dt structure represen?ng the mpping of vriles to their current vlues. > (define x ( )) > x ( ) > (define y x) y ( ) environment VAR x y VALUE Vriles point to their vlues Does Scheme hve pointers? > (define x ( )) > x ( ) > (define y x) y ( ) > (set! y (1 2) > y (1 2) environment VAR x y VALUE 1 2 The loc?on in memory ssocited with the vrile x does not contin the list itself, ut pointer to it. When we ssign the sme vlue to y, Scheme copies the pointer, not the list. Therefore, wht would the vlue of > (eq? x y) e, #t or #f? 4

Length is simple func:on on Lists The uilt- in func?on length tkes list nd returns the numer of its top- level elements Here s how we could implement it (define (length L) (if (null? L) 0 (+ 1 (length (cdr L)))) As typicl in dynmiclly typed lnguges (e.g., Python), we do miniml type checking The underlying interpreter does it for us Get run-?me error if we pply length to non- list Building Lists list- copy tkes list nd returns copy of it The new list hs the sme elements, ut contined in new pirs > (set! x ( c)) ( c) > (set! y (list- copy x)) ( c) Spend few minutes to drw ox digrm of x nd y to show where the pointers point Copy- list List- copy is Lisp uilt- in (s copy- list) tht could e defined in Scheme s: (define (list- copy s) (if (pir? s) (cons (list- copy (cr s)) (list- copy (cdr s))) s)) Given non- tomic s- expression, it mkes nd returns complete copy (e.g., not just the top- level spine) ppend returns the concten?on of ny numer of lists Append copies its rguments except the lst If not, it would hve to modify the lists Such side effects re undesirle in func?onl lnguges Append >(ppend ( ) (c d)) ( c d) > (ppend (()()) (((c)))) (() () ((c))) > (ppend ( ) (c d) (e)) ( c d e) >(ppend ( ) ()) ( ) >(ppend ( )) ( ) >(ppend) () 5

Append The two rgument version of ppend could e defined like this (define (ppend2 s1 s2) (if (null? s1) s2 (cons (cr s1) (ppend2 (cdr s1) s2)))) No?ce how it ends up copying the top level list structure of its first rgument > (lod "ppend2.ss") > (define L1 '(1 2)) > (define L2 '( )) > (define L3 (ppend2 L1 L2)) > L3 (1 2 ) > L1 (1 2) > L2 ( ) Visulizing Append > (require rcket/trce) > (trce ppend2) > (ppend2 L1 L2) >(ppend2 (1 2) ( )) > (ppend2 (2) ( )) > >(ppend2 () ( )) < <( ) < (2 ) <(1 2 ) (1 2 ) Append does not modify its rguments. It mkes copies of ll of the lists sve the lst. > (lod "ppend2.ss") > (define L1 '(1 2)) > (define L2 '( )) > (define L3 (ppend2 L1 L2)) > L3 (1 2 ) > L1 (1 2) > L2 ( ) > (eq? (cdr (cdr L3) L2) #f Visulizing Append environment VAR L2 L1 L3 VALUE 1 2 Append2 copies the top level of its first list rgument, L1 List ccess func:ons To find the element t given posi?on in list use the func?on list- ref (nth in CL) > (list- ref ( c) 0) To find the nth cdr, use list- til (nthcdr in CL) > (list- til ( c) 2) (c) Both func?ons re zero indexed 6

> (define L '( c d)) > (list- ref L 2) c > (list- ref L 0) > (list- ref L - 1) list- ref: expects type <non- neg?ve exct integer> s 2nd rg, given: - 1; other rguments were: ( c d) > (list- ref L 4) list- ref: index 4 too lrge for list: ( c d) List- ref nd list- til > (list- til L 0) ( c d) > (list- til L 2) (c d) > (list- til L 4) () > (list- til L 5) list- til: index 5 too lrge for list: ( c d) Defining Scheme s list- ref & list- til (define (mylist- ref l n) (cond ((< n 0) (error...)) ((not (pir? l)) (error...)) ((= n 0) (cr l)) (#t (mylist- ref (cdr l) (- n 1))))) (define (mylist- til l n) (cond ((< n 0) (error...)) ((not (pir? l)) (error...)) ((= n 0) (cdr l)) (#t (mylist- ref (cdr l) (- n 1))))) Accessing lists Scheme s lst returns the lst element in list > (define (lst l) (if (null? (cdr l)) (cr l) (lst (cdr l)))) (lst ( c)) c Note: in CL, lst returns the lst cons cell (k pir) We lso hve: first, second, third, nd CxR, where x is string of up to four s or ds. E.g., cdr, cddr, cddr, cddr, Memer Memer returns true, ut insted of simply returning t, its returns the prt of the list eginning with the oject it ws looking for. > (memer ( c)) ( c) memer compres ojects using equl? There re versions tht use eq? nd eqv? And tht tke n ritrry funcgon 7

Defining memer (define (memer X L) (cond ((null? L) #f) ((equl? X (cr L)) L) (#t (memer X (cdr L))))) Memf If we wnt to find n element s?sfying n ritrry predicte we use the func?on memf: > (memf odd? (2 3 4)) (3 4) Which could e defined like: (define (memf f l) (cond ((null? l) #f) ((f (cr l)) l) (#t (memf f (cdr l))))) DoQed pirs nd lists Lists uilt y clling list re known s proper lists; they lwys end with pointer to null A proper list is either the empty list, or pir whose cdr is proper list Pirs ren t just for uilding lists, if you need structure with two fields, you cn use pir Use cr to get the 1st field nd cdr for the 2nd > (define the_pir (cons )) (. ) Becuse this pir is not proper list, it s displyed in dot notgon In dot not?on the cr nd cdr of ech pir re shown seprted y period DoQed pirs nd lists A pir tht isn t proper list is clled dohed pir Rememer tht dohed pir isn t relly list t ll, It s just (. ) two prt dt structure Doted pirs nd lists tht end with dohed pir re not used very onen If you produce one for 331 code, you ve proly mde n error 8

Conclusion Simple linked lists were the only dt structure in erly Lisps From them you cn uild most other dt structures though efficiency my e low Its s?ll the most used dt tructure in Lisp nd Scheme Simple, elegnt, less is more Recursion is the nturl wy to process lists 9