如何查找和修改嵌套案例类中的字段?

时间:2015-10-28 11:35:08

标签: scala lens monocle-scala

使用List字段定义了一些嵌套的案例类:

@Lenses("_") case class Version(version: Int, content: String)
@Lenses("_") case class Doc(path: String, versions: List[Version])
@Lenses("_") case class Project(name: String, docs: List[Doc])
@Lenses("_") case class Workspace(projects: List[Project])

示例workspace

val workspace = Workspace(List(
  Project("scala", List(
    Doc("src/a.scala", List(Version(1, "a11"), Version(2, "a22"))),
    Doc("src/b.scala", List(Version(1, "b11"), Version(2, "b22"))))),
  Project("java", List(
    Doc("src/a.java", List(Version(1, "a11"), Version(2, "a22"))),
    Doc("src/b.java", List(Version(1, "b11"), Version(2, "b22"))))),
  Project("javascript", List(
    Doc("src/a.js", List(Version(1, "a11"), Version(2, "a22"))),
    Doc("src/b.js", List(Version(1, "b11"), Version(2, "b22")))))
))

现在我想写一个方法,为version添加一个新的doc

def addNewVersion(workspace: Workspace, projectName: String, docPath: String, version: Version): Workspace = {
  ???
}

我将使用如下:

  val newWorkspace = addNewVersion(workspace, "scala", "src/b.scala", Version(3, "b33"))

  println(newWorkspace == Workspace(List(
    Project("scala", List(
      Doc("src/a.scala", List(Version(1, "a11"), Version(2, "a22"))),
      Doc("src/b.scala", List(Version(1, "b11"), Version(2, "b22"), Version(3, "b33"))))),
    Project("java", List(
      Doc("src/a.java", List(Version(1, "a11"), Version(2, "a22"))),
      Doc("src/b.java", List(Version(1, "b11"), Version(2, "b22"))))),
    Project("javascript", List(
      Doc("src/a.js", List(Version(1, "a11"), Version(2, "a22"))),
      Doc("src/b.js", List(Version(1, "b11"), Version(2, "b22")))))
  )))

我不确定如何以优雅的方式实现它。我尝试使用monocle,但它没有提供filterfind。我的尴尬解决方案是:

def addNewVersion(workspace: Workspace, projectName: String, docPath: String, version: Version): Workspace = {
  (_projects composeTraversal each).modify(project => {
    if (project.name == projectName) {
      (_docs composeTraversal each).modify(doc => {
        if (doc.path == docPath) {
          _versions.modify(_ ::: List(version))(doc)
        } else doc
      })(project)
    } else project
  })(workspace)
}

有没有更好的解决方案? (可以使用任何库,而不仅仅是monocle

3 个答案:

答案 0 :(得分:8)

我只是使用eachWhere方法扩展Quicklens来处理这种情况,这个特殊的方法看起来像这样:

import com.softwaremill.quicklens._

def addNewVersion(workspace: Workspace, projectName: String, docPath: String, version: Version): Workspace = {
  workspace
    .modify(_.projects.eachWhere(_.name == projectName)
             .docs.eachWhere(_.path == docPath).versions)
    .using(vs => version :: vs)
}

答案 1 :(得分:6)

我们可以用光学器件很好地实现addNewVersion但是有一个问题:

import monocle._
import monocle.macros.Lenses
import monocle.function._
import monocle.std.list._ 
import Workspace._, Project._, Doc._

def select[S](p: S => Boolean): Prism[S, S] =
   Prism[S, S](s => if(p(s)) Some(s) else None)(identity)

 def workspaceToVersions(projectName: String, docPath: String): Traversal[Workspace, List[Version]] =
  _projects composeTraversal each composePrism select(_.name == projectName) composeLens
    _docs composeTraversal each composePrism select(_.path == docPath) composeLens
    _versions

def addNewVersion(workspace: Workspace, projectName: String, docPath: String, version: Version): Workspace =
  workspaceToVersions(projectName, docPath).modify(_ :+ version)(workspace)

这会有效,但您可能已注意到select Prism未使用的select Traversal。这是因为t不满足t.modify(f) compose t.modify(g) == t.modify(f compose g)法律规定所有val negative: Prism[Int, Int] = select[Int](_ < 0) (negative.modify(_ + 1) compose negative.modify(_ - 1))(-1) == 0 select

一个反例是:

workspaceToVersions

但是,{{1}}中{{1}}的使用完全有效,因为我们会对我们修改的其他字段进行过滤。所以我们不能使谓词无效。

答案 2 :(得分:5)

您可以使用Monocle的Index类型来使您的解决方案更清晰,更通用。

import monocle._, monocle.function.Index, monocle.function.all.index

def indexListBy[A, B, I](l: Lens[A, List[B]])(f: B => I): Index[A, I, B] =
  new Index[A, I, B] {
    def index(i: I): Optional[A, B] = l.composeOptional(
      Optional((_: List[B]).find(a => f(a) == i))(newA => as =>
        as.map {
          case a if f(a) == i => newA
          case a => a
        }
      )
    )
  }

implicit val projectNameIndex: Index[Workspace, String, Project] =
  indexListBy(Workspace._projects)(_.name)

implicit val docPathIndex: Index[Project, String, Doc] =
  indexListBy(Project._docs)(_.path)

这说:我知道如何使用字符串(名称)在工作区中查找项目,以及通过字符串(路径)在项目中查找文档。您还可以将Index个实例设置为Index[List[Project], String, Project],但由于您不拥有List,这可能是不理想的。

接下来,您可以定义一个结合了两个查找的Optional

def docLens(projectName: String, docPath: String): Optional[Workspace, Doc] =
  index[Workspace, String, Project](projectName).composeOptional(index(docPath))

然后你的方法:

def addNewVersion(
  workspace: Workspace,
  projectName: String,
  docPath: String,
  version: Version
): Workspace =
  docLens(projectName, docPath).modify(doc =>
    doc.copy(versions = doc.versions :+ version)
  )(workspace)

你已经完成了。这并不比你的实现更简洁,但它由更好的可组合部分组成。