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

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

Интервал:

Закладка:

Сделать

(incf (balance account) overdraft))))

This :beforemethod has three advantages over a primary method. One is that it makes it immediately obvious how the method changes the overall behavior of the withdrawfunction—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-accountwon't interfere with this :beforemethod, making it easier for an author of a subclass of checking-accountto extend the behavior of withdrawwhile keeping part of the old behavior.

Lastly, since a :beforemethod 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 :aftermethods run after the primary methods in most-specific-last order, that is, the reverse of the :beforemethods. Thus, the :beforeand :aftermethods combine to create a sort of nested wrapping around the core functionality provided by the primary methods—each more-specific :beforemethod will get a chance to set things up so the less-specific :beforemethods and primary methods can run successfully, and each more-specific :aftermethod will get a chance to clean up after all the primary methods and less-specific :aftermethods.

Finally, :aroundmethods are combined much like primary methods except they're run "around" all the other methods. That is, the code from the most specific :aroundmethod is run before anything else. Within the body of an :aroundmethod, CALL-NEXT-METHOD will lead to the code of the next most specific :aroundmethod or, in the least specific :aroundmethod, to the complex of :before, primary, and :aftermethods. Almost all :aroundmethods will contain such a call to CALL-NEXT-METHOD because an :aroundmethod that doesn't will completely hijack the implementation of the generic function from all the methods except for more-specific :aroundmethods.

Occasionally that kind of hijacking is called for, but typically :aroundmethods 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 :aroundmethod 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 :aroundmethod 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 :aroundmethods, which work like :aroundmethods 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-combinationoption 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-lastafter 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 priorityto 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 prioritymight 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 :aroundmethods that work like :aroundmethods in the standard method combination: the most specific :aroundmethod runs before any other methods, and CALL-NEXT-METHOD is used to pass control to less-and-less-specific :aroundmethods until it reaches the combined primary methods. The :most-specific-lastoption doesn't affect the order of :aroundmethods. And, as I mentioned before, the built-in method combinations don't support :beforeor :aftermethods.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x