# Tricks.

## Presentation on theme: "Tricks."— Presentation transcript:

Tricks

The apply-append trick
Let’s say you have a list of lists that you want to be just a list as in ‘((1 2)(3 4)(5 6)(7 8)(9 10)) Try this: (apply #’append ‘((1 2)(3 4)(5 6)(7 8)(9 10)) And you’ll get ‘( )

Apply has many tricks up its sleeve
Say you want to add together a bunch of numbers ther they’re in a list like '(1 2 3)) Try (apply #'+ '(1 2 3)) you’ll get 6

And (apply #'max '( )) 5 (apply #'min '( )) 1

You can even use + In place of cons in a recursive function as in
(defun add-em (list-o-numbers) (if (null list-o-numbers) 0 (+ (first list-o-numbers) (add-em (rest list-o-numbers)))))

Careful With some of these functions they’re used to correct mistakes that you should have done right in the first place (i.e., you shouldn’t have to use the applied-append because you should have the data prepared in the right way in the first place).

No name functions (mapcar #’(lambda (x)(reverse (rest x)))
‘((1 2 3)(4 5 6)(7 8 9))) returns ((3 2) (6 5) (9 8))

Double Recursion (RETURN-ATOMS '(((((((4))))))((3)))) (4 3)
(defun return-atoms (lists) (cond ((null lists)()) ((atom (first lists)) lists) (t (append (return-atoms (first lists)) (return-atoms (rest lists)))))) (RETURN-ATOMS '(((((((4))))))((3)))) (4 3)

Loop (loop for item in ‘(1 2 3 4 5) collect (+ item 5)) returns
( )