将一个函数分成多行
以下是《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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Lisp 中,行是没有意义的。 Lisp 表示法基于 s 表达式,并且 Lisp 在求值期间看不到文本行。您可以以任何方式在空格上分解表达式。
您必须像这样阅读代码:
请注意,该函数有几个小问题:
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.
You have to read the code like this:
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.