Lists

Basics

Lists can be built using the list function:

CL-USER>(list123)(123)

You can use first, second, and all the way up to tenth to access the corresponding elements of a list:

CL-USER>(first(list123))1CL-USER>(second(list123))2

These can also be used to set elements:

CL-USER>(defparametermy-list(list123))MY-LISTCL-USER>(setf(secondmy-list)7)7CL-USER>my-list(173)

More generally, the nth function can be used:

CL-USER>(nth1(list123))2

And it works with setf:

CL-USER>(defparametermy-list(list123))MY-LISTCL-USER>(setf(nth1my-list)65)65CL-USER>my-list(1653)

Higher-Order Functions

Map

The map function takes a function and a list, goes through each element in the sequence, and returns a new list where every element is the result of calling that function with the original element.

For instance:

CL-USER>(mapcar#'evenp(list123456))(NILTNILTNILT)

Is equivalent to:

CL-USER>(list(evenp1)(evenp2)(evenp3)(evenp4)(evenp5)(evenp6))(NILTNILTNILT)

Another example:

CL-USER>(mapcar#'string-upcase(list"Hello""world!"))("HELLO""WORLD!")

One way to help understand mapcar is by writing our own:

CL-USER> (defun my-map (function list) (if list (cons (funcall function (first list)) (my-map function (rest list))) nil)) MY-MAP CL-USER> (my-map #'string-upcase (list "a" "b" "c")) ("A" "B" "C") 

Reduce

The reduce function can be used to turn a list into a scalar, by applying a function on successive subsets of the list. For instance:

CL-USER>(reduce#'+(list123))6

You can also use a custom function:

CL-USER>(reduce#'(lambda(ab)(*ab))(list102030))6000

The above is equivalent to (* (* 10 20) 30). To get a better understanding of how reduce works, we can use format:

CL-USER>(reduce#'(lambda(ab)(formatt"A: ~A, B: ~A~%"ab)(*ab))(list123456))A:1,B:2A:2,B:3A:6,B:4A:24,B:5A:120,B:6720

Sorting

The sort function allows you to sort a sequence:

CL-USER>(sort(list9247308)#'<)(0234789)

Destructuring

(defundestructure(list)(destructuring-bind(firstsecond&restothers)list(formatt"First: ~A~%"first)(formatt"Second: ~A~%"second)(formatt"Rest: ~A~%"others)))

This produces:

CL-USER>(destructure(list123456))First:1Second:2Rest:(3456)NIL
close