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

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

Интервал:

Закладка:

Сделать

Numbers with no exponent marker are read in the default representation and must contain a decimal point followed by at least one digit to distinguish them from integers. The digits in a floating-point number are always treated as base 10 digits—the #B, #X, #O, and #Rsyntaxes work only with rationals. The following are some example floating-point numbers along with their canonical representation:

1.0 ==> 1.0

1e0 ==> 1.0

1d0 ==> 1.0d0

123.0 ==> 123.0

123e0 ==> 123.0

0.123 ==> 0.123

.123 ==> 0.123

123e-3 ==> 0.123

123E-3 ==> 0.123

0.123e20 ==> 1.23e+19

123d23 ==> 1.23d+25

Finally, complex numbers are written in their own syntax, namely, #Cor #cfollowed by a list of two real numbers representing the real and imaginary part of the complex number. There are actually five kinds of complex numbers because the real and imaginary parts must either both be rational or both be the same kind of floating-point number.

But you can write them however you want—if a complex is written with one rational and one floating-point part, the rational is converted to a float of the appropriate representation. Similarly, if the real and imaginary parts are both floats of different representations, the one in the smaller representation will be upgraded .

However, no complex numbers have a rational real component and a zero imaginary part—since such values are, mathematically speaking, rational, they're represented by the appropriate rational value. The same mathematical argument could be made for complex numbers with floating-point components, but for those complex types a number with a zero imaginary part is always a different object than the floating-point number representing the real component. Here are some examples of numbers written the complex number syntax:

#c(2 1) ==> #c(2 1)

#c(2/3 3/4) ==> #c(2/3 3/4)

#c(2 1.0) ==> #c(2.0 1.0)

#c(2.0 1.0d0) ==> #c(2.0d0 1.0d0)

#c(1/2 1.0) ==> #c(0.5 1.0)

#c(3 0) ==> 3

#c(3.0 0.0) ==> #c(3.0 0.0)

#c(1/2 0) ==> 1/2

#c(-6/3 0) ==> -2

Basic Math

The basic arithmetic operations—addition, subtraction, multiplication, and division—are supported for all the different kinds of Lisp numbers with the functions + , - , * , and / . Calling any of these functions with more than two arguments is equivalent to calling the same function on the first two arguments and then calling it again on the resulting value and the rest of the arguments. For example, (+ 1 2 3)is equivalent to (+ (+ 1 2) 3). With only one argument, + and * return the value; - returns its negation and / its reciprocal. [115] For mathematical consistency, + and * can also be called with no arguments, in which case they return the appropriate identity: 0 for + and 1 for * .

(+ 1 2) ==> 3

(+ 1 2 3) ==> 6

(+ 10.0 3.0) ==> 13.0

(+ #c(1 2) #c(3 4)) ==> #c(4 6)

(- 5 4) ==> 1

(- 2) ==> -2

(- 10 3 5) ==> 2

(* 2 3) ==> 6

(* 2 3 4) ==> 24

(/ 10 5) ==> 2

(/ 10 5 2) ==> 1

(/ 2 3) ==> 2/3

(/ 4) ==> 1/4

If all the arguments are the same type of number (rational, floating point, or complex), the result will be the same type except in the case where the result of an operation on complex numbers with rational components yields a number with a zero imaginary part, in which case the result will be a rational. However, floating-point and complex numbers are contagious —if all the arguments are reals but one or more are floating-point numbers, the other arguments are converted to the nearest floating-point value in a "largest" floating-point representation of the actual floating-point arguments. Floating-point numbers in a "smaller" representation are also converted to the larger representation. Similarly, if any of the arguments are complex, any real arguments are converted to the complex equivalents.

(+ 1 2.0) ==> 3.0

(/ 2 3.0) ==> 0.6666667

(+ #c(1 2) 3) ==> #c(4 2)

(+ #c(1 2) 3/2) ==> #c(5/2 2)

(+ #c(1 1) #c(2 -1)) ==> 3

Because / doesn't truncate, Common Lisp provides four flavors of truncating and rounding for converting a real number (rational or floating point) to an integer: FLOOR truncates toward negative infinity, returning the largest integer less than or equal to the argument. CEILING truncates toward positive infinity, returning the smallest integer greater than or equal to the argument. TRUNCATE truncates toward zero, making it equivalent to FLOOR for positive arguments and to CEILING for negative arguments. And ROUND rounds to the nearest integer. If the argument is exactly halfway between two integers, it rounds to the nearest even integer.

Two related functions are MOD and REM , which return the modulus and remainder of a truncating division on real numbers. These two functions are related to the FLOOR and TRUNCATE functions as follows:

(+ (* (floor (/ x y)) y) (mod x y)) === x

(+ (* (truncate (/ x y)) y) (rem x y)) === x

Thus, for positive quotients they're equivalent, but for negative quotients they produce different results. [116] Roughly speaking, MOD is equivalent to the % operator in Perl and Python, and REM is equivalent to the % in C and Java. (Technically, the exact behavior of % in C wasn't specified until the C99 standard.)

The functions 1+ and 1- provide a shorthand way to express adding and subtracting one from a number. Note that these are different from the macros INCF and DECF . 1+ and 1- are just functions that return a new value, but INCF and DECF modify a place. The following equivalences show the relation between INCF / DECF , 1+ / 1- , and + / - :

(incf x) === (setf x (1+ x)) === (setf x (+ x 1))

(decf x) === (setf x (1- x)) === (setf x (- x 1))

(incf x 10) === (setf x (+ x 10))

(decf x 10) === (setf x (- x 10))

Numeric Comparisons

The function = is the numeric equality predicate. It compares numbers by mathematical value, ignoring differences in type. Thus, = will consider mathematically equivalent values of different types equivalent while the generic equality predicate EQL would consider them inequivalent because of the difference in type. (The generic equality predicate EQUALP , however, uses = to compare numbers.) If it's called with more than two arguments, it returns true only if they all have the same value. Thus:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x