Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding and removing the last occurrence of a specified element in a list [racket]
    primarykey
    data
    text
    <p>I've started to write a function that should find the last occurrence of an element in a list. My idea was to use <code>search</code> to count the occurrences of the specified symbol and return it. I would then pass the count into <code>removeLast</code> that would remove the element. I would then decrement the count in <code>removeLast</code> to facilitate the base case. From what I've been seeing using <code>set!</code> is generally bad practice. Is there a better/more elegant way to "remember" the last occurrence of symbol.</p> <pre><code>(define (lastLess lis symbol) (define count 0) (set! count (search symbol lis count)) (removeLast symbol lis count) ) (define (search symbol lis count ) ( cond ((null? lis) count) ( (eq? symbol (car lis)) (+ count (add1 (search symbol (cdr lis) count ))) ) ( (pair? (car lis))(+ count(+ 0 (search symbol (car lis) count )))) ( else (+ count(+ 0 (search symbol (cdr lis) count)))) ) ) (define (removeLast symbol lis count) (cond ((null? lis) '()) ((eq? count 0) (cdr lis)) ((eq? symbol (car lis)) ((set! count (sub1 count)) (cons (car lis)(removeLast symbol (cdr lis) count)) ) ) ((pair? (car lis)) (removeLast symbol (car lis) count)) (else (cons (car lis) (removeLast symbol (cdr lis) count ))) ) ) </code></pre> <p>Running the code as is the <code>((set! count (sub1 count))(cons (car lis)(removeLast symbol (cdr lis) count))))</code> throws an error:</p> <blockquote> <p>application: not a procedure; expected a procedure that can be applied to arguments given: # arguments...: '(e)</p> </blockquote> <p>EDIT: This is an assignment for class, so redundant <code>reverse</code>s aren't acceptable, and I must account for nest lists.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload