I'm new on lisp and I'm finding a difficulty while working with "append
". I have to reorder a list and put the first element of the input list as the last of the output list. I've trying with "append
" and "nconc
", and any time I get the list I want, but with a ".
" before the last element. What this dot means? Is there any way to avoid this symbol to appear?
Thanks a lot!
(nconc (rest l) (first l)) >> (B C D E . A)
(append (rest l) (first l)) >> (B C D E . A)
At the most basic level, lists are created with a series of cons
calls:
(cons 1 2 ) ; (1 . 2)
(cons 1 (cons 2 NIL)) ; (1 2 . NIL) = (1 2)
(cons 1 (cons 2 3 )) ; (1 2 . 3)
(cons 1 (cons 2 (cons 3 NIL))) ; (1 2 3 . NIL) = (1 2 3)
NIL
is the special marker to signal the end of a list. Hence, the NIL
after the .
can just disappear together with the .
. But with any other atom after the .
, it can't.
append
is a higher-level function, which appends two lists:
; l = (1 2 3)
(append (rest l) (first l))
=
(cons 2 (cons 3 1))
=
( 2 3 . 1)
This is so because first l
element here is not a list.(*) But we can make a list out of it:
; l = (1 2 3)
(append (rest l) (list (first l)))
=
(cons 2 (cons 3 (list 1)))
=
(cons 2 (cons 3 (cons 1 NIL)))
=
( 2 3 1 . NIL )
=
( 2 3 1 )
nconc
in this respect is just like append
.
(*) nor is it NIL
in which case it will get treated as the end of list marker, and disappear together with the dot. Which shows that NIL
is an empty list, too:
; l = (NIL 2 3)
(append (rest l) (first l))
=
(cons 2 (cons 3 NIL))
=
( 2 3 . NIL )
=
( 2 3 )
; l = ((0 1) 2 3)
(append (rest l) (first l))
=
(cons 2 (cons 3 (list 0 1)))
=
( 2 3 . (0 1) )
=
( 2 3 0 1 )