gpt4 book ai didi

loops - 可以cl :loop use a custom sum function?

转载 作者:行者123 更新时间:2023-12-02 00:37:20 25 4
gpt4 key购买 nike

我可以为循环指定自定义求和函数(例如,vector-add)吗?

我想做这样的事情:

(loop for vec in '((1 2) (3 4)) sum vec)
;=> (4 6)

最佳答案

这是一个有趣的问题。如果你能做到这一点就好了,但简短的回答是“不”。根据6.1.3 Value Accumulation Clauses来自 HyperSpec:

The sum construct forms a cumulative sum of the successive primary values of the supplied form at each iteration. The argument var is used to accumulate the sum; if var is supplied, loop does not return the final sum automatically. The var argument is bound as if by the construct with to a zero of the appropriate type. Subsequent values (including any necessary coercions) are computed as if by the function +. If into var is used, a type can be supplied for var with the type-spec argument; the consequences are unspecified if a nonnumeric type is supplied. If there is no into variable, the optional type-spec argument applies to the internal variable that is keeping the sum. The default type is implementation-dependent; but it must be a supertype of type number.

您的实际用例是这么简单(遍历列表并计算它们的向量和)还是更复杂?如果就这么简单,你可以用reduce做你想做的事。 .它看起来更像或不太像

(reduce 'vector-add '((1 2) (3 4)))

其中 vector-add 是您的自定义求和函数。如果您仍然需要使用 loop,您可以使用 for sum = ... then ... 获得类似于 reduce 的行为 loop 和一个显式的 finally (return sum)。首先,定义vector-add

(defun vector-add (x y)
(mapcar '+ x y))

(vector-add '(1 2) '(3 4))
;=> (4 6)

我们可以做到:

(loop
for vec in '((1 2) (3 4) (5 6))
for sum = vec then (vector-add sum vec)
finally (return sum))
;=> (9 12)

关于loops - 可以cl :loop use a custom sum function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com