Lisp (programming Language) - Examples

Examples

Here are examples of Common Lisp code.

The basic "Hello world" program:

(print "Hello world")

Lisp syntax lends itself naturally to recursion. Mathematical problems such as the enumeration of recursively defined sets are simple to express in this notation.

Evaluate a number's factorial:

(defun factorial (n) (if (<= n 1) 1 (* n (factorial (- n 1)))))

An alternative implementation, often faster than the previous version if the Lisp system has tail recursion optimization:

(defun factorial (n &optional (acc 1)) (if (<= n 1) acc (factorial (- n 1) (* acc n))))

Contrast with an iterative version which uses Common Lisp's loop macro:

(defun factorial (n) (loop for i from 1 to n for fac = 1 then (* fac i) finally (return fac)))

The following function reverses a list. (Lisp's built-in reverse function does the same thing.)

(defun -reverse (list) (let ((return-value ')) (dolist (e list) (push e return-value)) return-value))

Read more about this topic:  Lisp (programming Language)

Famous quotes containing the word examples:

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)