使用镜头更新集合中元素的最佳方法是什么?例如:
case class Ingredient(name: String, quantity: Int)
case class Recipe(val ingredients: List[Ingredient])
如果我想使用镜片创建一个改变单一成分数量的新配方,最好的方法是什么?
我尝试过的方法是动态创建一个镜头:Lens[List[Ingredient], Ingredient]
. 不过这感觉有点笨拙:
case class Recipe(val ingredients: List[Ingredient]) {
import Recipe._
def changeIngredientQuantity(ingredientName: String, newQuantity: Int) = {
val lens = ingredientsLens >=> ingredientLens(ingredientName) >=> Ingredient.quantityLens
lens.set(this, newQuantity)
}
}
object Recipe {
val ingredientsLens = Lens.lensu[Recipe, List[Ingredient]](
(r, i) => r.copy(ingredients = i),
r => r.ingredients
)
def ingredientLens(name: String) = Lens.lensu[List[Ingredient], Ingredient](
(is, i) => is.map (x => if (x.name == name) i else x),
is => is.find(i => i.name == name).get
)
}
case class Ingredient(name: String, quantity: Int)
object Ingredient {
val quantityLens = Lens.lensu[Ingredient, Int](
(i, q) => i.copy(quantity = q),
i => i.quantity
)
}