The Marker

Functional Programming means writing programs that work by returning values, instead of modifying things. It is the dominant paradigm in Lisp. Most built-in Lisp functions are meant to be called for the values they return, not for the side-effect.

Exercises

What do these function do?

A.

(defun enigma (x)
    (and (not (null x))
        (or (null (car x))
            (enigma (cdr x)))))

Answer: detect whether a list contain a falsy value.
With python one could either use:

>>> not all(x)

Or

>>> def enigma(x):
...     return x and (not x[0] or enigma(x[1:]))

B.

>>(defun mystery (x y)
    (if (null y)
        nil
        (if (eql (car y) x)
           0
           (let ((z (mystery x (cdr y))))
              (and z (+ z 1))))))

Answer: returns the index of the value x in y
In python one could either use:

>>> y.index(x)

What could occur in place of the x in each of the following exchanges?

(a) > (car (x (cdr '(a (b c) d))))
    B
(b) >(x 13 (/ 1 0))
    13
(c) >(x #'list 1 nil)
    (1)

Answers:

(car (car (cdr '(a (b c) d))))
(or 13 (/ 1 0))
(apply #'list 1 nil)

Using only operators introduced in this chapter, define a function that takes a list as an argument and returns true if one of its elements is a list.

(defun has-list(x)
    (if (null x)
        nil
        (or (listp (car x)) (has-list (cdr x)))))

Give iterative and recursive definitions of functions that:

(a) takes a positive integer and prints that many dots.
(b) takes a list and returns then umber of times the symbol a occurs in it.

;;a:Iterative:
(defun print-dots(x)
    (do ((i 0 (+ i 1)))
        (( eql i x) (format t "~%"))
    (format t ".")))

;;a:Recursive
(defun print-dots(x)
    (if (< x 1)
        nil
        (print-dots (- x 1)))
    (format t "."))

changed January 1