Manipulating a Schema List (Recursion)

The main problem is that when setting the list, return all the elements of this list that are different from the last element. For example, given (abcd) -> return (abc). I have a function, it's just the syntax of the circuit I'm having problems with, and Google is not very friendly. I'm not sure if I use the cons correctly.

(define all-but-last (lambda (x) (if (null? (cdr x)) ('())) (cons ((car x) (all-but-last(cdr x))) ))) 

Someone who is well versed in r5rs syntax will be helpful. Thanks!

+4
source share
5 answers

Using DrRacket with the R5RS language, this works:

 (define all-but-last (lambda (x) (if (null? x) '() (if (null? (cdr x)) '() (cons (car x) (all-but-last(cdr x))))))) 
+2
source

If you remove the extra parentheses around '() and the cons arguments, the code will work (for non-empty input lists).

+3
source

Alternative solution:

 (define (all-but-last xs) (reverse (rest (reverse xs)))) 
+1
source

See the answers to this question:

deletion of the last element of the list (scheme)

Also, I'm going to mark this as "homework." If it is not, let me know and I will delete it.

0
source

if you pass '() to your function, I think you should specify an error message other than return' ()

0
source

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


All Articles