Peter Siebel - Practical Common Lisp
Здесь есть возможность читать онлайн «Peter Siebel - Practical Common Lisp» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2005, ISBN: 2005, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Practical Common Lisp
- Автор:
- Издательство:Apress
- Жанр:
- Год:2005
- ISBN:1-59059-239-5
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Practical Common Lisp: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Practical Common Lisp»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Practical Common Lisp — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Practical Common Lisp», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
And while :from-end
can't change the results of the COUNT
function, it does affect the order the elements are passed to any :test
and :key
functions, which could possibly have side effects. For example:
CL-USER> (defparameter *v* #((a 10) (b 20) (a 30) (b 40)))
*V*
CL-USER> (defun verbose-first (x) (format t "Looking at ~s~%" x) (first x))
VERBOSE-FIRST
CL-USER> (count 'a *v* :key #'verbose-first)
Looking at (A 10)
Looking at (B 20)
Looking at (A 30)
Looking at (B 40)
2
CL-USER> (count 'a *v* :key #'verbose-first :from-end t)
Looking at (B 40)
Looking at (A 30)
Looking at (B 20)
Looking at (A 10)
2
Table 11-2 summarizes these arguments.
Table 11-2. Standard Sequence Function Keyword Arguments
Argument | Meaning | Default |
:test |
Two-argument function used to compare item (or value extracted by :key function) to element. |
EQL |
:key |
One-argument function to extract key value from actual sequence element. NIL means use element as is. |
NIL |
:start |
Starting index (inclusive) of subsequence. | 0 |
:end |
Ending index (exclusive) of subsequence. NIL indicates end of sequence. |
NIL |
:from-end |
If true, the sequence will be traversed in reverse order, from end to start. | NIL |
:count |
Number indicating the number of elements to remove or substitute or NIL to indicate all ( REMOVE and SUBSTITUTE only). |
NIL |
Higher-Order Function Variants
For each of the functions just discussed, Common Lisp provides two higher-order function variants that, in the place of the item argument, take a function to be called on each element of the sequence. One set of variants are named the same as the basic function with an -IF
appended. These functions count, find, remove, and substitute elements of the sequence for which the function argument returns true. The other set of variants are named with an -IF-NOT
suffix and count, find, remove, and substitute elements for which the function argument does not return true.
(count-if #'evenp #(1 2 3 4 5)) ==> 2
(count-if-not #'evenp #(1 2 3 4 5)) ==> 3
(position-if #'digit-char-p "abcd0001") ==> 4
(remove-if-not #'(lambda (x) (char= (elt x 0) #\f))
#("foo" "bar" "baz" "foom")) ==> #("foo" "foom")
According to the language standard, the -IF-NOT
variants are deprecated. However, that deprecation is generally considered to have itself been ill-advised. If the standard is ever revised, it's more likely the deprecation will be removed than the -IF-NOT
functions. For one thing, the REMOVE-IF-NOT
variant is probably used more often than REMOVE-IF
. Despite its negative-sounding name, REMOVE-IF-NOT
is actually the positive variant—it returns the elements that do satisfy the predicate. [125] This same functionality goes by the name grep in Perl and filter in Python.
The -IF
and -IF-NOT
variants accept all the same keyword arguments as their vanilla counterparts except for :test
, which isn't needed since the main argument is already a function. [126] The difference between the predicates passed as :test arguments and as the function arguments to the -IF and -IF-NOT functions is that the :test predicates are two-argument predicates used to compare the elements of the sequence to the specific item while the -IF and -IF-NOT predicates are one-argument functions that simply test the individual elements of the sequence. If the vanilla variants didn't exist, you could implement them in terms of the -IF versions by embedding a specific item in the test function. (count char string) === (count-if #'(lambda (c) (eql char c)) string) (count char string :test #'CHAR-EQUAL) === (count-if #'(lambda (c) (char-equal char c)) string)
With a :key
argument, the value extracted by the :key
function is passed to the function instead of the actual element.
(count-if #'evenp #((1 a) (2 b) (3 c) (4 d) (5 e)) :key #'first) ==> 2
(count-if-not #'evenp #((1 a) (2 b) (3 c) (4 d) (5 e)) :key #'first) ==> 3
(remove-if-not #'alpha-char-p
#("foo" "bar" "1baz") :key #'(lambda (x) (elt x 0))) ==> #("foo" "bar")
The REMOVE
family of functions also support a fourth variant, REMOVE-DUPLICATES
, that has only one required argument, a sequence, from which it removes all but one instance of each duplicated element. It takes the same keyword arguments as REMOVE
, except for :count
, since it always removes all duplicates.
(remove-duplicates #(1 2 1 2 3 1 2 3 4)) ==> #(1 2 3 4)
Whole Sequence Manipulations
A handful of functions perform operations on a whole sequence (or sequences) at a time. These tend to be simpler than the other functions I've described so far. For instance, COPY-SEQ
and REVERSE
each take a single argument, a sequence, and each returns a new sequence of the same type. The sequence returned by COPY-SEQ
contains the same elements as its argument while the sequence returned by REVERSE
contains the same elements but in reverse order. Note that neither function copies the elements themselves—only the returned sequence is a new object.
The CONCATENATE
function creates a new sequence containing the concatenation of any number of sequences. However, unlike REVERSE
and COPY-SEQ
, which simply return a sequence of the same type as their single argument, CONCATENATE
must be told explicitly what kind of sequence to produce in case the arguments are of different types. Its first argument is a type descriptor, like the :element-type
argument to MAKE-ARRAY
. In this case, the type descriptors you'll most likely use are the symbols VECTOR
, LIST
, or STRING
. [127] If you tell CONCATENATE to return a specialized vector, such as a string, all the elements of the argument sequences must be instances of the vector's element type.
For example:
(concatenate 'vector #(1 2 3) '(4 5 6)) ==> #(1 2 3 4 5 6)
(concatenate 'list #(1 2 3) '(4 5 6)) ==> (1 2 3 4 5 6)
(concatenate 'string "abc" '(#\d #\e #\f)) ==> "abcdef"
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.