如何将平面列表转换为任意复杂的树状结构?首先,一个简单的例子,转换'(1 2 3 4)
成'(1 (2 (3 (4))))
.我知道如何用经典递归来做到这一点:
(defun nestify (xs)
(if (null xs)
(list)
(list (car xs) (nestify (cdr xs)))))
Run Code Online (Sandbox Code Playgroud)
现在,如果嵌套结构任意复杂怎么办?例如,我想转换'(1 2 3 4 5 6 7 8)
成'(1 (2 3) (4 (5 6) 7) 8)
.如何编写能够在任何此类嵌套结构中转换平面列表的通用函数?我可以考虑给出一个带虚拟值的模板.例如:
* (nestify '(1 2 3 4 5 6 7 8) '(t (t t) (t (t t) t) t))
'(1 (2 3) (4 (5 6) 7) 8)
Run Code Online (Sandbox Code Playgroud)
我第一次尝试使用递归和自定义树大小查找功能:
(defun length* (tr)
"Count number of elements in a tree." …
Run Code Online (Sandbox Code Playgroud)