Lisp 列表线性化与映射
Lisp list linearization with map
是否可以使用映射函数将列表线性化?
示例:(1 2 (3 (4 5) 6)) -> (1 2 3 4 5 6)
我的错误做法:
(defun f1 (x)
(cond
((atom x) x)
(t (f2 x))
)
)
(defun f2 (lst)
(mapcar 'f1 lst)
)
我不会称其为 linearize a list
但 将列表展平 。
(defun flatten (lst)
"Flatten the list lst"
(cond ((null lst) nil)
((atom lst) (list lst))
(t (loop for e in lst appending (flatten e)))))
是的,地图,虽然不是 mapcar
但 mapcan
:
(defun flatten (lst)
(mapcan
#'(lambda (a)
(cond
((atom a) (list a))
(T (flatten a))))
lst))
如果 Lisp 你指的是 Scheme 或类似的东西,请尝试 append-map
、flat-map
、flatMap
或 mapcat
而不是 Common Lisp 的 mapcan
.
是否可以使用映射函数将列表线性化?
示例:(1 2 (3 (4 5) 6)) -> (1 2 3 4 5 6)
我的错误做法:
(defun f1 (x)
(cond
((atom x) x)
(t (f2 x))
)
)
(defun f2 (lst)
(mapcar 'f1 lst)
)
我不会称其为 linearize a list
但 将列表展平 。
(defun flatten (lst)
"Flatten the list lst"
(cond ((null lst) nil)
((atom lst) (list lst))
(t (loop for e in lst appending (flatten e)))))
是的,地图,虽然不是 mapcar
但 mapcan
:
(defun flatten (lst)
(mapcan
#'(lambda (a)
(cond
((atom a) (list a))
(T (flatten a))))
lst))
如果 Lisp 你指的是 Scheme 或类似的东西,请尝试 append-map
、flat-map
、flatMap
或 mapcat
而不是 Common Lisp 的 mapcan
.