Page 1 of 1

Question on Arrays Code

Posted: Sat Jun 28, 2014 9:05 am
by macrolyte
Hi. I was looking at implementing some matrix functions and have some questions on style and efficiency. My use of arrays is limited, so it took me a few hours to come up with this :

Code: Select all


(defun mult-arrays (&rest arrays)
  (let ((temp-array (make-array (array-dimension (car arrays) 0) :initial-element 1))) ;; use temporary array as accumulator 
    (dolist (aX arrays)
      (dotimes (i (array-dimension aX 0))
	     (setf (aref temp-array i) (* (aref temp-array i) (aref aX i)))))
    temp-array))

(mult-arrays #(23 45 17 9 27))                ;==> #(23 45 17 9 27)

(mult-arrays #(12 3 0 8) #(2 3 8 12))         ;==> #(24 9 0 96)

And yes, I know I need to implement bounds checking... My concern is are there better solutions for this? Thanks.

Re: Question on Arrays Code

Posted: Mon Jun 30, 2014 10:21 am
by Goheeca
One of my first attempt would look like this, it depends on its intention (the performance aspect, etc.).

Code: Select all

(defun scalar-product (a b)
  (dotimes (index (array-dimension a 0) a)
    (setf (aref a index) (* (aref a index)
                            (aref b index)))))

(defun mult-arrays (&rest arrays)
  (when arrays (reduce #'scalar-product arrays)))