Flatten a list using common lisp

后端 未结 3 2046
孤城傲影
孤城傲影 2021-01-25 21:05

I was reading the book On Lisp by Paul Graham. In Chapter 4, Utility Functions, he gives examples of small functions that operate on lists, which would be helpful while writing

3条回答
  •  花落未央
    2021-01-25 21:48

    A non-recursive code which builds the result by conses, following comments and starting from a code by user:Sylwester:

    (defun flatten (lst &optional back acc)
      (loop
         (cond 
            ((consp lst) (psetq lst (cdr lst)              ; parallel assignment
                               back (cons (car lst) back)))
            (back
                      (if (consp (car back))  
                        (psetq lst (cdar back)
                              back (cons (caar back) (cdr back)))
                        (psetq acc (if (car back) (cons (car back) acc) acc)
                              back (cdr back))))
            (t     
                   (return acc)))))                        ; the result
    

    It's not pretty, but it seems to work. Parallel assignment PSETQ is used to simulate tail-recursive call frame update without worrying about precise sequencing.

    Implements the same process as the one encoded nicely by

    (defun flatten2 (l z)
        (cond
            ((endp l) z)
            ((listp (car l)) (flatten2 (car l) (flatten2 (cdr l) z)))
            ((atom (car l)) (cons (car l) (flatten2 (cdr l) z)))))
    
    (defun flatten (l)
       (flatten2 l nil))
    

    with implicit stack operations explicated as list structure manipulations among the variables.

提交回复
热议问题