Description
Implement
Shop.getSetOfProductsOrderedByEveryCustomer()
using fold.
fold を読んで、
Shop.getSetOfProductsOrderedByEveryCustomer()
を実装してください。
listOf(1, 2, 3, 4).fold(1, {
partProduct, element ->
element * partProduct
}) == 24
Code
// Return the set of products that were ordered by every customer
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
val allProducts = customers.flatMap { it.orders.flatMap { it.products }}.toSet()
return customers.fold(allProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})
}
Memo
fold
... 左から右の各要素に処理を適用した値を、初期値に対して累積していく