Reputation: 61
Is there any way by which cons
can be implemented in Common LISP using list
, append
, first
, rest
etc?
In the following code
(defun my_list (&rest arguments)
`(,@arguments) ; Line 1
)
What does complete line 1 mean ?
Upvotes: 3
Views: 1605
Reputation: 65854
Yes, you could in theory define cons
in terms of list
and append
, like so:
(defun cons (car cdr) (append (list car) cdr))
Upvotes: 1
Reputation: 1228
I have the answer for the second question:
for the ,:
if my_symbol = 1
`(my_symbol 2 3) = (my_symbol 2 3)
, but with the ,:
`(,my_symbol 2 3) = (1 2 3)
The , evaluates the next symbol in a ` statement
Now for the @ (which is a symbol, so it needs the , to be activated)
`(,@('a 'b 'c) ('d 'e 'f)) = ('a 'b 'c ('d 'e 'f) )
`(,@('a 'b 'c) ,@('d 'e 'f) ) = ('a 'b 'c 'd 'e 'f)
I hope these examples could help. So the line 1 is simply extracting the arguments from a list and putting them into another one.
Upvotes: 0
Reputation: 51501
First question: No, because cons
is the building block for list
and append
, not the other way around. It is like trying to construct a brick out of houses.
Second question: The backquote syntax is explained in the CLHS (http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/sec_2-4-6.html).
Stylistic comments:
It is spelt "Common Lisp".
Do not use underscores to separate parts of names, but hyphens: my-list
.
Do not let parentheses dangle around. Your snippet should be formatted like this:
(defun my-list (&rest arguments)
`(,@arguments)) ; Line 1
Using the backquote syntax outside of macros is usually not a good idea. In this case, it is completely superfluous:
(defun my-list (&rest arguments)
arguments)
Upvotes: 6
Reputation: 25729
How about this?
(defun cons (a b) '(a . b))
Or, if you desperately need to use lists...
(defun cons (a b) (first (list '(a . b))))
Upvotes: -1