I'm attempting to concatenate lists in scheme using fold-left and append (for usage in a bigger function). However, I keep getting outputs that look like this:
=> (0 quote (1) quote (2))
This is my code:
(fold-left (lambda(a b) (append a b)) '(0) '('(1) '(2)))
Why wouldn't this work exactly the same as:
(define x (append '(0) '(1)))
(define y (append x '(2)))
y
This code outputs a simple list:
(0 1 2)
Isn't fold-left doing the exact same as the second code block? What can I change to get a simple list output?
You are quoting inside quoted data. When Scheme encounters (quote x)
, or 'x
for short, it evaluates it to the argument unchanged..
'('(1) '(2)))
Is short for:
(quote ((quote (1)) (quote (2))))
And as by my stated evaluation rules it should evaluate to:
((quote (1)) (quote (2)))
Thus if you take caar
or that quoted expression you should get the symbol quote
:
(caar '('(1) '(2)))
; ==> quote
If you were no intended to have those quotes in the data structure then you need to not have them in the expression, like:
'((1) (2))
NB: There is a language related to Scheme, called Racket, it's default output in their REPL is not the value itself but an expression that would evaluate to that value. This is usually confusing even for seasoned schemers. It's like asking someone "what is 3 plus 4" and answer 1 plus 6
.