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

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

Интервал:

Закладка:

Сделать

After the initiallyor finally, these clauses consist of all the Lisp forms up to the start of the next loop clause or the end of the loop. All the initiallyforms are combined into a single prologue , which runs once, immediately after all the local loop variables are initialized and before the body of the loop. The finallyforms are similarly combined into a epilogue to be run after the last iteration of the loop body. Both the prologue and epilogue code can refer to local loop variables.

The prologue is always run, even if the loop body iterates zero times. The loop can return without running the epilogue if any of the following happens:

• A returnclause executes.

RETURN , RETURN-FROM , or another transfer of control construct is called from within a Lisp form within the body. [243] You can cause a loop to finish normally, running the epilogue, from Lisp code executed as part of the loop body with the local macro LOOP-FINISH .

• The loop is terminated by an always, never, or thereisclause, as I'll discuss in the next section.

Within the epilogue code, RETURN or RETURN-FROM can be used to explicitly provide a return value for the loop. Such an explicit return value will take precedence over any value that might otherwise be provided by an accumulation or termination test clause.

To allow RETURN-FROM to be used to return from a specific loop (useful when nesting LOOP expressions), you can name a LOOP with the loop keyword named. If a namedclause appears in a loop, it must be the first clause. For a simple example, assume listsis a list of lists and you want to find an item that matches some criteria in one of those nested lists. You could find it with a pair of nested loops like this:

(loop named outer for list in lists do

(loop for item in list do

(if (what-i-am-looking-for-p item)

(return-from outer item))))

Termination Tests

While the forand repeatclauses provide the basic infrastructure for controlling the number of iterations, sometimes you'll need to break out of a loop early. You've already seen how a returnclause or a RETURN or RETURN-FROM within a doclause can immediately terminate the loop; but just as there are common patterns for accumulating values, there are also common patterns for deciding when it's time to bail on a loop. These patterns are supported in LOOP by the termination clauses, while, until, always, never, and thereis. They all follow the same pattern.

loop-keyword test-form

All five evaluate test-form each time through the iteration and decide, based on the resulting value, whether to terminate the loop. They differ in what happens after they terminate the loop—if they do—and how they decide.

The loop keywords whileand untilintroduce the "mild" termination clauses. When they decide to terminate the loop, control passes to the epilogue, skipping the rest of the loop body. The epilogue can then return a value or do whatever it wants to finish the loop. A whileclause terminates the loop the first time the test form is false; until, conversely, stops it the first time the test form is true.

Another form of mild termination is provided by the LOOP-FINISH macro. This is a regular Lisp form, not a loop clause, so it can be used anywhere within the Lisp forms of a doclause. It also causes an immediate jump to the loop epilogue. It can be useful when the decision to break out of the loop can't be easily condensed into a single form that can be used with a whileor untilclause.

The other three clauses— always, never, and thereis—terminate the loop with extreme prejudice; they immediately return from the loop, skipping not only any subsequent loop clauses but also the epilogue. They also provide a default value for the loop even when they don't cause the loop to terminate. However, if the loop is not terminated by one of these termination tests, the epilogue is run and can return a value other than the default provided by the termination clauses.

Because these clauses provide their own return values, they can't be combined with accumulation clauses unless the accumulation clause has an intosubclause. The compiler (or interpreter) should signal an error at compile time if they are.The alwaysand neverclauses return only boolean values, so they're most useful when you need to use a loop expression as part of a predicate. You can use alwaysto check that the test form is true on every iteration of the loop. Conversely, nevertests that the test form evaluates to NIL on every iteration. If the test form fails (returning NIL in an alwaysclause or non- NIL in a neverclause), the loop is immediately terminated, returning NIL . If the loop runs to completion, the default value of T is provided.

For instance, if you want to test that all the numbers in a list, numbers, are even, you can write this:

(if (loop for n in numbers always (evenp n))

(print "All numbers even."))

Equivalently you could write the following:

(if (loop for n in numbers never (oddp n))

(print "All numbers even."))

A thereisclause is used to test whether the test form is ever true. As soon as the test form returns a non- NIL value, the loop is terminated, returning that value. If the loop runs to completion, the thereisclause provides a default return value of NIL .

(loop for char across "abc123" thereis (digit-char-p char)) ==> 1

(loop for char across "abcdef" thereis (digit-char-p char)) ==> NIL

Putting It All Together

Now you've seen all the main features of the LOOP facility. You can combine any of the clauses I've discussed as long as you abide by the following rules:

• The namedclause, if any, must be the first clause.

• After the namedclause come all the initially, with, for, and repeatclauses.

• Then comes the body clauses: conditional and unconditional execution, accumulation, and termination test. [244] Some Common Lisp implementations will let you get away with mixing body clauses and for clauses, but that's strictly undefined, and some implementations will reject such loops.

• End with any finallyclauses.

The LOOP macro will expand into code that performs the following actions:

• Initializes all local loop variables as declared with withor forclauses as well as those implicitly created by accumulation clauses. The initial value forms are evaluated in the order the clauses appear in the loop.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x