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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
CL-USER> (add-record (make-cd "Fly" "Dixie Chicks" 8 t))
((:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T)
(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T))
CL-USER> (add-record (make-cd "Home" "Dixie Chicks" 9 t))
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T)
(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T))
The stuff printed by the REPL after each call to add-record
is the return value, which is the value returned by the last expression in the function body, the PUSH
. And PUSH
returns the new value of the variable it's modifying. So what you're actually seeing is the value of the database after the record has been added.
Looking at the Database Contents
You can also see the current value of *db*
whenever you want by typing *db*
at the REPL.
CL-USER> *db*
((:TITLE "Home" :ARTIST "Dixie Chicks" :RATING 9 :RIPPED T)
(:TITLE "Fly" :ARTIST "Dixie Chicks" :RATING 8 :RIPPED T)
(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T))
However, that's not a very satisfying way of looking at the output. You can write a dump-db
function that dumps out the database in a more human-readable format, like this:
TITLE: Home
ARTIST: Dixie Chicks
RATING: 9
RIPPED: T
TITLE: Fly
ARTIST: Dixie Chicks
RATING: 8
RIPPED: T
TITLE: Roses
ARTIST: Kathy Mattea
RATING: 7
RIPPED: T
The function looks like this:
(defun dump-db ()
(dolist (cd *db*)
(format t "~{~a:~10t~a~%~}~%" cd)))
This function works by looping over all the elements of *db*
with the DOLIST
macro, binding each element to the variable cd
in turn. For each value of cd
, you use the FORMAT
function to print it.
Admittedly, the FORMAT
call is a little cryptic. However, FORMAT
isn't particularly more complicated than C or Perl's printf
function or Python's string- %
operator. In Chapter 18 I'll discuss FORMAT
in greater detail. For now we can take this call bit by bit. As you saw in Chapter 2, FORMAT
takes at least two arguments, the first being the stream where it sends its output; t
is shorthand for the stream *standard-output*
.
The second argument to FORMAT
is a format string that can contain both literal text and directives telling FORMAT
things such as how to interpolate the rest of its arguments. Format directives start with ~
(much the way printf
's directives start with %
). FORMAT
understands dozens of directives, each with their own set of options. [26] One of the coolest FORMAT directives is the ~R directive. Ever want to know how to say a really big number in English words? Lisp knows. Evaluate this: (format nil "~r" 1606938044258990275541962092) and you should get back (wrapped for legibility): "one octillion six hundred six septillion nine hundred thirty-eight sextillion forty-four quintillion two hundred fifty-eight quadrillion nine hundred ninety trillion two hundred seventy-five billion five hundred forty-one million nine hundred sixty-two thousand ninety-two"
However, for now I'll just focus on the ones you need to write dump-db
.
The ~a
directive is the aesthetic directive; it means to consume one argument and output it in a human-readable form. This will render keywords without the leading : and strings without quotation marks. For instance:
CL-USER> (format t "~a" "Dixie Chicks")
Dixie Chicks
NIL
or:
CL-USER> (format t "~a" :title)
TITLE
NIL
The ~t
directive is for tabulating. The ~10t
tells FORMAT
to emit enough spaces to move to the tenth column before processing the next ~a
. A ~t
doesn't consume any arguments.
CL-USER> (format t "~a:~10t~a" :artist "Dixie Chicks")
ARTIST: Dixie Chicks
NIL
Now things get slightly more complicated. When FORMAT
sees ~{
the next argument to be consumed must be a list. FORMAT
loops over that list, processing the directives between the ~{
and ~
}, consuming as many elements of the list as needed each time through the list. In dump-db
, the FORMAT
loop will consume one keyword and one value from the list each time through the loop. The ~%
directive doesn't consume any arguments but tells FORMAT
to emit a newline. Then after the ~
} ends the loop, the last ~%
tells FORMAT
to emit one more newline to put a blank line between each CD.
Technically, you could have also used FORMAT
to loop over the database itself, turning our dump-db
function into a one-liner.
(defun dump-db ()
(format t "~{~{~a:~10t~a~%~}~%~}" *db*))
That's either very cool or very scary depending on your point of view.
Improving the User Interaction
While our add-record
function works fine for adding records, it's a bit Lispy for the casual user. And if they want to add a bunch of records, it's not very convenient. So you may want to write a function to prompt the user for information about a set of CDs. Right away you know you'll need some way to prompt the user for a piece of information and read it. So let's write that.
(defun prompt-read (prompt)
(format *query-io* "~a: " prompt)
(force-output *query-io*)
(read-line *query-io*))
You use your old friend FORMAT
to emit a prompt. Note that there's no ~%
in the format string, so the cursor will stay on the same line. The call to FORCE-OUTPUT
is necessary in some implementations to ensure that Lisp doesn't wait for a newline before it prints the prompt.
Then you can read a single line of text with the aptly named READ-LINE
function. The variable *query-io*
is a global variable (which you can tell because of the *
naming convention for global variables) that contains the input stream connected to the terminal. The return value of prompt-read
will be the value of the last form, the call to READ-LINE
, which returns the string it read (without the trailing newline.)
You can combine your existing make-cd
function with prompt-read
to build a function that makes a new CD record from data it gets by prompting for each value in turn.
(defun prompt-for-cd ()
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.