How to append the current list with another element in Scheme?
Let's say I have a list:
a b a a a c e
.
I want to get rid of all adjacent duplicate, i.e. the two a's in the middle. So the list becomes
a b a c e
.
The algorithm that I current h开发者_开发百科ave in mind is,
- Check if the current value is equal to the next value by(equal? (car lst) (car (cdr lst)))
If they are equal then I want to skip the duplicate element, but I don't know how to achieve this behavior in Scheme? Any idea?
- If they're not equal, keep traversing through the list.By the way, is there a way to implement iterative for
loop in Scheme for these types of problem? Because I feel recursion is just overkill for this simple problem.
Thanks,
I have not written Scheme for a long time, but maybe this will be helpful to you:
(define (remove-adjacent-duplicates list)
(if (empty? list)
'()
(if (equal? (car list) (cadr list))
(remove-adjacent-duplicates (cdr list))
(cons (car list) (remove-adjacent-duplicates (cdr list)))))
Oh, and don't be afraid of recursion, especially in Scheme. It's fun! :)
Here's an iterative answer for this problem using fold
:
(define (uniq lst)
(fold (lambda (elem result)
(if (and (pair? result) (equal? elem (car result)))
result
(cons elem result)))
'() (reverse lst)))
(In future, any time you're trying to convert a list to something, consider using fold
, and any time you're trying to convert something to a list, consider using unfold
. They're very powerful functions!)
In this case you would want to save the car of the cdr to cons onto the result of your recursive call (ditch the car, it makes checking in a case with like 3 a's easier). Now the question you are asking is what is the recursive call on. Well, now you cons the car of the cdr onto the recurion on the cdr.
精彩评论