How to remove nested parentheses in LISP

前端 未结 12 1595
清酒与你
清酒与你 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

    Lisp has the function remove to remove things. Here I use a version REMOVE-IF that removes every item for which a predicate is true. I test if the thing is a parenthesis and remove it if true.

    If you want to remove parentheses, see this function:

    (defun unnest (thing)
      (read-from-string
       (concatenate
        'string
        "("
        (remove-if (lambda (c)
                     (member c '(#\( #\))))
                   (princ-to-string thing))
        ")")))
    

    Note, though, as Svante mentions, one does not usually 'remove' parentheses.

提交回复
热议问题