First, I assume you are using Common Lisp, as it is most often used in Lisp courses. So my examples will be in CL. If you use Scheme, you will get almost the same code. If modern Clojure, he will need some changes, through the idea will be the same.
Alternation
To alternate 2 lists, you must go through both of them, collecting items in turn. You can use a loop operator or recursion for this. I will use recursion because it has a more functional style and can be used in any Lisp, and not just in the CL. Also note that there is a tail recursion function that allows you to write a recursive function to be compiled in a loop.
Thus, the basic skeleton for our function will be:
(defun interleave (l1 l2)
??????
(interleave ?????))
, , ( , ). , (cons current-value (interleave ????)).
, . , . , :
(defun interleave (l1 l2)
?????
(cons current-value (interleave l2 l1)))
-. , (nil).
( 1), :
2. , , , , .
3. , .
, 2 : , , , . № 3.
, ( ):
(defun interleave (l1 l2)
(cond ((and (eql l1 nil) (eql l2 nil)) nil) ;; rule
((eql l1 nil) (cons nil (interleave l2 l1))) ;; rule
(true (cons (first l1) (interleave l2 (rest l1)))))) ;; rule
Reverse
: cond reduce, .
cond , , , :
(defun reverse-1-1 (li)
(if (eql li nil)
nil
(append (reverse-1-1 (rest li))
(list (first li)))))
, append O (n), n , - O ( ^ 2).
, ( , ):
(defun reverse-1-2 (li)
(reverse-aux li nil))
(defun reverse-aux (li accumulator)
(if (eql li nil)
accumulator
(reverse-aux (rest li) (cons (first li) accumulator))))
, .
. Lisp reduce ( fold, foldr, foldl - ). , :
(defun reverse-2 (li)
(reduce
:from-end , , : initial-value , nil.
: :from-end true , , , reverse-1-2.