gpt4 book ai didi

java - 扩展 "Movies example"最佳答案

转载 作者:行者123 更新时间:2023-11-30 04:27:17 26 4
gpt4 key购买 nike

我遵循了 Xtend 教程和电影示例。在本教程的最后,您可以找到这个问题:

    @Test def void sumOfVotesOfTop2() {
val long sum = movies.sortBy[ -rating ].take(2).map[ numberOfVotes ].reduce[ a, b | a + b ]
assertEquals(47_229L, sum)
}

First the movies are sorted by rating, then we take the best two. Next the list of movies is turned into a list of their numberOfVotes using the map function. Now we have a List which can be reduced to a single Long by adding the values.

You could also use reduce instead of map and reduce. Do you know how?

我的问题是:最后一个问题的最佳答案是什么?

我找到了一种在不使用map()扩展方法的情况下计算相同“总和”值的方法,但这对我来说似乎很糟糕。这是我的解决方案:

assertEquals(47229, this.movies.sortBy[ -rating ].take(2).reduce[m1, m2 | new Movie('', 0, 0.0, m1.numberOfVotes + m2.numberOfVotes,null)].numberOfVotes)

有更好(更干净)的方法吗?

最佳答案

您可以使用fold(R seed, (R,T)=>R function)代替reduce((T,T)=>T):

assertEquals(47229, 
movies
.sortBy[rating]
.reverseView
.take(2)
.fold(0L) [ result, movie | result + movie.numberOfVotes ])

请注意,map((T)=>R) 不会执行任何急切计算,而是根据需要进行计算,因此对于使用 map 函数的解决方案来说,性能应该不重要。尽管如此,如果您需要累积一组值的结果(其中结果类型与元素类型不同),fold 会非常方便。

关于java - 扩展 "Movies example"最佳答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543833/

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