2
\$\begingroup\$

As explained here, I'm learning a limited subset of Scheme.

My task has been to sort a numerical list. To implement a simple insertion sort, I need to remove a single element from a list.

I've done the following (in the spirit of The Little Schemer):

(define remove-elem
 (lambda (ll elem)
 (cond
 ((null? ll) '())
 ((eq? (car ll) elem) (cdr ll))
 (else 
 (cons (car ll) (remove-elem (cdr ll) elem))))
 ))

What are other ways of implementing this function?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 29, 2013 at 22:17
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

That looks mostly right to me. I'll suggest two things.

First, there is nice syntatic sugar for defining functions:

(define (remove-elem xs elem) 
 (cond ...)
)

Save yourself the lambda.

Second, you are using eq?. That is the wrong checker for this problem. That function returns true if the two objects are the exact same object in memory. It could be true for primitives like ints, but it's not necessarily true. What you want to use is eqv? which will guaranteed work for numbers.

answered Oct 29, 2013 at 23:06
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.