What is the best way to update an element in a collection using lenses? For example:
case class Ingredient(name: String, quantity: Int)
case class Recipe(val ingredients: List[Ingredient])
If I want to use lenses to create a new recipe with the quantity of a single ingredient changed, what's the best way of doing it?
The approach I've tried is to create a lens on the fly: Lens[List[Ingredient], Ingredient]
. This feels a little clunky though:
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
)
}
val
in case class parameters, they are vals by default – Feces