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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

These calls compare elements of two sequences pairwise:

(every #'> #(1 2 3 4) #(5 4 3 2)) ==> NIL

(some #'> #(1 2 3 4) #(5 4 3 2)) ==> T

(notany #'> #(1 2 3 4) #(5 4 3 2)) ==> NIL

(notevery #'> #(1 2 3 4) #(5 4 3 2)) ==> T

Sequence Mapping Functions

Finally, the last of the sequence functions are the generic mapping functions. MAP , like the sequence predicate functions, takes a n -argument function and n sequences. But instead of a boolean value, MAP returns a new sequence containing the result of applying the function to subsequent elements of the sequences. Like CONCATENATE and MERGE , MAP needs to be told what kind of sequence to create.

(map 'vector #'* #(1 2 3 4 5) #(10 9 8 7 6)) ==> #(10 18 24 28 30)

MAP-INTO is like MAP except instead of producing a new sequence of a given type, it places the results into a sequence passed as the first argument. This sequence can be the same as one of the sequences providing values for the function. For instance, to sum several vectors— a, b, and c—into one, you could write this:

(map-into a #'+ a b c)

If the sequences are different lengths, MAP-INTO affects only as many elements as are present in the shortest sequence, including the sequence being mapped into. However, if the sequence being mapped into is a vector with a fill pointer, the number of elements affected isn't limited by the fill pointer but rather by the actual size of the vector. After a call to MAP-INTO , the fill pointer will be set to the number of elements mapped. MAP-INTO won't, however, extend an adjustable vector.

The last sequence function is REDUCE , which does another kind of mapping: it maps over a single sequence, applying a two-argument function first to the first two elements of the sequence and then to the value returned by the function and subsequent elements of the sequence. Thus, the following expression sums the numbers from one to ten:

(reduce #'+ #(1 2 3 4 5 6 7 8 9 10)) ==> 55

REDUCE is a surprisingly useful function—whenever you need to distill a sequence down to a single value, chances are you can write it with REDUCE , and it will often be quite a concise way to express what you want. For instance, to find the maximum value in a sequence of numbers, you can write (reduce #'max numbers). REDUCE also takes a full complement of keyword arguments ( :key, :from-end, :start, and :end) and one unique to REDUCE ( :initial-value). The latter specifies a value that's logically placed before the first element of the sequence (or after the last if you also specify a true :from-endargument).

Hash Tables

The other general-purpose collection provided by Common Lisp is the hash table. Where vectors provide an integer-indexed data structure, hash tables allow you to use arbitrary objects as the indexes, or keys. When you add a value to a hash table, you store it under a particular key. Later you can use the same key to retrieve the value. Or you can associate a new value with the same key—each key maps to a single value.

With no arguments MAKE-HASH-TABLE makes a hash table that considers two keys equivalent if they're the same object according to EQL . This is a good default unless you want to use strings as keys, since two strings with the same contents aren't necessarily EQL . In that case you'll want a so-called EQUAL hash table, which you can get by passing the symbol EQUAL as the :testkeyword argument to MAKE-HASH-TABLE . Two other possible values for the :testargument are the symbols EQ and EQUALP . These are, of course, the names of the standard object comparison functions, which I discussed in Chapter 4. However, unlike the :testargument passed to sequence functions, MAKE-HASH-TABLE 's :testcan't be used to specify an arbitrary function—only the values EQ , EQL , EQUAL , and EQUALP . This is because hash tables actually need two functions, an equivalence function and a hash function that computes a numerical hash code from the key in a way compatible with how the equivalence function will ultimately compare two keys. However, although the language standard provides only for hash tables that use the standard equivalence functions, most implementations provide some mechanism for defining custom hash tables.

The GETHASH function provides access to the elements of a hash table. It takes two arguments—a key and the hash table—and returns the value, if any, stored in the hash table under that key or NIL . [129] By an accident of history, the order of arguments to GETHASH is the opposite of ELT — ELT takes the collection first and then the index while GETHASH takes the key first and then the collection. For example:

(defparameter *h* (make-hash-table))

(gethash 'foo *h*) ==> NIL

(setf (gethash 'foo *h*) 'quux)

(gethash 'foo *h*) ==> QUUX

Since GETHASH returns NIL if the key isn't present in the table, there's no way to tell from the return value the difference between a key not being in a hash table at all and being in the table with the value NIL . GETHASH solves this problem with a feature I haven't discussed yet—multiple return values. GETHASH actually returns two values; the primary value is the value stored under the given key or NIL . The secondary value is a boolean indicating whether the key is present in the hash table. Because of the way multiple values work, the extra return value is silently discarded unless the caller explicitly handles it with a form that can "see" multiple values.

I'll discuss multiple return values in greater detail in Chapter 20, but for now I'll give you a sneak preview of how to use the MULTIPLE-VALUE-BIND macro to take advantage of GETHASH 's extra return value. MULTIPLE-VALUE-BIND creates variable bindings like LET does, filling them with the multiple values returned by a form.

The following function shows how you might use MULTIPLE-VALUE-BIND ; the variables it binds are valueand present:

(defun show-value (key hash-table)

(multiple-value-bind (value present) (gethash key hash-table)

(if present

(format nil "Value ~a actually present." value)

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

Интервал:

Закладка:

Сделать

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

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


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

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

x