it’s my first time posting and i have a doubt on scheme.
I have to remove all occurrences of an element from a list, passed both as an arguments,
when entering parameters like that:
]=> (rmobject '(1 2 3 5 0 2 3 5 3) 3)
I’m getting an error:
The object (3 5 3 2 3 6 3) is not applicable
I suppose it’s because of the second lambda, that is not working properly but why?
(define (rmobject list1 obj)
(if (null? list1)
'()
(if (= obj (car list1))
((lambda (list1) (cdr list1)) list1)
((lambda (list1) (list1)) list1)))
(cons (car list1) (rmobject (cdr list1) obj)))
I rewrote the code and this works properly on removing the elements but the proper doesn’t, and both are suppose the same. Thanks in advance
(define (rmobject list1 obj)
(if (null? list1)
'()
(if (= obj (car list1))
(rmobject (cdr list1) obj)
(cons (car list1) (rmobject (cdr list1) obj)))))
The first version in your code doesn’t make much sense. Why use
lambdas in this way? you’re supposed to recursively call the same procedure being defined, not creating a one-shot anonymous procedure, that won’t work for solving the problem at hand. And this part:(list1)is causing the errorThe object is not applicable: you’re trying to invoke the list as if it were a procedure – because it’s surrounded by parenthesis. Remember that in Scheme, a syntax such as this one:(foo)indicates that thefooprocedure is to be called.The second version of your code is fine, that’s the simple way to implement a
remove-allprocedure. A bit of nitpicking, though: when you find yourself nestingifs, it’s a sure sign that acondwould be more appropriate. Also notice that it’s a good idea to useequal?instead of=, in that way your procedure will work for more than just numbers:For future reference: the procedure you’re implementing it’s generally included as part of the interpreter. For example, in Racket we have
remove*, which usesequal?as the default procedure for testing equality:Also, you can use
filteras in @Maxwell’s answer. Another way to write it:Anyway, this works: