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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
The first argument to FORMAT
, the destination for the output, can be T
, NIL
, a stream, or a string with a fill pointer. T
is shorthand for the stream *STANDARD-OUTPUT*
, while NIL
causes FORMAT
to generate its output to a string, which it then returns. [195] To slightly confuse matters, most other I/O functions also accept T and NIL as stream designators but with a different meaning: as a stream designator, T designates the bidirectional stream *TERMINAL-IO* , while NIL designates *STANDARD-OUTPUT* as an output stream and *STANDARD-INPUT* as an input stream.
If the destination is a stream, the output is written to the stream. And if the destination is a string with a fill pointer, the formatted output is added to the end of the string and the fill pointer is adjusted appropriately. Except when the destination is NIL
and it returns a string, FORMAT
returns NIL
.
The second argument, the control string, is, in essence, a program in the FORMAT
language. The FORMAT
language isn't Lispy at all—its basic syntax is based on characters, not s-expressions, and it's optimized for compactness rather than easy comprehension. This is why a complex FORMAT
control string can end up looking like line noise.
Most of FORMAT
's directives simply interpolate an argument into the output in one form or another. Some directives, such as ~%
, which causes FORMAT
to emit a newline, don't consume any arguments. And others, as you'll see, can consume more than one argument. One directive even allows you to jump around in the list of arguments in order to process the same argument more than once or to skip certain arguments in certain situations. But before I discuss specific directives, let's look at the general syntax of a directive.
FORMAT Directives
All directives start with a tilde ( ~
) and end with a single character that identifies the directive. You can write the character in either upper- or lowercase. Some directives take prefix parameters , which are written immediately following the tilde, separated by commas, and used to control things such as how many digits to print after the decimal point when printing a floating-point number. For example, the ~$
directive, one of the directives used to print floating-point values, by default prints two digits following the decimal point.
CL-USER> (format t "~$" pi)
3.14
NIL
However, with a prefix parameter, you can specify that it should print its argument to, say, five decimal places like this:
CL-USER> (format t "~5$" pi)
3.14159
NIL
The values of prefix parameters are either numbers, written in decimal, or characters, written as a single quote followed by the desired character. The value of a prefix parameter can also be derived from the format arguments in two ways: A prefix parameter of v
causes FORMAT
to consume one format argument and use its value for the prefix parameter. And a prefix parameter of #
will be evaluated as the number of remaining format arguments. For example:
CL-USER> (format t "~v$" 3 pi)
3.142
NIL
CL-USER> (format t "~#$" pi)
3.1
NIL
I'll give some more realistic examples of how you can use the #
argument in the section "Conditional Formatting."
You can also omit prefix parameters altogether. However, if you want to specify one parameter but not the ones before it, you must include a comma for each unspecified parameter. For instance, the ~F
directive, another directive for printing floating-point values, also takes a parameter to control the number of decimal places to print, but it's the second parameter rather than the first. If you want to use ~F
to print a number to five decimal places, you can write this:
CL-USER> (format t "~,5f" pi)
3.14159
NIL
You can also modify the behavior of some directives with colon and at-sign modifiers , which are placed after any prefix parameters and before the directive's identifying character. These modifiers change the behavior of the directive in small ways. For instance, with a colon modifier, the ~D
directive used to output integers in decimal emits the number with commas separating every three digits, while the at-sign modifier causes ~D
to include a plus sign when the number is positive.
CL-USER> (format t "~d" 1000000)
1000000
NIL
CL-USER> (format t "~:d" 1000000)
1,000,000
NIL
CL-USER> (format t "~@d" 1000000)
+1000000
NIL
When it makes sense, you can combine the colon and at-sign modifiers to get both modifications.
CL-USER> (format t "~:@d" 1000000)
+1,000,000
NIL
In directives where the two modified behaviors can't be meaningfully combined, using both modifiers is either undefined or given a third meaning.
Basic Formatting
Now you're ready to look at specific directives. I'll start with several of the most commonly used directives, including some you've seen in previous chapters.
The most general-purpose directive is ~A
, which consumes one format argument of any type and outputs it in aesthetic (human-readable) form. For example, strings are output without quotation marks or escape characters, and numbers are output in a natural way for the type of number. If you just want to emit a value for human consumption, this directive is your best bet.
(format nil "The value is: ~a" 10) ==> "The value is: 10"
(format nil "The value is: ~a" "foo") ==> "The value is: foo"
(format nil "The value is: ~a" (list 1 2 3)) ==> "The value is: (1 2 3)"
A closely related directive, ~S
, likewise consumes one format argument of any type and outputs it. However, ~S
tries to generate output that can be read back in with READ
. Thus, strings will be enclosed in quotation marks, symbols will be package-qualified when necessary, and so on. Objects that don't have a READ
able representation are printed with the unreadable object syntax, #<>
. With a colon modifier, both the ~A
and ~S
directives emit NIL
as ()
rather than NIL
. Both the ~A
and ~S
directives also take up to four prefix parameters, which can be used to control whether padding is added after (or before with the at-sign modifier) the value, but those parameters are only really useful for generating tabular data.
The other two most frequently used directives are ~%
, which emits a newline, and ~&
, which emits a fresh line . The difference between the two is that ~%
always emits a newline, while ~&
emits one only if it's not already at the beginning of a line. This is handy when writing loosely coupled functions that each generate a piece of output and that need to be combined in different ways. For instance, if one function generates output that ends with a newline ( ~%
) and another function generates some output that starts with a fresh line ( ~&
), you don't have to worry about getting an extra blank line if you call them one after the other. Both of these directives can take a single prefix parameter that specifies the number of newlines to emit. The ~%
directive will simply emit that many newline characters, while the ~&
directive will emit either n - 1 or n newlines, depending on whether it starts at the beginning of a line.
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.