ealfonso
ealfonso

Reputation: 7292

Best way to reduce/fold over 2d array in common lisp

Emacs lisp has reduce-vec. What's the proper way to do this in common lisp, without using loop or reinventing the wheel?

Upvotes: 1

Views: 537

Answers (1)

malisper
malisper

Reputation: 1671

You should be able to use something like the following. It works for arrays of any dimensions.

(defun reduce-multidimensional-array (fn arr &rest args)
  (apply #'reduce
         fn
         (make-array (array-total-size arr) :displaced-to arr)
         args))

In short, this works by creating a one dimensional array that shares elements with the array passed in. Since reduce works on one dimensional arrays it is possible to reduce the new array.

The function array-total-size returns the total number of elements in the array and the :displaced-to keyword argument causes the new array to share elements with the array passed in (even if they have different dimensions).

Upvotes: 6

Related Questions