I want to access a n-dimensional vector but somehow (empty? ‘()) keeps returning false.
;; access n dimensional vectors
;; (access-nd vector a-list-of-numbers) -> element
;; (access-nd (vector (vector ‘x ‘y) ‘a ‘b)) 0 1 ) -> x
(define (access-nd avector . alist)
(cond
((and (not(empty? alist)) (vector? avector))
(vector-ref (access-nd avector (rest alist)) (first alist)))
(else avector)))
Please Help.
Edit: CORRECTED CODE
(define (access-nd avector . alist)
(cond
((and (not(empty? alist)) (vector? avector))
(apply access-nd (vector-ref avector (first alist)) (rest alist)))
(else avector)))
Most likely, that one line should read:
Without the “apply”,
alistwill never be empty. Here’s why:In the definition of
access-ndthealistparameter is an optional parameters list; it’s separated with a dot from normal positional parameters. This meansaccess-ndcan be called with 1-n parameters. Any parameters after the first one are collected to a list and bound toalist. For example, a call likewill cause
alistto be bound to the list(1 2 3). Similarly, this call in your original code:will cause
alistto be bound to a list with one element. That’s whyalistwill never be empty.Scheme’s
apply, on the other hand, takes a list of arguments as the last parameter and calls the function as if they were passed to it in the normal way.