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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
(incf (balance account) overdraft))))
This :before
method has three advantages over a primary method. One is that it makes it immediately obvious how the method changes the overall behavior of the withdraw
function—it's not going to interfere with the main behavior or change the result returned.
The next advantage is that a primary method specialized on a class more specific than checking-account
won't interfere with this :before
method, making it easier for an author of a subclass of checking-account
to extend the behavior of withdraw
while keeping part of the old behavior.
Lastly, since a :before
method doesn't have to call CALL-NEXT-METHOD
to pass control to the remaining methods, it's impossible to introduce a bug by forgetting to.
The other auxiliary methods also fit into the effective method in ways suggested by their names. All the :after
methods run after the primary methods in most-specific-last order, that is, the reverse of the :before
methods. Thus, the :before
and :after
methods combine to create a sort of nested wrapping around the core functionality provided by the primary methods—each more-specific :before
method will get a chance to set things up so the less-specific :before
methods and primary methods can run successfully, and each more-specific :after
method will get a chance to clean up after all the primary methods and less-specific :after
methods.
Finally, :around
methods are combined much like primary methods except they're run "around" all the other methods. That is, the code from the most specific :around
method is run before anything else. Within the body of an :around
method, CALL-NEXT-METHOD
will lead to the code of the next most specific :around
method or, in the least specific :around
method, to the complex of :before
, primary, and :after
methods. Almost all :around
methods will contain such a call to CALL-NEXT-METHOD
because an :around
method that doesn't will completely hijack the implementation of the generic function from all the methods except for more-specific :around
methods.
Occasionally that kind of hijacking is called for, but typically :around
methods are used to establish some dynamic context in which the rest of the methods will run—to bind a dynamic variable, for example, or to establish an error handler (as I'll discuss in Chapter 19). About the only time it's appropriate for an :around
method to not call CALL-NEXT-METHOD
is when it returns a result cached from a previous call to CALL-NEXT-METHOD
. At any rate, an :around
method that doesn't call CALL-NEXT-METHOD
is responsible for correctly implementing the semantics of the generic function for all classes of arguments to which the method may apply, including future subclasses.
Auxiliary methods are just a convenient way to express certain common patterns more concisely and concretely. They don't actually allow you to do anything you couldn't do by combining primary methods with diligent adherence to a few coding conventions and some extra typing. Perhaps their biggest benefit is that they provide a uniform framework for extending generic functions. Often a library will define a generic function and provide a default primary method, allowing users of the library to customize its behavior by defining appropriate auxiliary methods.
Other Method Combinations
In addition to the standard method combination, the language specifies nine other built-in method combinations known as the simple built-in method combinations. You can also define custom method combinations, though that's a fairly esoteric feature and beyond the scope of this book. I'll briefly cover how to use the simple built-in combinations to give you a sense of the possibilities.
All the simple combinations follow the same pattern: instead of invoking the most specific primary method and letting it invoke less-specific primary methods via CALL-NEXT-METHOD
, the simple method combinations produce an effective method that contains the code of all the primary methods, one after another, all wrapped in a call to the function, macro, or special operator that gives the method combination its name. The nine combinations are named for the operators: +
, AND
, OR
, LIST
, APPEND
, NCONC
, MIN
, MAX
, and PROGN
. The simple combinations also support only two kinds of methods, primary methods, which are combined as just described, and :around
methods, which work like :around
methods in the standard method combination.
For example, a generic function that uses the +
method combination will return the sum of all the results returned by its primary methods. Note that the AND
and OR
method combinations won't necessarily run all the primary methods because of those macros' short-circuiting behavior—a generic function using the AND
combination will return NIL
as soon as one of the methods does and will return the value of the last method otherwise. Similarly, the OR
combination will return the first non- NIL
value returned by any of the methods.
To define a generic function that uses a particular method combination, you include a :method-combination
option in the DEFGENERIC
form. The value supplied with this option is the name of the method combination you want to use. For example, to define a generic function, priority
, that returns the sum of values returned by individual methods using the +
method combination, you might write this:
(defgeneric priority (job)
(:documentation "Return the priority at which the job should be run.")
(:method-combination +))
By default all these method combinations combine the primary methods in most-specific-first order. However, you can reverse the order by including the keyword :most-specific-last
after the name of the method combination in the DEFGENERIC
form. The order probably doesn't matter if you're using the +
combination unless the methods have side effects, but for demonstration purposes you can change priority
to use most-specific-last order like this:
(defgeneric priority (job)
(:documentation "Return the priority at which the job should be run.")
(:method-combination + :most-specific-last))
The primary methods on a generic function that uses one of these combinations must be qualified with the name of the method combination. Thus, a primary method defined on priority
might look like this:
(defmethod priority + ((job express-job)) 10)
This makes it obvious when you see a method definition that it's part of a particular kind of generic function.
All the simple built-in method combinations also support :around
methods that work like :around
methods in the standard method combination: the most specific :around
method runs before any other methods, and CALL-NEXT-METHOD
is used to pass control to less-and-less-specific :around
methods until it reaches the combined primary methods. The :most-specific-last
option doesn't affect the order of :around
methods. And, as I mentioned before, the built-in method combinations don't support :before
or :after
methods.
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.