UFC Insider
UFC Insider

Reputation: 838

Extract elements from list

I am trying to extract all elements that are of symbol 'sym from a list.

(define (extract-sym list)
  extract-sym-inner (list null))

(define (extract-sym-inner oldList newList)
  (cond (null? oldList
         (newList))
        (eq? (car oldList) newList
         (extract-sym-inner((cdr oldList) append newList (extract-sym(oldList)))))
        (eq? (car oldList) 'sym
         (extract-sym-inner((cdr oldList) cons newList(car oldList))))
        (else
         (extract-sym-inner(cdr oldList newList)))))

What I'm trying to do is:
Send the list into an inner function and then:
1. if it's null, return the new list
2. else if the element itself is a list, append the list from the outer function to the new list and continue to next element of old list
3. else if the element is of symbol 'sym, insert it to the new list and continue to the next element of old list
4. else continue to the next element of old list

I think the algorithm itself should work, but I can't manage to understand all the compilation errors I'm getting. For example (extract-sym '(1 2 sym)) gives me the error application: not a procedure;

Any comment would help..

Upvotes: 1

Views: 1047

Answers (1)

Óscar López
Óscar López

Reputation: 236004

There are lots of syntax errors in your code (mostly dealing with incorrect usage of brackets). As mentioned in the comments, you should spend some time familiarizing yourself with the syntax of the language before tackling any other problem. Having said that, this is what I believe you intended to do, study the following solution and pay attention to those brackets!

(define (extract-sym lst)                  ; don't use "list" as a parameter name
  (cond ((null? lst) '())                  ; if list is empty, return empty list
        ((eq? (car lst) 'sym)              ; if current element is 'sym
         (cons (car lst)                   ; add it to the output using cons
               (extract-sym (cdr lst))))   ; and advance recursion
        ((pair? (car lst))                 ; if current element is a list
         (append (extract-sym (car lst))   ; recursively process and use append
                 (extract-sym (cdr lst)))) ; also, advance recursion
        (else (extract-sym (cdr lst)))))   ; otherwise just advance recursion

For example:

(extract-sym '(1 sym 2 (3 sym 4) (5) sym))
=> '(sym sym sym)

Upvotes: 2

Related Questions