How to declare a variable inside a Scheme function?

Can this be done? Let's say I want to get the last element of the list, I would create the variable i = 0 and increase it until it is equal to the length. Any ideas? As an example, we will be grateful.

Thanks,

+7
source share
2 answers

There are several ways to declare a variable; the cleanest is let :

 (let ((x some-expr)) ; code block that uses x 

But you do not need this to get the last element of the list. Just use recursion:

 (define (last xs) (if (null? (cdr xs)) (car xs) (last (cdr xs)))) 

Note: if you want, you can use the variable to cache the cdr result:

 (define (last xs) (let ((tail (cdr xs))) (if (null? tail) (car xs) (last tail)))) 
+11
source

Yes, you can define local variables in a schema using let or define inside a function. Using set! , you can also reassign the variable as you imagine.

Having said that, you probably shouldn't solve your problem this way. In the diagram, it is usually recommended to avoid set! when you don’t need (and in this case you definitely don’t need). Repeating the list using indexes is usually a bad idea, since schema lists are linked lists and O (n) is such random access (makes the last function the way you want to implement it O(n^2) ).

Thus, a simple recursive implementation without indexes will be more idiomatic and faster than what you plan to do and as such is preferable.

+3
source

All Articles