[ACCEPTED]-How to declare a variable inside a Scheme function?-scheme
There are several ways to declare a variable; the 4 cleanest one is let
:
(let ((x some-expr))
; code block that uses x
But you don't need this 3 to get the last element of a list. Just 2 use recursion:
(define (last xs)
(if (null? (cdr xs))
(car xs)
(last (cdr xs))))
Note: if you want, you can 1 use a variable to cache cdr
's result:
(define (last xs)
(let ((tail (cdr xs)))
(if (null? tail)
(car xs)
(last tail))))
Yes, it's possible to define local variables 15 in scheme, either using let
or define
inside a function. Using 14 set!
, it's also possible to reassign a variable 13 like you imagine.
That being said, you should 12 probably not solve your problem this way. In 11 Scheme it's generally good practice to avoid 10 set!
when you don't need to (and in this case 9 you definitely don't need to). Further iterating 8 over a list using indices is usually a bad 7 idea as scheme's lists are linked lists 6 and as such random access O(n) (making the 5 last
function as you want to implement it O(n^2)
).
So 4 a simple recursive implementation without 3 indices would be more idiomatic and faster 2 than what you're planning to do and as such 1 preferable.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.