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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Strings
As mentioned earlier, strings in Common Lisp are really a composite data type, namely, a one-dimensional array of characters. Consequently, I'll cover many of the things you can do with strings in the next chapter when I discuss the many functions for manipulating sequences, of which strings are just one type. But strings also have their own literal syntax and a library of functions for performing string-specific operations. I'll discuss these aspects of strings in this chapter and leave the others for Chapter 11.
As you've seen, literal strings are written enclosed in double quotes. You can include any character supported by the character set in a literal string except double quote ( "
) and backslash (\). And you can include these two as well if you escape them with a backslash. In fact, backslash always escapes the next character, whatever it is, though this isn't necessary for any character except for "
and itself. Table 10-2 shows how various literal strings will be read by the Lisp reader.
Table 10-2. Literal Strings
Literal | Contents | Comment |
"foobar" |
foobar | Plain string. |
"foo\"bar" |
foo"bar | The backslash escapes quote. |
"foo\\bar" |
foo\bar | The first backslash escapes second backslash. |
"\"foobar\"" |
"foobar" | The backslashes escape quotes. |
"foo\bar" |
foobar | The backslash "escapes" b |
Note that the REPL will ordinarily print strings in readable form, adding the enclosing quotation marks and any necessary escaping backslashes, so if you want to see the actual contents of a string, you need to use function such as FORMAT
designed to print human-readable output. For example, here's what you see if you type a string containing an embedded quotation mark at the REPL:
CL-USER> "foo\"bar"
"foo\"bar"
FORMAT
, on the other hand, will show you the actual string contents: [118] Note, however, that not all literal strings can be printed by passing them as the second argument to FORMAT since certain sequences of characters have a special meaning to FORMAT . To safely print an arbitrary string—say, the value of a variable s—with FORMAT you should write (format t "~a" s).
CL-USER> (format t "foo\"bar")
foo"bar
NIL
String Comparisons
You can compare strings using a set of functions that follow the same naming convention as the character comparison functions except with STRING
as the prefix rather than CHAR
(see Table 10-3).
Table 10-3. String Comparison Functions
Numeric Analog | Case-Sensitive | Case-Insensitive |
= |
STRING= |
STRING-EQUAL |
/= |
STRING/= |
STRING-NOT-EQUAL |
< |
STRING< |
STRING-LESSP |
> |
STRING> |
STRING-GREATERP |
<= |
STRING<= |
STRING-NOT-GREATERP |
>= |
STRING>= |
STRING-NOT-LESSP |
However, unlike the character and number comparators, the string comparators can compare only two strings. That's because they also take keyword arguments that allow you to restrict the comparison to a substring of either or both strings. The arguments— :start1
, :end1
, :start2
, and :end2
—specify the starting (inclusive) and ending (exclusive) indices of substrings in the first and second string arguments. Thus, the following:
(string= "foobarbaz" "quuxbarfoo" :start1 3 :end1 6 :start2 4 :end2 7)
compares the substring "bar" in the two arguments and returns true. The :end1
and :end2
arguments can be NIL
(or the keyword argument omitted altogether) to indicate that the corresponding substring extends to the end of the string.
The comparators that return true when their arguments differ—that is, all of them except STRING=
and STRING-EQUAL
—return the index in the first string where the mismatch was detected.
(string/= "lisp" "lissome") ==> 3
If the first string is a prefix of the second, the return value will be the length of the first string, that is, one greater than the largest valid index into the string.
(string< "lisp" "lisper") ==> 4
When comparing substrings, the resulting value is still an index into the string as a whole. For instance, the following compares the substrings "bar" and "baz" but returns 5 because that's the index of the r in the first string:
(string< "foobar" "abaz" :start1 3 :start2 1) ==> 5 ; N.B. not 2
Other string functions allow you to convert the case of strings and trim characters from one or both ends of a string. And, as I mentioned previously, since strings are really a kind of sequence, all the sequence functions I'll discuss in the next chapter can be used with strings. For instance, you can discover the length of a string with the LENGTH
function and can get and set individual characters of a string with the generic sequence element accessor function, ELT
, or the generic array element accessor function, AREF
. Or you can use the string-specific accessor, CHAR
. But those functions, and others, are the topic of the next chapter, so let's move on.
11. Collections
Like most programming languages, Common Lisp provides standard data types that collect multiple values into a single object. Every language slices up the collection problem a little bit differently, but the basic collection types usually boil down to an integer-indexed array type and a table type that can be used to map more or less arbitrary keys to values. The former are variously called arrays , lists , or tuples ; the latter go by the names hash tables , associative arrays , maps , and dictionaries .
Lisp is, of course, famous for its list data structure, and most Lisp books, following the ontogeny-recapitulates-phylogeny principle of language instruction, start their discussion of Lisp's collections with lists. However, that approach often leads readers to the mistaken conclusion that lists are Lisp's only collection type. To make matters worse, because Lisp's lists are such a flexible data structure, it is possible to use them for many of the things arrays and hash tables are used for in other languages. But it's a mistake to focus too much on lists; while they're a crucial data structure for representing Lisp code as Lisp data, in many situations other data structures are more appropriate.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.