multidimensional arrays

Any other programming language that is not covered in the Web Scripting category.

multidimensional arrays

Postby hafner on Wed Nov 08, 2006 11:51 pm

Are you missing multidimensional arrays in Scheme? Scheme is many dialect's common subset rather than a complete (satisfying) programming language per se. Most of the Scheme implementations provide multidimensional arrays beyond the R5RS standard. But I find it just funny to program my own way, using nothing beyond R5RS. Here it goes (example code first):
Code: Select all
(define (run-example)
  ;; make an array with dimensions 3x4x5:
  (define a (mk-array '(3 4 5) "n/a"))
  ;; get element:
  (write (a 1 0 2)) ;; => "n/a"
  (newline)
  ;; set element to value "foo":
  (a 1 0 2 "foo")
  ;; get again:
  (write (a 1 0 2)) ;; => "foo"
  (newline))

(define (mk-array diml init)
  (define v (make-vector (apply * diml) init))
  (lambda args
    (let loop ((diml diml) (args args) (s 0))
      (if (null? diml)
          (if (null? args)
              (vector-ref v s)
              (vector-set! v s (car args)))
          (let ((d (car diml)) (i (car args)))
            (loop (cdr diml) (cdr args) (+ (* s d) i)))))))

(run-example)
BTW, initialization with a given value became very easy this way (i.e. compared to an implementation using vectors of vectors).

Regards
Thomas
hafner
Contributer
Contributer
 
Posts: 73
Joined: Tue Mar 07, 2006 2:18 pm
Location: München (Germany)

Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron