Максимален брой на всяко ниво (повърхностно ниво) 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) не работи

Опитах да заменя nconc с append и също не работи. Очевидно не можете да добавите елемент към празен списък с помощта на append/nconc. Тогава как?


person Mocktheduck    schedule 28.11.2015    source източник
comment
В момента съм на мобилен телефон и не мога да прочета целия ви код в детайли, но имайте предвид, че nconc е разрушителен: той модифицира последния cdr във всичките си аргументи освен последния. Вие също използвате някои цитирани списъци. Това може да доведе до някои неочаквани резултати.   -  person Joshua Taylor    schedule 29.11.2015
comment
Вижте например stackoverflow.com/questions/18790192/   -  person Joshua Taylor    schedule 29.11.2015
comment
замяната на nconc с append решава ли проблема ви?   -  person sds    schedule 29.11.2015
comment
Не, не го решава. Все пак няма да натрупа моите елементи   -  person Mocktheduck    schedule 29.11.2015
comment
Не знам как ми помага този въпрос. Моят nconc просто няма да направи нищо и нито добавя   -  person Mocktheduck    schedule 29.11.2015


Отговори (2)


По-проста реализация:

(defun max-superficial/sublists (list)
  (loop for num in list
       if (listp num) append (max-superficial/sublists num) into sublists
       else if (numberp num) maximize num into max
       else do (error "Not a number or list: ~a" num)
       finally (return (cons max sublists))))

;; If you want the max of each "level" or depth in a tree,
;; then you need to be able to operate on levels. Here are some
;; functions that are analogous to FIRST, REST, and POP:

(defun top-level (tree)
  (remove-if-not #'numberp tree))

(defun rest-levels (tree)
  (apply #'append (remove-if-not #'listp tree)))

(defmacro pop-level (tree)
  `(let ((top (top-level ,tree)))
     (setf ,tree (rest-levels ,tree))
     top))

(defun max-superficial (tree &key use-sublists)
  "It wasn't clear if you wanted the max in each sublist or the max
at each depth, so both are implemented. Use the :use-sublists key
to get the max in each sublist, otherwise the max at each depth
will be computed."
  (if use-sublists
      (max-superficial/sublists tree)
      (loop for top-level = (pop-level tree)
         collect (if top-level (reduce #'max top-level)) into result
         unless tree do (return result))))
person Throw Away Account    schedule 29.11.2015
comment
Това трябва ли да върне (1 2 3) както за '(1 (2 (3))), така и за '(1 (2) (3))? (Не е много ясно от OP...) - person gsg; 29.11.2015
comment
Той спомена както подсписъци, така и нива. Актуализирах кода, за да работи на нива или подсписъци в зависимост от аргумент &key. - person Throw Away Account; 29.11.2015
comment
Изглежда страхотно, но трябва да използвам само основните операции на lisp, така че да не работя с дървета. @gsg (1 2 3) Е правилният отговор. Дадох пример там, можете ясно да видите какво имам предвид. - person Mocktheduck; 29.11.2015

Ето едно (не особено ефективно) решение:

(defun max-avoiding-nil (a b)
  (cond ((null a) b)
    ((null b) a)
    (t (max a b))))

(defun depth-maximum (a b)
  (cond ((null a) b)
    ((null b) a)
    (t
     (cons (max-avoiding-nil (car a) (car b))
           (depth-maximum (cdr a) (cdr b))))))

(defun tree-max-list (list depth)
  (reduce #'depth-maximum tree
          :key (lambda (elt) (tree-max elt depth))
          :initial-value '()))

(defun tree-max (tree depth)
  (if (listp tree)
      (tree-max-list tree (1+ depth))
    (append (make-list depth 'nil) (list tree))))

(defun tree-maximums (tree)
  (tree-max-list tree 0))

(tree-maximums '(1 2 5 (4 2 7 (4 6) 9) 7 8)) => (8 9 6)
(tree-maximums '()) => nil
(tree-maximums '(1)) => (1)
(tree-maximums '((2))) => (nil 2)
(tree-maximums '((2) (3))) => (nil 3)
person gsg    schedule 29.11.2015
comment
Не трябва да използвам функции като намаляване или #, :, ламбда. Аз съм начинаещ и искам да реша това по най-основния начин, по който мога, като използвам само списъци - person Mocktheduck; 29.11.2015