views:

140

answers:

1

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)))
+2  A: 

Most likely, that one line should read:

     (vector-ref (apply access-nd avector (rest alist)) (first alist)))

Without the "apply", alist will never be empty. Here's why:

In the definition of access-nd the alist parameter is an optional parameters list; it's separated with a dot from normal positional parameters. This means access-nd can be called with 1-n parameters. Any parameters after the first one are collected to a list and bound to alist. For example, a call like

(access-nd v 1 2 3)

will cause alist to be bound to the list (1 2 3). Similarly, this call in your original code:

(access-nd avector (rest alist))

will cause alist to be bound to a list with one element. That's why alist will 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.

Ville Laurikari
Could you tell me why that is?
kunjaan
Edited my reply with hopefully enough detail to understand what is going on.
Ville Laurikari
Thanks .
kunjaan