LISP 中的映射函数
Mapping function in LISP
我有件事需要你的帮助。我在输入中有一个列表:
(1 ((2 3) (4 ((5) (6)))) ((7 8) (9 10)) 11)
我想在输出中接收以下内容:
((1 2 3 7 8 11)
(1 2 3 9 10 11)
(1 4 5 7 8 11)
(1 4 5 9 10 11)
(1 4 6 7 8 11)
(1 4 6 9 10 11))
mapcar、mapcan、maplist...等功能都没有用。我认为有必要使用递归函数,但不知道如何使用。
你描述的功能好像是DNF计算。这是我的解决方案:
(defun dnf (f)
(when f
(if (consp f)
(let ((f-car-dnf (dnf (car f)))
(f-cdr-dnf (dnf (cdr f))))
(if (or (null f-cdr-dnf) (every #'consp f))
(append f-car-dnf f-cdr-dnf)
(mapcan
(lambda (f-cdr-cj)
(mapcar (lambda (f-car-cj) (append f-car-cj f-cdr-cj))
f-car-dnf))
f-cdr-dnf)))
`((,f)))))
是实习任务吗?
我找到了问题的答案。但我不明白为什么 function "parse" returns NIL 作为结果。
(defun parse (input &optional (res nil) (curlist nil))
(let ((head (car input))
(tail (cdr input)))
(if (numberp head)
(progn
(push head curlist)
(if (null tail)
(push curlist res)
(parse tail res curlist))
(pop curlist))
(if (numberp (car head))
(progn
(push (car head) curlist)
(setf tail (append (cdr head) tail))
(if (null tail)
(push curlist res)
(parse tail res curlist))
(pop curlist))
(loop for element in head do
(parse (cons element tail) res curlist))
)
)
)
(if (null curlist) res)
)
我有件事需要你的帮助。我在输入中有一个列表:
(1 ((2 3) (4 ((5) (6)))) ((7 8) (9 10)) 11)
我想在输出中接收以下内容:
((1 2 3 7 8 11)
(1 2 3 9 10 11)
(1 4 5 7 8 11)
(1 4 5 9 10 11)
(1 4 6 7 8 11)
(1 4 6 9 10 11))
mapcar、mapcan、maplist...等功能都没有用。我认为有必要使用递归函数,但不知道如何使用。
你描述的功能好像是DNF计算。这是我的解决方案:
(defun dnf (f)
(when f
(if (consp f)
(let ((f-car-dnf (dnf (car f)))
(f-cdr-dnf (dnf (cdr f))))
(if (or (null f-cdr-dnf) (every #'consp f))
(append f-car-dnf f-cdr-dnf)
(mapcan
(lambda (f-cdr-cj)
(mapcar (lambda (f-car-cj) (append f-car-cj f-cdr-cj))
f-car-dnf))
f-cdr-dnf)))
`((,f)))))
是实习任务吗?
我找到了问题的答案。但我不明白为什么 function "parse" returns NIL 作为结果。
(defun parse (input &optional (res nil) (curlist nil))
(let ((head (car input))
(tail (cdr input)))
(if (numberp head)
(progn
(push head curlist)
(if (null tail)
(push curlist res)
(parse tail res curlist))
(pop curlist))
(if (numberp (car head))
(progn
(push (car head) curlist)
(setf tail (append (cdr head) tail))
(if (null tail)
(push curlist res)
(parse tail res curlist))
(pop curlist))
(loop for element in head do
(parse (cons element tail) res curlist))
)
)
)
(if (null curlist) res)
)