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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
(open "/some/file/name.txt" :direction :output :if-exists :supersede)
Common Lisp also provides several functions for writing data: WRITE-CHAR
writes a single character to the stream. WRITE-LINE
writes a string followed by a newline, which will be output as the appropriate end-of-line character or characters for the platform. Another function, WRITE-STRING
, writes a string without adding any end-of-line characters. Two different functions can print just a newline: TERPRI
—short for "terminate print"—unconditionally prints a newline character, and FRESH-LINE
prints a newline character unless the stream is at the beginning of a line. FRESH-LINE
is handy when you want to avoid spurious blank lines in textual output generated by different functions called in sequence. For example, suppose you have one function that generates output that should always be followed by a line break and another that should start on a new line. But assume that if the functions are called one after the other, you don't want a blank line between the two bits of output. If you use FRESH-LINE
at the beginning of the second function, its output will always start on a new line, but if it's called right after the first, it won't emit an extra line break.
Several functions output Lisp data as s-expressions: PRINT
prints an s-expression preceded by an end-of-line and followed by a space. PRIN1
prints just the s-expression. And the function PPRINT
prints s-expressions like PRINT
and PRIN1
but using the "pretty printer," which tries to print its output in an aesthetically pleasing way.
However, not all objects can be printed in a form that READ
will understand. The variable *PRINT-READABLY*
controls what happens if you try to print such an object with PRINT
, PRIN1
, or PPRINT
. When it's NIL
, these functions will print the object in a special syntax that's guaranteed to cause READ
to signal an error if it tries to read it; otherwise they will signal an error rather than print the object.
Another function, PRINC
, also prints Lisp objects, but in a way designed for human consumption. For instance, PRINC
prints strings without quotation marks. You can generate more elaborate text output with the incredibly flexible if somewhat arcane FORMAT
function. I'll discuss some of the more important details of FORMAT
, which essentially defines a mini-language for emitting formatted output, in Chapter 18.
To write binary data to a file, you have to OPEN
the file with the same :element-type
argument as you did to read it: '(unsigned-byte 8)
. You can then write individual bytes to the stream with WRITE-BYTE
.
The bulk output function WRITE-SEQUENCE
accepts both binary and character streams as long as all the elements of the sequence are of an appropriate type for the stream, either characters or bytes. As with READ-SEQUENCE
, this function is likely to be quite a bit more efficient than writing the elements of the sequence one at a time.
Closing Files
As anyone who has written code that deals with lots of files knows, it's important to close files when you're done with them, because file handles tend to be a scarce resource. If you open files and don't close them, you'll soon discover you can't open any more files. [155] Some folks expect this wouldn't be a problem in a garbage-collected language such as Lisp. It is the case in most Lisp implementations that a stream that becomes garbage will automatically be closed. However, this isn't something to rely on—the problem is that garbage collectors usually run only when memory is low; they don't know about other scarce resources such as file handles. If there's plenty of memory available, it's easy to run out of file handles long before the garbage collector runs.
It might seem straightforward enough to just be sure every OPEN
has a matching CLOSE
. For instance, you could always structure your file using code like this:
(let ((stream (open "/some/file/name.txt")))
;; do stuff with stream
(close stream))
However, this approach suffers from two problems. One is simply that it's error prone—if you forget the CLOSE
, the code will leak a file handle every time it runs. The other—and more significant—problem is that there's no guarantee you'll get to the CLOSE
. For instance, if the code prior to the CLOSE
contains a RETURN
or RETURN-FROM
, you could leave the LET
without closing the stream. Or, as you'll see in Chapter 19, if any of the code before the CLOSE
signals an error, control may jump out of the LET
to an error handler and never come back to close the stream.
Common Lisp provides a general solution to the problem of how to ensure that certain code always runs: the special operator UNWIND-PROTECT
, which I'll discuss in Chapter 20. However, because the pattern of opening a file, doing something with the resulting stream, and then closing the stream is so common, Common Lisp provides a macro, WITH-OPEN-FILE
, built on top of UNWIND-PROTECT
, to encapsulate this pattern. This is the basic form:
(with-open-file ( stream-var open-argument* )
body-form* )
The forms in body-forms are evaluated with stream-var bound to a file stream opened by a call to OPEN
with open-arguments as its arguments. WITH-OPEN-FILE
then ensures the stream in stream-var is closed before the WITH-OPEN-FILE
form returns. Thus, you can write this to read a line from a file:
(with-open-file (stream "/some/file/name.txt")
(format t "~a~%" (read-line stream)))
To create a new file, you can write something like this:
(with-open-file (stream "/some/file/name.txt" :direction :output)
(format stream "Some text."))
You'll probably use WITH-OPEN-FILE
for 90-99 percent of the file I/O you do—the only time you need to use raw OPEN
and CLOSE
calls is if you need to open a file in a function and keep the stream around after the function returns. In that case, you must take care to eventually close the stream yourself, or you'll leak file descriptors and may eventually end up unable to open any more files.
Filenames
So far you've used strings to represent filenames. However, using strings as filenames ties your code to a particular operating system and file system. Likewise, if you programmatically construct names according to the rules of a particular naming scheme (separating directories with /, say), you also tie your code to a particular file system.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.