notes22 - overall answer; you want to take the union of...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
> (cons ’(new element) ’(the old list)) ((new element) the old list) (Of course, cons really just takes two arguments and makes a pair containing them, but if you’re using that pair as the head of a list, then the eFect of cons in terms of the list abstraction is to add one new element.) This may seem too speci±c and arbitrary to be useful, but in fact cons is the most commonly used list constructor, because adding one new element is exactly what you want to do in a recursive transformation of a list: (define (map fn seq) (if (null? seq) ’() (CONS (fn (car seq)) (map fn (cdr seq))))) Append is used to combine two or more lists in a way that “²attens” some of the structure of the result: It returns a list whose elements are the elements of the arguments, which must be lists: > (append ’(one list) ’(and another list)) (one list and another list) It’s most useful when combining results from multiple recursive calls, each of which returns a subset of the
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: overall answer; you want to take the union of those sets, and that’s what append does. • Lists vs. sentences. We started out the semester using an abstract data type called sentence that looks a lot like a list. What’s the diFerence, and why did we do it that way? Our goal was to allow you to create aggregates of words without having to think about the structure of their internal representation (i.e., about pairs). We do this by deciding that the elements of a sentence must be words (not sublists), and enforcing that by giving you the constructor sentence that creates only sentences. Example: One of the homework problems this week asks you to reverse a list. You’ll see that this is a little tricky using cons , car , and cdr as the problem asks, but it’s easy for sentences: (define (reverse sent) (if (empty? sent) ’() (se (reverse (bf sent)) (first sent)) )) 288...
View Full Document

This note was uploaded on 02/17/2010 for the course COMPUTER S 26275 taught by Professor Harvey,b during the Spring '10 term at Berkeley.

Ask a homework question - tutors are online