用map实现Lisp列表线性化
是否可以使用映射函数将列表线性化?用map实现Lisp列表线性化,lisp,map-function,Lisp,Map Function,是否可以使用映射函数将列表线性化? 例如:(12(3(45)6))->(123456) 我的错误做法: (defun f1 (x) (cond ((atom x) x) (t (f2 x)) ) ) (defun f2 (lst) (mapcar 'f1 lst) ) 我不会称之为线性化列表,而是扁平化列表 (defun flatten (lst) "Flatten the list lst" (cond ((null lst)
例如:(12(3(45)6))->(123456) 我的错误做法:
(defun f1 (x)
(cond
((atom x) x)
(t (f2 x))
)
)
(defun f2 (lst)
(mapcar 'f1 lst)
)
我不会称之为
线性化列表
,而是扁平化列表
(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
来代替常见的Lisp的mapcanWow?直到。