Reputation: 275
I'm learning scheme and when trying to use car and cdr in a very simply function I don't get the expected results:
(define test
(lambda (lst)
'((car lst).cdr (lst))))
And when running
(test '(a.b.c))
I get output:
'((car lst) .cdr (lst))
How do I make it use the car and cdr functions and not treat them like strings?
Upvotes: 0
Views: 130
Reputation: 48745
When you quote something, like '(1 2 3 4)
the result will be the data structure created at read time without any evaluation.
'((car lst) .cdr (lst))))
; ==> ((car lst) .cdr (lst)))
It does exactly what you tell it to. It's like complaining that evaluating the string "5 + 5"
doesn't give you 10
.
If you actually want the car of something you do this:
(define (test lst)
(car lst))
(test '(1 2 3)) ; ==> 1
You can make a shallow copy of a pair like this:
(define (shallow-copy pair)
(cons (car pair) (cdr pair)))
(define test-value (list 1 2 3))
(define shallow-value (shallow-copy test-value)))
(eq? test-value shallow-value) ; ==> #f
(eq? (cdr test-value) (cdr shallow-value)); ==> #t
I have no idea what your procedure supposed to do so cannot help you further.
Upvotes: 3
Reputation: 4037
The symbol '
or quote
is a procedure that creates constant.
That's why you got '((car lst) .cdr (lst))
as output, You basically calculated the string expression of ((car lst) .cdr (lst))
. Read here about it.
The correct form of what you wanted to do should be written like this:
(define test
(lambda (lst)
(list (car lst) (cdr lst))))
(test '(a b c))
The output will be a list in which the first item will be the car
of '(a b c)
which is a
and the second item will be the cdr
of '(a b c)
which is the list (b c)
.
The output will be: (a (b c))
Upvotes: 2