如何在lisp中将多个列表的元素组合成一个

时间:2012-11-28 16:45:25

标签: list lisp append

我正在尝试列出列表列表(不用担心,我会举一个例子)并将每个最后的元素转换为一个。 这就是我到目前为止所做的:

(defun cost(state)
(let ((list_elements '()))
(dolist (element state)
  (dolist (subElement element)
    (setq list_elements (append list_elements (list subElement))))
finally (return list_elements))))

示例:

(list
(list
    (list
        (list 1 9 't121) 
        (list 1 10 't122))
    (list
        (list 2 10 't123)
        (list 2 11 't124)))
(list
    (list
        (list 1 9 't121)
        (list 1 11 't132))
    (list
        (list 2 11 't133)
        (list 2 12 't134))))

所以,这应该归还 ((1 9 T121) (1 10 T122) (2 10 T123) (2 11 T124) (1 9 T121) (1 11 T132) (1 11 T132) (2 11 T133) (2 12 T134)) 它只返回((1 9 T121) (1 11 T132))

之后,我应该计算列表中不同元素的数量。

有人看到这个功能有什么问题吗?

1 个答案:

答案 0 :(得分:1)

(defun double-append (list)
  (reduce #'append (reduce #'append list)))

;; or like this:
(defun mapcan-mapcon (list)
  (mapcan #'append (mapcon #'car list)))

(double-append (list
 (list
  (list
   (list 1 9 't121) 
   (list 1 10 't122))
  (list
   (list 2 10 't123)
   (list 2 11 't124)))
 (list
  (list
   (list 1 9 't121)
   (list 1 11 't132))
  (list
   (list 2 11 't133)
   (list 2 12 't134)))))

((1 9 T121) (1 10 T122) (2 10 T123) (2 11 T124) (1 9 T121) (1 11 T132)
 (2 11 T133) (2 12 T134))

到目前为止,我可以通过预期的结果来判断,它必须是类似的东西。

;; Using Alexandria, just as an example, of how currying can save
;; some repetitive coding:
(ql:quickload "alexandria")
(defun curried-append ()
  (let ((reducer (alexandria:curry #'reduce #'append)))
    (alexandria:compose reducer reducer)))

(funcall
 (curried-append)
 (list
  (list
   (list
    (list 1 9 't121) 
    (list 1 10 't122))
   (list
    (list 2 10 't123)
    (list 2 11 't124)))
  (list
   (list
    (list 1 9 't121)
    (list 1 11 't132))
   (list
    (list 2 11 't133)
    (list 2 12 't134)))))