Scheme for getting the last item in the list

I am trying to write a simple schema function that returns the last element of a list. My function looks as if it should work, but I managed to fail something:

(define (last_element l)( (cond (null? (cdr l)) (car l)) (last_element (cdr l)) )) (last_element '(1 2 3)) should return 3 

DrRacket continues to give me errors:

 mcdr: contract violation expected: mpair? given: () 

Since (null? '()) true, I don't understand why this is not working.

This is the function that I think I will need for homework (writing the last-element function is not the destination), and the instructions say that I cannot use the built-in reverse function, so I can’t simply (car (reverse l))

How to fix this feature?

+4
source share
3 answers

Your syntax is completely wrong. You have an extra set of parentheses around the function body, not enough around cond clauses, and your recursive case is not even within cond , so whether the test succeeds or fails. The following procedure should work:

 (define (last_element l) (cond ((null? (cdr l)) (car l)) (else (last_element (cdr l))))) 
+9
source

Just add: in professional-level Racket, the last function is part of the racket / list .

+4
source

You can also do it like this. First find the length of the list with cdring it down. Then use list-ref x, which gives the x element from the list. For example, list-ref yourlistsname 0 gives the first element (basically a list car.) And (list-ref yourlistsname (- length 1)) gives the last element of the list.

0
source

Source: https://habr.com/ru/post/1443410/


All Articles