Flatten a list using common lisp

后端 未结 3 2075
孤城傲影
孤城傲影 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:52

    push changes the symbol binding in scope. Thus the recursion (rflatten el acc) has it's own acc which is the result there but you don't do anything with the returned result and it doesn't alter the callee acc.

    Perhaps a (setf acc (rflatten el acc)) would fix that:

    (defun flatten (lst)
      (labels ((rflatten (lst1 acc)
                 (dolist (el lst1)
                   (if (listp el)
                       (setf acc (rflatten el acc))
                       (push el acc)))
                 acc))
        (reverse (rflatten lst nil))))
    

提交回复
热议问题