I\'m trying to solve a problem with outputting only the non repeating elements n
ID: 3583847 • Letter: I
Question
I'm trying to solve a problem with outputting only the non repeating elements n a list in scheme. e.g: (a b a a a c c) would give (a b).
I have implemented this solution:
(define (remove L)
(if (null? L) L
(let ((firstL (car L))
(restL (cdr L)))
(if (null? restL) (cons firstL ())
(if (equal? firstL (car restL)) (remove (cdr restL))
( cons firstL (remove restL)))))))
However it outputs the also the elements with odd number of repetitions. e.g: (a b a a a c c) would give (a b a).
I'm trying to fix it, but I couldn't. an example of one of the solutions that I have tried is:
(define (remove L)
(if (null? L) L
(let ((result ())
(firstL (car L))
(restL (cdr L)))
(if (null? restL) (result)
(if (equal? firstL (car restL)) (remove2 firstL restL)
(append ((list firstL) result)) (remove cdr restL)))))
(define (remove2 x y)
(cond ((null? y) (remove x)
((equal? x (car y)) (remove2 ((car y) (cdr y))))
(else(remove x)))))
Please if someone can figure a solution, write it down.
P.S. The solution has to be in scheme.
Thanks
Explanation / Answer
Your second attempt has lots of syntactic errors. I think if you look at the first attempt and mend one syntax error with the missing quote '() you almost have it if you can remove successive elements instead of just one. eg. make
(trim-first '(a b c)) ; ==> (b c)
(trim-first '(a a b c)) ; ==> (b c)
(trim-first '(a a a b c)) ; ==> (b c)
Then you could just use that instead of cdr:
(define (remove L)
(if (null? L)
L
(let ((firstL (car L)) (restL (cdr L)))
(if (null? restL)
(cons firstL '())
(if (equal? firstL (car restL))
(remove (trim-first restL))
(cons firstL (remove restL)))))))
I would have written it with cond to make it flatter though and kept away from the unconventional camelCase in favor of lisp-case:
(define (remove-runs lst)
(cond ((null? lst) '())
((null? (cdr lst)) lst)
((equal? (car lst) (cadr lst)) (remove-runs (trim-first (cdr lst))))
(else (cons (car lst) (remove-runs (cdr lst)))))