[英]Can't tell why collection fold and reduce aren't equivalent
I am going through the Kotlin Koans course.我正在学习 Kotlin Koans 课程。 And I am in the fold section .
我在折叠部分。
GIVEN给定
data class Shop(val name: String, val customers: List<Customer>)
data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}
data class Order(val products: List<Product>, val isDelivered: Boolean)
data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}
data class City(val name: String) {
override fun toString() = name
}
and和
fun Shop.getOrderedProducts(): Set<Product> =
customers.flatMap(Customer::orders).flatMap(Order::products).toSet()
The question asks me to do the following: Return the set of products that were ordered by all customers.该问题要求我执行以下操作:退回所有客户订购的产品集。 Here is my answer, which for whatever reason is not accepted ( would you point the error? )
这是我的答案,无论出于何种原因不被接受(您会指出错误吗? )
// Return the set of products that were ordered by all customers
fun Shop.getProductsOrderedByAll(): Set<Product> =
customers.flatMap(Customer::orders)
.map(Order::products)
.reduce{ acc, el -> (acc.intersect(el)).toList()}
.toSet()
Here is the correct answer:以下是正确答案:
// Return the set of products that were ordered by all customers
fun Shop.getProductsOrderedByAll(): Set<Product> {
val allProducts = customers.flatMap { it.getOrderedProducts() }.toSet()
return customers.fold(allProducts, { orderedByAll, customer ->
orderedByAll.intersect(customer.getOrderedProducts())
})
}
While I don't dispute their answer -- I can follow it without problem -- I don't see why mine isn't correct.虽然我不质疑他们的答案——我可以毫无问题地遵循它——但我不明白为什么我的答案不正确。
I finally figured it out.我终于弄明白了。 I was assuming that each customer is equivalent to one order, but that's not the case.
我假设每个客户都相当于一个订单,但事实并非如此。 Each customer may place multiple orders.
每个客户可以下多个订单。 And the question is to intersect products per customer -- not product per order
问题是与每个客户的产品相交——而不是每个订单的产品
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.