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

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

Интервал:

Закладка:

Сделать

If the application is simple enough to be written with no libraries beyond the facilities provided by the language itself, you could define a simple package like this:

(defpackage :com.gigamonkeys.email-db

(:use :common-lisp))

This defines a package, named COM.GIGAMONKEYS.EMAIL-DB, that inherits all the symbols exported by the COMMON-LISPpackage. [226] In many Lisp implementations the :use clause is optional if you want only to :use COMMON-LISP —if it's omitted, the package will automatically inherit names from an implementation-defined list of packages that will usually include COMMON-LISP . However, your code will be more portable if you always explicitly specify the packages you want to :use . Those who are averse to typing can use the package's nickname and write (:use :cl) .

You actually have several choices of how to represent the names of packages and, as you'll see, the names of symbols in a DEFPACKAGE . Packages and symbols are named with strings. However, in a DEFPACKAGE form, you can specify the names of packages and symbols with string designators . A string designator is either a string, which designates itself; a symbol, which designates its name; or a character, which designates a one-character string containing just the character. Using keyword symbols, as in the previous DEFPACKAGE , is a common style that allows you to write the names in lowercase—the reader will convert the names to uppercase for you. You could also write the DEFPACKAGE with strings, but then you have to write them in all uppercase, because the true names of most symbols and packages are in fact uppercase because of the case conversion performed by the reader. [227] Using keywords instead of strings has another advantage—Allegro provides a "modern mode" Lisp in which the reader does no case conversion of names and in which, instead of a COMMON-LISP package with uppercase names, provides a common-lisp package with lowercase names. Strictly speaking, this Lisp isn't a conforming Common Lisp since all the names in the standard are defined to be uppercase. But if you write your DEFPACKAGE forms using keyword symbols, they will work both in Common Lisp and in this near relative.

(defpackage "COM.GIGAMONKEYS.EMAIL-DB"

(:use "COMMON-LISP"))

You could also use nonkeyword symbols—the names in DEFPACKAGE aren't evaluated—but then the very act of reading the DEFPACKAGE form would cause those symbols to be interned in the current package, which at the very least will pollute that namespace and may also cause problems later if you try to use the package. [228] Some folks, instead of keywords, use uninterned symbols, using the #: syntax. (defpackage #:com.gigamonkeys.email-db (:use #:common-lisp)) This saves a tiny bit of memory by not interning any symbols in the keyword package—the symbol can become garbage after DEFPACKAGE (or the code it expands into) is done with it. However, the difference is so slight that it really boils down to a matter of aesthetics.

To read code in this package, you need to make it the current package with the IN-PACKAGE macro:

(in-package :com.gigamonkeys.email-db)

If you type this expression at the REPL, it will change the value of *PACKAGE* , affecting how the REPL reads subsequent expressions, until you change it with another call to IN-PACKAGE . Similarly, if you include an IN-PACKAGE in a file that's loaded with LOAD or compiled with COMPILE-FILE , it will change the package, affecting the way subsequent expressions in the file are read. [229] The reason to use IN-PACKAGE instead of just SETF ing *PACKAGE* is that IN-PACKAGE expands into code that will run when the file is compiled by COMPILE-FILE as well as when the file is loaded, changing the way the reader reads the rest of the file during compilation.

With the current package set to the COM.GIGAMONKEYS.EMAIL-DBpackage, other than names inherited from the COMMON-LISPpackage, you can use any name you want for whatever purpose you want. Thus, you could define a new hello-worldfunction that could coexist with the hello-worldfunction previously defined in COMMON-LISP-USER. Here's the behavior of the existing function:

CL-USER> (hello-world)

hello, world

NIL

Now you can switch to the new package using IN-PACKAGE . [230] In the REPL buffer in SLIME you can also change packages with a REPL shortcut. Type a comma, and then enter change-package at the Command: prompt. Notice how the prompt changes—the exact form is determined by the development environment, but in SLIME the default prompt consists of an abbreviated version of the package name.

CL-USER> (in-package :com.gigamonkeys.email-db)

#

EMAIL-DB>

You can define a new hello-worldin this package:

EMAIL-DB> (defun hello-world () (format t "hello from EMAIL-DB package~%"))

HELLO-WORLD

And test it, like this:

EMAIL-DB> (hello-world)

hello from EMAIL-DB package

NIL

Now switch back to CL-USER.

EMAIL-DB> (in-package :cl-user)

#

CL-USER>

And the old function is undisturbed.

CL-USER> (hello-world)

hello, world

NIL

Packaging Reusable Libraries

While working on the e-mail database, you might write several functions related to storing and retrieving text that don't have anything in particular to do with e-mail. You might realize that those functions could be useful in other programs and decide to repackage them as a library. You should define a new package, but this time you'll export certain names to make them available to other packages.

(defpackage :com.gigamonkeys.text-db

(:use :common-lisp)

(:export :open-db

:save

:store))

Again, you use the COMMON-LISPpackage, because you'll need access to standard functions within COM.GIGAMONKEYS.TEXT-DB. The :exportclause specifies names that will be external in COM.GIGAMONKEYS.TEXT-DBand thus accessible in packages that :useit. Therefore, after you've defined this package, you can change the definition of the main application package to the following:

(defpackage :com.gigamonkeys.email-db

(:use :common-lisp :com.gigamonkeys.text-db))

Now code written in COM.GIGAMONKEYS.EMAIL-DBcan use unqualified names to refer to the exported symbols from both COMMON-LISPand COM.GIGAMONKEYS.TEXT-DB. All other names will continue to be interned directly in the COM.GIGAMONKEYS.EMAIL-DBpackage.

Importing Individual Names

Now suppose you find a third-party library of functions for manipulating e-mail messages. The names used in the library's API are exported from the package COM.ACME.EMAIL, so you could :usethat package to get easy access to those names. But suppose you need to use only one function from this library, and other exported symbols conflict with names you already use (or plan to use) in our own code. [231] During development, if you try to :use a package that exports a symbol with the same name as a symbol already interned in the using package, Lisp will signal an error and typically offer you a restart that will unintern the offending symbol from the using package. For more on this, see the section "Package Gotchas." In this case, you can import the one symbol you need with an :import-fromclause in the DEFPACKAGE . For instance, if the name of the function you want to use is parse-email-address, you can change the DEFPACKAGE to this:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x