1

I'm trying to explain Elisp to 5th and 6th graders and I tell them that (+ 1 2) evaluates to 3 and not (3). So if I do want something that evaluates to (3) would I just evaluate ((+ 1 2))? No! This gives the error message Lisp error: (invalid-function (+ 1 2)), which I explain by saying any list must have a function in the first element position, and having (+ 1 2) in the first position is not a function. Good. But again, how to get a result (3)? If I try (list (+ 1 2)) I do in fact get (3). Why does list evaluate (+ 1 2) then create the list containing 3? quote doesn't -- and, no, it shouldn't. (function (+ 1 2)) gives (+ 1 2). As I understand,list is just syntactic sugar for (cons (+ 1 2) '()). Is this true? Can anyone explain some of the details of what I'm experiencing here -- or point me to a good explanation?

4

+1 for teaching Lisp to 5th graders. And have fun! Lisp, like Logo, is good for kids.


Your question is a bit rambling. (Emacs.SE is not a place for tutorials or discussions - it's really for specific Q & A.)

I recommend that you take a look at the manual An Introduction to Programming in Emacs Lisp, by using C-h i and choosing Emacs Lisp Intro. Work your way through it. (Then maybe do likewise with your 5th graders.) You won't regret it.


This is false: "any list must have a function in the first element position".

If you evaluate a list that doesn't have a function as its car then an error is raised. But lists that do not have a function as their car certainly exist. (3) is one such example.


Anyway, the answer to your question is that function list conses up its arguments, with nil as the last cdr. So yes, (list (+ 1 2)) is equivalent to (cons (+ 1 2) ()). It's generally more convenient to write (list a b c) than to write (cons a (cons b (cons c nil))).

It's not about being syntactic sugar. Both list and cons are full-fledged Lisp functions. It's not important how they might be implemented (e.g. in C code).

  • My specific question would be, Why does cons and list evaluate `(+ 1 2), then put the result in a list? In my presentation, I am trying to get across the uniqueness of building a language out of lists. This is one confusing aspect, i.e., why are some things evaluated, value returned, and others not? – 147pm Nov 19 at 19:14
  • 1
    Functions in Elisp always evaluate their arguments. (Macros and special forms don't necessarily do that, and yes, sometimes we call those "functions" too, which I did when I said that an error is raised when you evaluate a list that doesn't have a "function" as its car.) cons and list are not macros or special forms - they evaluate their arguments. You will do yourself, and your students, a favor by reading the Intro to Elisp manual. – Drew Nov 19 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.