List evaluation in LISP (strange behaviour of cons)
Domanda
I am currently playing around with LISP. Everything is fine, but I can't understand the following issue.
I have the this append-operation:
(define (append l1 l2)
(if (eq? l1 null)
l2
(cons (first l1)
(myappend (rest l1) l2))))
I use it like this:
(myappend (cons (cons 1 2) null) '(4 5))
And the result in Racket is:
'((1 . 2) 4 5)
But why? In my oppinion it should be '(1 2 4 5), because cons returns a list and myappends appends two lists. Can anybody help me? What is LISP doing?
Soluzione
cons
returns a dotted pair, not necessarily a list.
(cons 1 2)
returns (1 . 2)
(cons 1 null)
returns (1)
(cons 1 (cons 2 null))
returns (1 2)
Altri suggerimenti
A (cons 1 2)
will return an object whose first pointer (car
) points to 1, and the other (cdr
) points to 2, that's why it get printed in the dot-pair fashion.
Also you may want to understand deeper, I will recommend you read the CL: gentle introduction to symbolic computation, "6.4. Comparing CONS, LIST, AND APPEND", which explained these topics really well.
Try what (cons 1 2) returns. Is it a list?
to @ThomasUhrig : the following info might help you.
Although we are talking about Lisp language here, I notice that a line from Page 8 and 9 of a famous Book named "The Little Schemer (4th edition)" help me understand the 2 puzzling facts altogether:
Why (cons 1 2) does not look like '(1 2)?
Why (cons 1 '(2)) does look like '(1 2)?
----
> (cons 1 2)
(1 . 2)
> (cons 1 '(2))
(1 2)
> '(1 2)
(1 2)
Just read the "The Laws of Cons":
The primitive
cons
takes 2 arguments.The 2nd argument to
cons
must be a list.The result is a list.
In practice: (cons A B) works for all values A and B, And
(car (cons A B)) = A
(cdr (cons A B)) = B