6

使用镜头更新集合中元素的最佳方法是什么?例如:

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
  )
}
4

2 回答 2

6

您不能在给定索引处的 List[T] 和 T 之间创建 Lens,因为 Lens 要求您聚焦的对象始终存在。但是,在列表或另一个集合中查找的情况下,索引处可能没有元素。

但是,您可以使用 Traversal,这是一种专注于 0 到多个元素的镜头。使用Monocle,您将使用 index 函数创建从 List 到给定索引处的元素的遍历:

import monocle.SimpleLens
import monocle.syntax.lens._     // to use |-> and |->> instead of composeLens, composeTraversal
import monocle.functions.Index._ // to use index Traversal

// monocle also provides a macro to simplify lens creation
val ingredientsLens = SimpleLens[Recipe, List[Ingredient]](_.ingredients, (recipe, newIngredients)  => recipe.copy(ingredients = newIngredients))  
val quantityLens    = SimpleLens[Ingredient, Int](_.quantity            , (ingredient, newQuantity) => ingredient.copy(quantity = newQuantity))  

val applePie = Receipe(List(Ingredient("apple", 3), Ingredient("egg", 2), ...))


applePie |-> ingredientsLens |->> index(0)   headOption // Some(Ingredient("apple", 3))
applePie |-> ingredientsLens |->> index(999) headOption // None
applePie |-> ingredientsLens |->> index(0) |->> quantityLens headOption // 3
applePie |-> ingredientsLens |->> index(0) |->> quantityLens set 5 
// Receipe(List(Ingredient("apple", 5), Ingredient("egg", 2), ...))
于 2014-04-30T15:45:44.757 回答
1

如果您想根据名称进行更新,那么有一个Mapof怎么样name -> quantity?然后你可以使用这里描述的解决方案:

Scalaz:如何用价值镜头组成地图镜头?

如果你坚持使用Scalaz 的部分镜头,List仍然可以使用。该功能看起来很有希望。listLookupByPLens

于 2013-10-31T22:46:59.047 回答