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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Sorting and Merging
The functions SORT
and STABLE-SORT
provide two ways of sorting a sequence. They both take a sequence and a two-argument predicate and return a sorted version of the sequence.
(sort (vector "foo" "bar" "baz") #'string<) ==> #("bar" "baz" "foo")
The difference is that STABLE-SORT
is guaranteed to not reorder any elements considered equivalent by the predicate while SORT
guarantees only that the result is sorted and may reorder equivalent elements.
Both these functions are examples of what are called destructive functions. Destructive functions are allowed—typically for reasons of efficiency—to modify their arguments in more or less arbitrary ways. This has two implications: one, you should always do something with the return value of these functions (such as assign it to a variable or pass it to another function), and, two, unless you're done with the object you're passing to the destructive function, you should pass a copy instead. I'll say more about destructive functions in the next chapter.
Typically you won't care about the unsorted version of a sequence after you've sorted it, so it makes sense to allow SORT
and STABLE-SORT
to destroy the sequence in the course of sorting it. But it does mean you need to remember to write the following: [128] When the sequence passed to the sorting functions is a vector, the "destruction" is actually guaranteed to entail permuting the elements in place, so you could get away without saving the returned value. However, it's good style to always do something with the return value since the sorting functions can modify lists in much more arbitrary ways.
(setf my-sequence (sort my-sequence #'string<))
rather than just this:
(sort my-sequence #'string<)
Both these functions also take a keyword argument, :key
, which, like the :key
argument in other sequence functions, should be a function and will be used to extract the values to be passed to the sorting predicate in the place of the actual elements. The extracted keys are used only to determine the ordering of elements; the sequence returned will contain the actual elements of the argument sequence.
The MERGE
function takes two sequences and a predicate and returns a sequence produced by merging the two sequences, according to the predicate. It's related to the two sorting functions in that if each sequence is already sorted by the same predicate, then the sequence returned by MERGE
will also be sorted. Like the sorting functions, MERGE
takes a :key
argument. Like CONCATENATE
, and for the same reason, the first argument to MERGE
must be a type descriptor specifying the type of sequence to produce.
(merge 'vector #(1 3 5) #(2 4 6) #'<) ==> #(1 2 3 4 5 6)
(merge 'list #(1 3 5) #(2 4 6) #'<) ==> (1 2 3 4 5 6)
Subsequence Manipulations
Another set of functions allows you to manipulate subsequences of existing sequences. The most basic of these is SUBSEQ
, which extracts a subsequence starting at a particular index and continuing to a particular ending index or the end of the sequence. For instance:
(subseq "foobarbaz" 3) ==> "barbaz"
(subseq "foobarbaz" 3 6) ==> "bar"
SUBSEQ
is also SETF
able, but it won't extend or shrink a sequence; if the new value and the subsequence to be replaced are different lengths, the shorter of the two determines how many characters are actually changed.
(defparameter *x* (copy-seq "foobarbaz"))
(setf (subseq *x* 3 6) "xxx") ; subsequence and new value are same length
*x* ==> "fooxxxbaz"
(setf (subseq *x* 3 6) "abcd") ; new value too long, extra character ignored.
*x* ==> "fooabcbaz"
(setf (subseq *x* 3 6) "xx") ; new value too short, only two characters changed
*x* ==> "fooxxcbaz"
You can use the FILL
function to set multiple elements of a sequence to a single value. The required arguments are a sequence and the value with which to fill it. By default every element of the sequence is set to the value; :start
and :end
keyword arguments can limit the effects to a given subsequence.
If you need to find a subsequence within a sequence, the SEARCH
function works like POSITION
except the first argument is a sequence rather than a single item.
(position #\b "foobarbaz") ==> 3
(search "bar" "foobarbaz") ==> 3
On the other hand, to find where two sequences with a common prefix first diverge, you can use the MISMATCH
function. It takes two sequences and returns the index of the first pair of mismatched elements.
(mismatch "foobarbaz" "foom") ==> 3
It returns NIL
if the strings match. MISMATCH
also takes many of the standard keyword arguments: a :key
argument for specifying a function to use to extract the values to be compared; a :test
argument to specify the comparison function; and :start1
, :end1
, :start2
, and :end2
arguments to specify subsequences within the two sequences. And a :from-end
argument of T
specifies the sequences should be searched in reverse order, causing MISMATCH
to return the index, in the first sequence, where whatever common suffix the two sequences share begins.
(mismatch "foobar" "bar" :from-end t) ==> 3
Sequence Predicates
Four other handy functions are EVERY
, SOME
, NOTANY
, and NOTEVERY
, which iterate over sequences testing a boolean predicate. The first argument to all these functions is the predicate, and the remaining arguments are sequences. The predicate should take as many arguments as the number of sequences passed. The elements of the sequences are passed to the predicate—one element from each sequence—until one of the sequences runs out of elements or the overall termination test is met: EVERY
terminates, returning false, as soon as the predicate fails. If the predicate is always satisfied, it returns true. SOME
returns the first non- NIL
value returned by the predicate or returns false if the predicate is never satisfied. NOTANY
returns false as soon as the predicate is satisfied or true if it never is. And NOTEVERY
returns true as soon as the predicate fails or false if the predicate is always satisfied. Here are some examples of testing just one sequence:
(every #'evenp #(1 2 3 4 5)) ==> NIL
(some #'evenp #(1 2 3 4 5)) ==> T
(notany #'evenp #(1 2 3 4 5)) ==> NIL
(notevery #'evenp #(1 2 3 4 5)) ==> T
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.