LISP中的映射功能

时间:2015-03-10 07:35:20

标签: recursion mapping 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等功能无济于事。我认为有必要使用递归函数,但不知道如何。

2 个答案:

答案 0 :(得分:0)

您描述的功能似乎是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)))))

这是一项实习任务吗?

答案 1 :(得分:0)

我找到了问题的答案。但我不明白为什么函数“parse”会返回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)
)