重写apply函数以改用递归

重写apply函数以改用递归

本文介绍了重写apply函数以改用递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习lisp的最困难的部分可能是以"lisp方式"思考,这种方式既优雅又令人印象深刻,但并不总是那么容易.我知道递归用于解决许多问题,并且我正在研究一本书,该书改而使用apply解决了许多问题,据我所知,它不那么花哨,也没有那么可移植.

Probably the hardest part of learning lisp has been to think in the "lisp way" which is elegant and impressive, but not always easy. I know that recursion is used to solve a lot of problems, and I am working through a book that instead uses apply to solve a lot of problems, which I understand is not as lispy, and also not as portable.

有经验的lisper应该能够在不特别了解describe-pathlocationedges所指的情况下帮助执行此逻辑.这是我正在研究的书中的一个示例:

An experienced lisper should be able to help with this logic without knowing specifically what describe-path location and edges refer to. Here is an example in a book I am working through:

(defun describe-paths (location edges)
  (apply (function append) (mapcar #'describe-path
               (cdr (assoc location edges)))))

我已成功重写此代码以避免使用apply,而改用递归.似乎有效:

I have successfully rewritten this to avoid apply and use recursion instead. It seems to be working:

(defun describe-paths-recursive (location edges)
  (labels ((processx-edge (edge)
         (if (null edge)
         nil
         (append (describe-path (first edge))
             (processx-edge (rest edge))))))
    (processx-edge (cdr (assoc location edges)))))

我希望对此有更多的了解,以建议是否有更优雅的方法将apply转换为递归,或者我是否做了一些不明智的事情.这段代码看起来不错,但是还会有更多的"lispy"吗?

I would like some more seasoned pairs of eyes on this to advise if there is a more elegant way to translate the apply to recursion, or if I have done something unwise. This code seems decent, but would there been something even more "lispy" ?

推荐答案

这个问题没有错;例如,在python类别中会问很多与此类似的问题.

There's nothing wrong with this question; plenty of questions similar to this are asked in the python category, for example.

但是您的问题是:您在做什么很好.实际上,它几乎与彼得·诺维格(Peter Norvig)在其Lisp书籍中展示的一种更通用的技术非常相似,因此您要么已经读过这本书,要么偶然发现了自己的良好实践.无论哪种方式,这都是一个完全可以接受的递归实现.

But to your question: what you are doing is Good. In fact, it closely resembles, nearly identically, a more general technique Peter Norvig shows in one of his Lisp books, so either you've read that book, or you stumbled upon a good practice on your own. Either way, this is a perfectly acceptable implementation of recursion.

这篇关于重写apply函数以改用递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:06