将一个函数分成多行

发布于 2024-10-03 05:45:08 字数 447 浏览 0 评论 0原文

以下是《Land of Lisp》这本书中示例的一些源代码:

(defun random-node ()
  (1+ (random *node-num*)))

(defun edge-pair (a b)
  (unless (eql a b)
     (list (cons a b) (cons b a))))

(defun make-edge-list ()
    (apply #'append (loop repeat *edge-num*
                          collect (edge-pair (random-node) (random-node)))))

由于我没有 Lisp 本能,我发现将一个方法分成多行(作为命令式风格),然后尝试将其转变为函数式风格。

您能帮我将 make-edge-list 函数分成多行吗?

Here are some source code for an example from the amazing book "Land of Lisp" :

(defun random-node ()
  (1+ (random *node-num*)))

(defun edge-pair (a b)
  (unless (eql a b)
     (list (cons a b) (cons b a))))

(defun make-edge-list ()
    (apply #'append (loop repeat *edge-num*
                          collect (edge-pair (random-node) (random-node)))))

Since I don't have the Lisp instinct , I find it is useful to break a method into multiple lines (as an imperative style) and then trying to morph it into the functional style.

Would you please help me to break make-edge-list function into multiple lines?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城半夏 2024-10-10 05:45:08

在 Lisp 中,行是没有意义的。 Lisp 表示法基于 s 表达式,并且 Lisp 在求值期间看不到文本行。您可以以任何方式在空格上分解表达式。

(defun make-edge-list ()
   (apply #'append
          (loop repeat *edge-num*
                collect (edge-pair (random-node)
                                    (random-node)))))

您必须像这样阅读代码:

  • 每个边对都是一个 cons 列表。每个 cons 存储一个位置。
  • 循环返回边对列表。
  • 然后append被应用到这个列表并返回一个conses列表。缺点列表实际上是一个位置列表。

请注意,该函数有几个小问题:

  • APPLY 不适用于任意长度的列表。因此,我们希望列表不会太长。

  • 更重要的是,如果我们稍微改变一下LOOP,那么APPEND函数的应用就不是真正需要的了。 LOOP不仅可以COLLECT,还可以APPEND。

Lines are meaningless in Lisp. Lisp notation is based on s-expressions and the textual line is not seen by Lisp during evaluation. You can break up an expression in any way on whitespace.

(defun make-edge-list ()
   (apply #'append
          (loop repeat *edge-num*
                collect (edge-pair (random-node)
                                    (random-node)))))

You have to read the code like this:

  • each edge pair is a list of conses. Each cons stores a position.
  • the loop returns a list of edge pairs.
  • Then append is applied to this list and returns a list of conses. The list of conses is really a list of positions.

Note that the function has several slight problems:

  • APPLY works not for lists of arbitrary lengths. So let's hope that the list is not too long.

  • More important, the apply of the function APPEND is not really needed if we change the LOOP slightly. LOOP can not only COLLECT, but also APPEND.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文