gpt4 book ai didi

grails - Grails在返回值之前将其添加到函数的返回值中

转载 作者:行者123 更新时间:2023-12-02 16:04:22 25 4
gpt4 key购买 nike

我有一个返回某些值的函数(调用方)。在返回它们之前,通过调用另一个函数(被调用者)的结果将它们添加到其中,是否有一种更整洁的方法在返回之前将被调用者函数的结果值添加到调用者函数的结果值中?

def funcA() { // Caller Function
def a,b,c
a = blah
b = blah blah
...
def (d,e) = funcB()
a += d // Is there a neater way to encapsulate
b += e // these additions somehow into the previous line? maybe kind of like
// (a,b) += funcB() ?
return [a,b,c]
}

def funcB() { // Callee Function
def d,e
...
return [d,e]
}

最佳答案

更糟糕的是,我们没有zip,那么像[a,b].zip()*.sum()这样的东西就可以工作。
transpose()仅为您提供货币对(而不提供其余货币对)。因此这仅在您的列表长度相同时才有效:

assert [43,668]==[[1,2,3],[42,666]].transpose()*.sum()

在这种情况下,可以尝试用零填充较短的列表,因此总和不受影响(此时,这取决于那里的类型)。

因此,此功能是一种解决方法:
def zipadd(a,b) {
def l = [a,b]
// iterate over the size of the longer of the two lists
(0..(l*.size().max()-1)).collect{
// get the pairs, filter null, sum both
l*.getAt(it).findAll{it!=null}.sum()
}
}

assert [43,668,3]==zipadd([1,2,3],[42,666])
assert [43,668,3]==zipadd([42,666],[1,2,3])
assert [24,93,0,1]==zipadd([1,0,0,1], [23,93])

如果您直接使用pass l(列表的列表)而不是a和b,那么这也应该适用于两个以上的元素。

关于grails - Grails在返回值之前将其添加到函数的返回值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998871/

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