Is it possible to do so? Let's say I want to get the last element of a list, I would create a variable i = 0
, and increment it until it equals to length. Any idea? An example would be greatly appreciated.
Thanks,
A variable is a box-like object that can hold any Scheme value. It is said to be undefined if its box holds a special Scheme value that denotes undefined-ness (which is different from all other Scheme values, including for example #f ); otherwise the variable is defined. On its own, a variable object is anonymous.
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters.
In Scheme, you always give a variable an initial value, so there's no such thing as an uninitialized variable or an unininitialized variable error. Scheme values are always pointers to objects, so when we use the literal 5 , Scheme interprets that as meaning a pointer to the object 5 .
C++ will allow you to declare a variable anywhere in the program as long as the variable is declared before you use it. A good programming practice to develop is to declare variables at the top of a function. Declaring variables in this manner makes for easier readability of the program.
There are several ways to declare a variable; the cleanest one is let
:
(let ((x some-expr))
; code block that uses x
But you don't need this to get the last element of a list. Just use recursion:
(define (last xs)
(if (null? (cdr xs))
(car xs)
(last (cdr xs))))
Note: if you want, you can 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 in scheme, either using let
or define
inside a function. Using set!
, it's also possible to reassign a variable like you imagine.
That being said, you should probably not solve your problem this way. In Scheme it's generally good practice to avoid set!
when you don't need to (and in this case you definitely don't need to). Further iterating over a list using indices is usually a bad idea as scheme's lists are linked lists and as such random access O(n) (making the last
function as you want to implement it O(n^2)
).
So a simple recursive implementation without indices would be more idiomatic and faster than what you're planning to do and as such preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With