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

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

Интервал:

Закладка:

Сделать

Less frequently used is the related ~~directive, which causes FORMAT to emit a literal tilde. Like the ~%and ~&directives, it can be parameterized with a number that controls how many tildes to emit.

Character and Integer Directives

In addition to the general-purpose directives, ~Aand ~S, FORMAT supports several directives that can be used to emit values of specific types in particular ways. One of the simplest of these is the ~Cdirective, which is used to emit characters. It takes no prefix arguments but can be modified with the colon and at-sign modifiers. Unmodified, its behavior is no different from ~Aexcept that it works only with characters. The modified versions are more useful. With a colon modifier, ~:Coutputs nonprinting characters such as space, tab, and newline by name. This is useful if you want to emit a message to the user about some character. For instance, the following:

(format t "Syntax error. Unexpected character: ~:c" char)

can emit messages like this:

Syntax error. Unexpected character: a

but also like the following:

Syntax error. Unexpected character: Space

With the at-sign modifier, ~@Cwill emit the character in Lisp's literal character syntax.

CL-USER> (format t "~@c~%" #\a)

#\a

NIL

With both the colon and at-sign modifiers, the ~Cdirective can print extra information about how to enter the character at the keyboard if it requires special key combinations. For instance, on the Macintosh, in certain applications you can enter a null character (character code 0 in ASCII or in any ASCII superset such as ISO-8859-1 or Unicode) by pressing the Control key and typing @. In OpenMCL, if you print the null character with the ~:Cdirective, it tells you this:

(format nil "~:@c" (code-char 0)) ==> "^@ (Control @)"

However, not all Lisps implement this aspect of the ~Cdirective. And even if they do, it may or may not be accurate—for instance, if you're running OpenMCL in SLIME, the C-@key chord is intercepted by Emacs, invoking set-mark-command. [196] This variant on the ~C directive makes more sense on platforms like the Lisp Machines where key press events were represented by Lisp characters.

Format directives dedicated to emitting numbers are another important category. While you can use the ~Aand ~Sdirectives to emit numbers, if you want fine control over how they're printed, you need to use one of the number-specific directives. The numeric directives can be divided into two subcategories: directives for formatting integer values and directives for formatting floating-point values.

Five closely related directives format integer values: ~D, ~X, ~O, ~B, and ~R. The most frequently used is the ~Ddirective, which outputs integers in base 10.

(format nil "~d" 1000000) ==> "1000000"

As I mentioned previously, with a colon modifier it adds commas.

(format nil "~:d" 1000000) ==> "1,000,000"

And with an at-sign modifier, it always prints a sign.

(format nil "~@d" 1000000) ==> "+1000000"

And the two modifiers can be combined.

(format nil "~:@d" 1000000) ==> "+1,000,000"

The first prefix parameter can specify a minimum width for the output, and the second parameter can specify a padding character to use. The default padding character is space, and padding is always inserted before the number itself.

(format nil "~12d" 1000000) ==> " 1000000"

(format nil "~12,'0d" 1000000) ==> "000001000000"

These parameters are handy for formatting things such as dates in a fixed-width format.

(format nil "~4,'0d-~2,'0d-~2,'0d" 2005 6 10) ==> "2005-06-10"

The third and fourth parameters are used in conjunction with the colon modifier: the third parameter specifies the character to use as the separator between groups and digits, and the fourth parameter specifies the number of digits per group. These parameters default to a comma and the number 3. Thus, you can use the directive ~:Dwithout parameters to output large integers in standard format for the United States but can change the comma to a period and the grouping from 3 to 4 with ~,,'.,4D.

(format nil "~:d" 100000000) ==> "100,000,000"

(format nil "~,,'.,4:d" 100000000) ==> "1.0000.0000"

Note that you must use commas to hold the places of the unspecified width and padding character parameters, allowing them to keep their default values.

The ~X, ~O, and ~Bdirectives work just like the ~Ddirective except they emit numbers in hexadecimal (base 16), octal (base 8), and binary (base 2).

(format nil "~x" 1000000) ==> "f4240"

(format nil "~o" 1000000) ==> "3641100"

(format nil "~b" 1000000) ==> "11110100001001000000"

Finally, the ~Rdirective is the general radix directive. Its first parameter is a number between 2 and 36 (inclusive) that indicates what base to use. The remaining parameters are the same as the four parameters accepted by the ~D, ~X, ~O, and ~Bdirectives, and the colon and at-sign modifiers modify its behavior in the same way. The ~Rdirective also has some special behavior when used with no prefix parameters, which I'll discuss in the section "English-Language Directives."

Floating-Point Directives

Four directives format floating-point values: ~F, ~E, ~G, and ~$. The first three of these are the directives based on FORTRAN's edit descriptors. I'll skip most of the details of those directives since they mostly have to do with formatting floating-point values for use in tabular form. However, you can use the ~F, ~E, and ~$directives to interpolate floating-point values into text. The ~G, or general, floating-point directive, on the other hand, combines aspects of the ~Fand ~Edirectives in a way that only really makes sense for generating tabular output.

The ~Fdirective emits its argument, which should be a number, [197] Technically, if the argument isn't a real number, ~F is supposed to format it as if by the ~D directive, which in turn behaves like the ~A directive if the argument isn't a number, but not all implementations get this right. in decimal format, possibly controlling the number of digits after the decimal point. The ~Fdirective is, however, allowed to use computerized scientific notation if the number is sufficiently large or small. The ~Edirective, on the other hand, always emits numbers in computerized scientific notation. Both of these directives take a number of prefix parameters, but you need to worry only about the second, which controls the number of digits to print after the decimal point.

(format nil "~f" pi) ==> "3.141592653589793d0"

(format nil "~,4f" pi) ==> "3.1416"

(format nil "~e" pi) ==> "3.141592653589793d+0"

(format nil "~,4e" pi) ==> "3.1416d+0"

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

Интервал:

Закладка:

Сделать

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

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


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

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

x