Hello. I am working through the Kotlin Koans and c...
# announcements
t
Hello. I am working through the Kotlin Koans and currently at https://play.kotlinlang.org/koans/Collections/Fold/Task.kt. Am I understanding the problem correctly in that Shop.getProductsOrderedByAll() should return a set of products that were purchased by all of the customers? Therefore, if there is at least one customer who did not purchase a product, then that product should not be part of the resulting set?
d
Yes
t
Thanks for responding. With that assumption, I implemented the following codes:
Copy code
fun Shop.getProductsOrderedByAll(): Set<Product> {
    return customers.fold(setOf<Product>()) { products, customer ->
        val customerProducts = customer.getOrderedProducts().toSet()
        return if (products.size == 0) customerProducts else products.intersect(customerProducts)
    }
}
However, the system does not seem to accept this answer. I am not sure what I am missing here. Thanks.
m
fold is an inline function, so you shouldn't return from the lambda. That return is returning from `getProductsOrderedByAll`instead of the lambda.
d
Looks like flawed logic also. If your first customer has only product A, and your second customer has only product B, your set being passed into the third element of fold would be empty and thus start with products the third customer has, say products C through F, and those elements could be in your final result despite the first two customers not having purchased them
t
It seems fixing my lambda function to be inline solves the issue and the system accepted the answer. Thanks @mkrussel. @Dave K -- Thanks for pointing out the logic error. My original flawed implementation was still accepted after I made the lambda inline. I believe that was because the first customer's orders were not empty. If you hadn't pointed out the flaw, I would have missed out on a good learning experience, so thanks again. Below is my final implementation.
Copy code
fun Shop.getProductsOrderedByAll(): Set<Product> {
    val allProducts = customers.flatMap(Customer::getOrderedProducts).toSet()
    return customers.fold(allProducts) { 
        products, customer -> products.intersect(customer.getOrderedProducts()) 
    }
}
d
Nice change :)
­čĹŹ 1