Ruf*_*ife 2 arrays common-lisp
所有喜欢的地图功能mapcar,mapcan,mapc,等需要列为其输入.我正在使用2D数组,并且考虑到通常较大的尺寸(有时为50,000 x 1,000),我宁愿不要弄乱我的阵列的等级.
我需要一种方法来应用类似于(log n)2D数组中每个元素的函数,并产生一个结果的2D数组.
任何帮助或方向都非常感谢.
在AllegroCL工作(Common Lisp)
你需要的是一个组合
像这样的东西:
(defun array-map (function array
&optional (retval (make-array (array-dimensions array))))
"Apply FUNCTION to each element of ARRAY.
Return a new array, or write into the optional 3rd argument."
(dotimes (i (array-total-size array) retval)
(setf (row-major-aref retval i)
(funcall function (row-major-aref array i)))))
Run Code Online (Sandbox Code Playgroud)
例:
(defparameter a (make-array '(2 3) :initial-contents '((1 2 3) (4 5 6))))
a
==> #2A((1 2 3) (4 5 6))
(array-map #'sqrt a)
==> #2A((1 1.4142135 1.7320508) (2 2.236068 2.4494898))
a ; does not change!
==> #2A((1 2 3) (4 5 6))
Run Code Online (Sandbox Code Playgroud)
您也可以使用array-map类似于map-into:
(array-map #'1+ a a)
==> #2A((2 3 4) (5 6 7))
a ; modified, no new storage is allocated
==> #2A((2 3 4) (5 6 7))
Run Code Online (Sandbox Code Playgroud)
请注意,这array-map将适用于任何数组维度,从向量到矩阵到10d和c.
练习:实现array-multi-map接受任意数量的参数和任意数量的数组的函数,以便
(array-multi-map #'+ #A((1 2 3) (4 5 6)) #A((11 22 33) (44 55 66)))
==> #A((12 24 36) (48 60 72))
Run Code Online (Sandbox Code Playgroud)
PS.整个CLHS第15章阵列或CLtL2第17章阵列值得研究.