user2905256
user2905256

Reputation: 145

How to get rid of extra list levels in scheme?

My function below must accept an input that looks like this:

(getlist '(a b '(a b) 1 2 '() '(1 2)) )

The function must then output a list of all of the lists within the original list. So the output should be like

"((a b)()(1 2))" 

but I am getting this:

"((quote (a b)) (quote ()) (quote (1 2)))"

I am getting the right values but they are all wrapped inside an extra list with the quotes attached. How do I fix this?

Thank You

;function to return all lists in a list
(define (getlist lst)
    ;if list is empty 
    (if (null? lst)
        ;true
        '()
        ;false
        (if (list? (car lst))
            ;true
            (cons (car lst) (getlist (cdr lst)))
            ;false
            (getlist (cdr lst)))))

Upvotes: 0

Views: 44

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

That's because the input list really does contain the lists (quote (a b)), (quote ()), and (quote (1 2)).
The symbol quote is never evaluated.

' is not a "list-building" operator.
It's shorthand for the quote special form, which causes its arguments to not be evaluated.

Since the entire list is quoted, you're not evaluating '(a b)– that is, (quote (a b))– and the result is the list (quote (a b)).

The fix is to remove all the quotes except the outermost one:

> (getlist '(a b (a b) 1 2 () (1 2)))
'((a b) () (1 2))

Upvotes: 2

Related Questions