Corman Common Lisp 3.0Version of implementation Corman Common Lisp of programming language Lisp
Key features of version 3.0:
- Improved math and numeric code performance and stability.
- Added integration with .NET.
- Numerous bug fixes and minor changes in kernel functions, garbage collection, ANSI compatibility etc.
- IDE improvements.
This example uses recursive definition of Fibonacci numbers and expands use of
loop macro to
finally clause (expression evaluated after the loop is done).
(defun fibonacci (n) (if (< n 3) 1 (+ (fibonacci (- n 1)) (fibonacci (- n 2))) ) ) (loop for i from 1 to 16 do (format t "~D, " (fibonacci i)) finally (format t "...~%") )
This example uses iterative definition of Fibonacci numbers, though expressed through recursive calls of
(defun fibonacci (n) (defun fib-iter (a b count) (if (zerop count) b (fib-iter (+ a b) a (- count 1)) ) ) (fib-iter 1 0 n) ) (loop for i from 1 to 16 do (format t "~D, " (fibonacci i)) finally (format t "...~%") )
When executed in interactive mode, program output looks as follows:
First line contains standard output, second — the result of expression evaluation (in this case there is none).
(format t "Hello, World!~%")
This example uses recursive factorial definition (which is natural for Lisp). Features:
(- n 1)is prefix notation equivalent to
n-1in infix notation;
(= n 0)evaluates to
Tif n is zero, and to
nil(used as false) otherwise;
if: Lisp expressions are evaluated using brackets, so they can be written in several lines;
function definition using
Common Lisp macro
format specifiers in
~Dcorresponds to printing an integer, and
(defun factorial (n) (if (= n 0) 1 (* n (factorial (- n 1))) ) ) (loop for i from 0 to 16 do (format t "~D! = ~D~%" i (factorial i)) )
Common Lisp provides complex numbers as datatype, printed as
write-to-string converts a number into a string.
Note that for interactive evaluation it’s enough to add
(quadratic-roots-2 1 0 1) to see the result of calculation, while for compiled execution you’ll have to wrap call of this function in printing command, like
(format t (quadratic-roots-2 1 0 1)).
(defun quadratic-roots-2 (A B C) (cond ((= A 0) (string "Not a quadratic equation.")) (t (let ((D (- (* B B) (* 4 A C)))) (cond ((= D 0) (concatenate 'string "x = " (write-to-string (/ (+ (- B) (sqrt D)) (* 2 A))))) (t (values (concatenate 'string "x1 = " (write-to-string (/ (+ (- B) (sqrt D)) (* 2 A)))) (concatenate 'string "x2 = " (write-to-string (/ (- (- B) (sqrt D)) (* 2 A)))))))))))
(defun camel-case (s) (remove #\Space (string-capitalize (substitute #\Space nil s :key #'alpha-char-p)))) (princ (camel-case (read-line)))
In this example the inner loop with
collect clause produces a list of numbers from 1 to
n. After this operation
* is applied to this list, and the product of the numbers is printed.
(loop for n from 0 to 16 do (format t "~D! = ~D~%" n (apply '* (loop for i from 1 to n collect i)) ) )