我想從數在各個層面(表面的層次)LISP
Ex: (1 2 5 (4 2 7 (4 6) 9) 7 8) => (8 9 6)
的名單我現在有什麼計算最大每一子表/平/膚淺的層面的最大數量爲:
maximum (l) ;;function to compute the maximum number for a simple list, it works
(defun max-superficial (lista acc acc2) ;;main function: lista - my list, acc - my final list
;;of results, acc2 - accumulation list for a sublist
(typecase lista
(null
(typecase acc2
;; if my list is empty and I have nothing accumulated, just return the final list
(null acc)
;;if my list is empty but I have something in my accumulation list, just add the maximum
;;of acc2 to my final list
(t (nconc acc (list (maximum acc2))))))
(cons (destructuring-bind (head . tail) lista
(typecase head
(list
;;if my list isn't empty and the head of the list is a list itself, call
;;the function again for the head with an empty accumulation list and then call it again
;;for the tail
(nconc acc
(list (max-superficial head acc nil))
(max-superficial tail acc acc2)))
;; otherwise just accumulate the head and call the function for the tail
---problem here (t (nconc acc2 (list head))
(print '(wtf))
(print acc)
(print acc2)
(print head)
(max-superficial tail acc acc2)))))))
問題是我只寫這個程序,我想測試它,並在列表「---問題在這裏」它不會把我的頭添加到累積列表。
For: (max-superficial '(1 2) nil nil) --result should be ==> wtf nil (1) 1 wtf nil (1 2) 2 2
My result: wtf nil nil 1 wtf nil nil 2 nil
我單獨檢查和(nconc some-list (list 3))
不正是它應該...添加3號到一些名單的後面。我不知道爲什麼nconc acc2 (list head)
不工作
試圖用append替換nconc,它也不工作。顯然,您不能使用append/nconc將元素添加到空列表中。那怎麼樣?
我在此刻移動,不能詳細閱讀所有的代碼,但請注意,nconc具有破壞性:它修改了除最後一個參數外的最後一個cdr。你也在使用一些引用列表。這可能會導致一些意想不到的結果。 –
請參閱http://stackoverflow.com/questions/18790192/unexpected-persistence-of-data –
確實用'append'替換'nconc'解決您的問題? – sds