在C-Lisp中是否可以将地图结果收集到2维数组中?我将如何在函数中引用此数组?
我尝试过类似的事情
(map 'Array'(3 3) #'somefunction sequence)
或
(map '(simple-array T (3 3)) #'somefunction sequence)
并且没有成功。
当然,我要从中开始的序列具有我希望获得的结果数组中总数相同的元素
答案 0 :(得分:4)
执行此操作的一个好方法是使用置换数组和map-into
。这是一个简单的示例:
(defun map-array (f a &rest make-array-kws &key &allow-other-keys)
;; Map F over A, which can be any array, returning a new array with
;; the same shape as A. Keyword arguments get passwd to MAKE-ARRAY
;; of the result array. This may not handle things like fill
;; pointers well or at all.
(let ((r (apply #'make-array (array-dimensions a)
make-array-kws)))
(map-into
(make-array (array-total-size r)
:element-type (array-element-type r)
:displaced-to r)
f
(make-array (array-total-size a)
:element-type (array-element-type a)
:displaced-to a))
r))
答案 1 :(得分:3)
不。根据超级规范(http://www.lispworks.com/documentation/lw50/CLHS/Body/f_map.htm#map),结果类型说明符必须为序列类型。多维数组不是序列类型。当然,您可以编写一个函数来执行所需的操作,但是无法使用map
函数直接完成。
这是您自己制作的方法:
(defun map-to-array (fn sequence w h &optional (type t))
(assert (<= (length sequence) (* w h)) (w h) "Result array too small.")
(let ((result (make-array (list w h)
:element-type type))
(x -1)
(y 0))
(map nil
(lambda (e)
(incf x)
(when (= x w)
(setf x 0)
(incf y))
(setf (aref result x y)
(funcall fn e)))
sequence)
result))