是否可以从 CLisp 中的映射中获得一个二维数组作为结果类型?
Is it possible to have a 2 dimension array as a result type from a map in CLisp?
在 C-Lisp 中是否可以将 map 的结果收集到二维数组中?我如何在函数中引用这个数组?
我已经尝试过,
(map 'Array'(3 3) #'somefunction sequence)
或
(map '(simple-array T (3 3)) #'somefunction sequence)
并没有成功。
当然,我开始的序列与我希望获得的结果数组的元素总数相同
没有。根据 hyperspec (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))
执行此操作的一个好方法是使用置换数组和 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))
在 C-Lisp 中是否可以将 map 的结果收集到二维数组中?我如何在函数中引用这个数组?
我已经尝试过,
(map 'Array'(3 3) #'somefunction sequence)
或
(map '(simple-array T (3 3)) #'somefunction sequence)
并没有成功。
当然,我开始的序列与我希望获得的结果数组的元素总数相同
没有。根据 hyperspec (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))
执行此操作的一个好方法是使用置换数组和 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))