Time for some basic Emacs Lisp datastructures. Are you ready? Ok, let’s go!

List, cons, car and cdr

We start slowly. You can create a list in emacs with the list function

(list "hello")

That is a list with one item. You can create the same list like this

'("hello") ;same as (list "hello")

The ' in the start of expression means that the expression should not be evaluated, and everything inside parenthesis is a list in lisp.

Lists in Emacs are built up from something that is called “cons cells”. The list above is actually a cons cell with the two objects "hello" and nil. You can create cons cells with the cons function.

(cons "hello" nil) ; the same as '("hello")

The two slots that a cons is made up of is called car and cdr. In the example above, "hello" is the car slot and nil is the cdr slot. You can access the car slot with the function car.

(car (cons "hello" nil)) ; evaluates to "hello"

There is also a cdr function, try it out yourself! To create a list with more items you create a linked list of cons cells, like this:

(cons "hello" (cons "world" nil)) ; same as '("hello" "world")

Dotted pair notation and alist

Another way to create a cons cell is with the “dotted pair notation”.

'("hello" . nil) ; same as (cons "hello" nil)

You can create a linked list with the dotted pair notation

'("hello" . ("world" . nil)) ; same as '("hello" "world")

You can also create a data structure that maps any key to any value with the dotted pair notation:

'(("mykey" . 1) (anotherkey . 2))

If you come from a Javascript your a Java background you can think of this as an object or a hash map. This Emacs Lisp this is called an “associative list” or alist. To get a cons cell from a key you can use the assoc function.

(assoc 'anotherkey '(("mykey" . 1) (anotherkey . 2))) ; this evaluates to (anotherkey . 2)

There are more functions that operates on associative lists. You can read about them in the docs

Summary

  • You can use a list as a list, but you can also use a list as a map!
  • Everything inside parenthesis is a list, but the list is evaluated unless you prepend it with '
  • If you want to call a function and put the result in a list you cannot use ', but you have to use for example list, or cons.