How to remove nested parentheses in LISP

前端 未结 12 1547
清酒与你
清酒与你 2020-11-29 10:20

How can I remove nested parentheses recursively in Common LISP Such as

  (unnest \'(a b c (d e) ((f) g))) => (a b c d e f g)
  (unnest \'(a b))                    


        
12条回答
  •  清酒与你
    2020-11-29 10:37

    Most of the answers have already mentioned a recursive solution to the Flatten problem. Using Common Lisp Object System's multiple dispatching you could solve the problem recursively by defining 3 methods for 3 possible scenarios:

    (defmethod flatten ((tree null))
      "Tree is empty list."
      ())
    (defmethod flatten ((tree list))
      "Tree is a list."
      (append (flatten (car tree))
              (flatten (cdr tree))))
    (defmethod flatten (tree)
      "Tree is something else (atom?)."
      (list tree))
    
    (flatten '(2 ((8) 2 (9 (d (s (((((a))))))))))) ; => (2 8 2 9 D S A)
    

提交回复
热议问题