Peter Siebel - Practical Common Lisp

Здесь есть возможность читать онлайн «Peter Siebel - Practical Common Lisp» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2005, ISBN: 2005, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Practical Common Lisp: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Practical Common Lisp»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Practical Common Lisp — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Practical Common Lisp», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

(4) ; whoops!

List-Manipulation Functions

With that background out of the way, you're ready to look at the library of functions Common Lisp provides for manipulating lists.

You've already seen the basic functions for getting at the elements of a list: FIRST and REST . Although you can get at any element of a list by combining enough calls to REST (to move down the list) with a FIRST (to extract the element), that can be a bit tedious. So Common Lisp provides functions named for the other ordinals from SECOND to TENTH that return the appropriate element. More generally, the function NTH takes two arguments, an index and a list, and returns the n th (zero-based) element of the list. Similarly, NTHCDR takes an index and a list and returns the result of calling CDR n times. (Thus, (nthcdr 0 ...)simply returns the original list, and (nthcdr 1 ...)is equivalent to REST .) Note, however, that none of these functions is any more efficient, in terms of work done by the computer, than the equivalent combinations of FIRST s and REST s—there's no way to get to the n th element of a list without following n CDR references. [141] NTH is roughly equivalent to the sequence function ELT but works only with lists. Also, confusingly, NTH takes the index as the first argument, the opposite of ELT . Another difference is that ELT will signal an error if you try to access an element at an index greater than or equal to the length of the list, but NTH will return NIL .

The 28 composite CAR / CDR functions are another family of functions you may see used from time to time. Each function is named by placing a sequence of up to four As and Ds between a Cand R, with each Arepresenting a call to CAR and each Da call to CDR . Thus:

(caar list) === (car (car list))

(cadr list) === (car (cdr list))

(cadadr list) === (car (cdr (car (cdr list))))

Note, however, that many of these functions make sense only when applied to lists that contain other lists. For instance, CAAR extracts the CAR of the CAR of the list it's given; thus, the list it's passed must contain another list as its first element. In other words, these are really functions on trees rather than lists:

(caar (list 1 2 3)) ==> error

(caar (list (list 1 2) 3)) ==> 1

(cadr (list (list 1 2) (list 3 4))) ==> (3 4)

(caadr (list (list 1 2) (list 3 4))) ==> 3

These functions aren't used as often now as in the old days. And even the most die-hard old-school Lisp hackers tend to avoid the longer combinations. However, they're used quite a bit in older Lisp code, so it's worth at least understanding how they work. [142] In particular, they used to be used to extract the various parts of expressions passed to macros before the invention of destructuring parameter lists. For example, you could take apart the following expression: (when (> x 10) (print x)) Like this: ;; the condition (cadr '(when (> x 10) (print x))) ==> (> X 10) ;; the body, as a list (cddr '(when (> x 10) (print x))) ==> ((PRINT X))

The FIRST - TENTH and CAR , CADR , and so on, functions can also be used as SETF able places if you're using lists nonfunctionally.

Table 12-1 summarizes some other list functions that I won't cover in detail.

Table 12-1. Other List Functions

Function Description
LAST Returns the last cons cell in a list. With an integer, argument returns the last n cons cells.
BUTLAST Returns a copy of the list, excluding the last cons cell. With an integer argument, excludes the last n cells.
NBUTLAST The recycling version of BUTLAST ; may modify and return the argument list but has no reliable side effects.
LDIFF Returns a copy of a list up to a given cons cell.
TAILP Returns true if a given object is a cons cell that's part of the structure of a list.
LIST* Builds a list to hold all but the last of its arguments and then makes the last argument the CDR of the last cell in the list. In other words, a cross between LIST and APPEND .
MAKE-LIST Builds an n item list. The initial elements of the list are NIL or the value specified with the :initial-elementkeyword argument.
REVAPPEND Combination of REVERSE and APPEND ; reverses first argument as with REVERSE and then appends the second argument.
NRECONC Recycling version of REVAPPEND ; reverses first argument as if by NREVERSE and then appends the second argument. No reliable side effects.
CONSP Predicate to test whether an object is a cons cell.
ATOM Predicate to test whether an object is not a cons cell.
LISTP Predicate to test whether an object is either a cons cell or NIL .
NULL Predicate to test whether an object is NIL . Functionally equivalent to NOT but stylistically preferable when testing for an empty list as opposed to boolean false.

Mapping

Another important aspect of the functional style is the use of higher-order functions, functions that take other functions as arguments or return functions as values. You saw several examples of higher-order functions, such as MAP , in the previous chapter. Although MAP can be used with both lists and vectors (that is, with any kind of sequence), Common Lisp also provides six mapping functions specifically for lists. The differences between the six functions have to do with how they build up their result and whether they apply the function to the elements of the list or to the cons cells of the list structure.

MAPCAR is the function most like MAP . Because it always returns a list, it doesn't require the result-type argument MAP does. Instead, its first argument is the function to apply, and subsequent arguments are the lists whose elements will provide the arguments to the function. Otherwise, it behaves like MAP : the function is applied to successive elements of the list arguments, taking one element from each list per application of the function. The results of each function call are collected into a new list. For example:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Practical Common Lisp»

Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Practical Common Lisp»

Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x