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

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

Интервал:

Закладка:

Сделать

The ~$, or monetary, directive is similar to ~Fbut a bit simpler. As its name suggests, it's intended for emitting monetary units. With no parameters, it's basically equivalent to ~,2F. To modify the number of digits printed after the decimal point, you use the first parameter, while the second parameter controls the minimum number of digits to print before the decimal point.

(format nil "~$" pi) ==> "3.14"

(format nil "~2,4$" pi) ==> "0003.14"

All three directives, ~F, ~E, and ~$, can be made to always print a sign, plus or minus, with the at-sign modifier. [198] Well, that's what the language standard says. For some reason, perhaps rooted in a common ancestral code base, several Common Lisp implementations don't implement this aspect of the ~F directive correctly.

English-Language Directives

Some of the handiest FORMAT directives for generating human-readable messages are the ones for emitting English text. These directives allow you to emit numbers as English words, to emit plural markers based on the value of a format argument, and to apply case conversions to sections of FORMAT 's output.

The ~Rdirective, which I discussed in "Character and Integer Directives," when used with no base specified, prints numbers as English words or Roman numerals. When used with no prefix parameter and no modifiers, it emits the number in words as a cardinal number.

(format nil "~r" 1234) ==> "one thousand two hundred thirty-four"

With the colon modifier, it emits the number as an ordinal.

(format nil "~:r" 1234) ==> "one thousand two hundred thirty-fourth"

And with an at-sign modifier, it emits the number as a Roman numeral; with both an at-sign and a colon, it emits "old-style" Roman numerals in which fours and nines are written as IIII and VIIII instead of IV and IX.

(format nil "~@r" 1234) ==> "MCCXXXIV"

(format nil "~:@r" 1234) ==> "MCCXXXIIII"

For numbers too large to be represented in the given form, ~Rbehaves like ~D.

To help you generate messages with words properly pluralized, FORMAT provides the ~Pdirective, which simply emits an s unless the corresponding argument is 1.

(format nil "file~p" 1) ==> "file"

(format nil "file~p" 10) ==> "files"

(format nil "file~p" 0) ==> "files"

Typically, however, you'll use ~Pwith the colon modifier, which causes it to reprocess the previous format argument.

(format nil "~r file~:p" 1) ==> "one file"

(format nil "~r file~:p" 10) ==> "ten files"

(format nil "~r file~:p" 0) ==> "zero files"

With the at-sign modifier, which can be combined with the colon modifier, ~Pemits either y or ies .

(format nil "~r famil~:@p" 1) ==> "one family"

(format nil "~r famil~:@p" 10) ==> "ten families"

(format nil "~r famil~:@p" 0) ==> "zero families"

Obviously, ~Pcan't solve all pluralization problems and is no help for generating messages in other languages, but it's handy for the cases it does handle. And the ~[directive, which I'll discuss in a moment, gives you a more flexible way to conditionalize parts of FORMAT 's output.

The last directive for dealing with emitting English text is ~(, which allows you to control the case of text in the output. Each ~(is paired with a ~), and all the output generated by the portion of the control string between the two markers will be converted to all lowercase.

(format nil "~(~a~)" "FOO") ==> "foo"

(format nil "~(~@r~)" 124) ==> "cxxiv"

You can modify ~(with an at sign to make it capitalize the first word in a section of text, with a colon to make it to capitalize all words, and with both modifiers to convert all text to uppercase. (A word for the purpose of this directive is a sequence of alphanumeric characters delimited by nonalphanumeric characters or the ends of the text.)

(format nil "~(~a~)" "tHe Quick BROWN foX") ==> "the quick brown fox"

(format nil "~@(~a~)" "tHe Quick BROWN foX") ==> "The quick brown fox"

(format nil "~:(~a~)" "tHe Quick BROWN foX") ==> "The Quick Brown Fox"

(format nil "~:@(~a~)" "tHe Quick BROWN foX") ==> "THE QUICK BROWN FOX"

Conditional Formatting

In addition to directives that interpolate arguments and modify other output, FORMAT provides several directives that implement simple control constructs within the control string. One of these, which you used in Chapter 9, is the conditional directive ~[.This directive is closed by a corresponding ~], and in between are a number of clauses separated by ~;. The job of the ~[directive is to pick one of the clauses, which is then processed by FORMAT . With no modifiers or parameters, the clause is selected by numeric index; the ~[directive consumes a format argument, which should be a number, and takes the nth (zero-based) clause where N is the value of the argument.

(format nil "~[cero~;uno~;dos~]" 0) ==> "cero"

(format nil "~[cero~;uno~;dos~]" 1) ==> "uno"

(format nil "~[cero~;uno~;dos~]" 2) ==> "dos"

If the value of the argument is greater than the number of clauses, nothing is printed.

(format nil "~[cero~;uno~;dos~]" 3) ==> ""

However, if the last clause separator is ~:;instead of ~;, then the last clause serves as a default clause.

(format nil "~[cero~;uno~;dos~:;mucho~]" 3) ==> "mucho"

(format nil "~[cero~;uno~;dos~:;mucho~]" 100) ==> "mucho"

It's also possible to specify the clause to be selected using a prefix parameter. While it'd be silly to use a literal value in the control string, recall that #used as a prefix parameter means the number of arguments remaining to be processed. Thus, you can define a format string such as the following:

(defparameter *list-etc*

"~#[NONE~;~a~;~a and ~a~:;~a, ~a~]~#[~; and ~a~:;, ~a, etc~].")

and then use it like this:

(format nil *list-etc*) ==> "NONE."

(format nil *list-etc* 'a) ==> "A."

(format nil *list-etc* 'a 'b) ==> "A and B."

(format nil *list-etc* 'a 'b 'c) ==> "A, B and C."

(format nil *list-etc* 'a 'b 'c 'd) ==> "A, B, C, etc."

(format nil *list-etc* 'a 'b 'c 'd 'e) ==> "A, B, C, etc."

Note that the control string actually contains two ~[~]directives—both of which use #to select the clause to use. The first consumes between zero and two arguments, while the second consumes one more, if available. FORMAT will silently ignore any arguments not consumed while processing the control string.

With a colon modifier, the ~[can contain only two clauses; the directive consumes a single argument and processes the first clause if the argument is NIL and the second clause is otherwise. You used this variant of ~[in Chapter 9 to generate pass/fail messages, like this:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x