gpt4 book ai didi

scala - 如何使用单片眼镜更新 map

转载 作者:行者123 更新时间:2023-12-04 23:19:26 26 4
gpt4 key购买 nike

我想试试 Monocle图书馆。
但是我找不到基本语法的帮助资源。

总之我需要光学Map[K,V] -> A有光学V -> A ,我怎么定义这个?

假设我有一些

import monocle.macros.GenLens

case class DirState(opened: Boolean)

object DirState {
val opened = GenLens[DirState](_.opened)
}

type Path = List[String]
type StateStore = Map[Path, DirState]

接下来遇到需要简单的地方 StateStore => StateStore ,所以我要导入
import monocle._
import monocle.std._
import monocle.syntax._
import monocle.function._

并尝试首先定义:
def setOpened(path: Path): StateStore => StateStore = 
at(path) composeLens DirState.opened set true

到达这里

ambiguous implicit values: both method atMap in trait MapInstances of type [K, V]=> monocle.function.At[Map[K,V],K,V] and method atSet in trait SetInstances of type [A]=> monocle.function.At[Set[A],A,Unit] match expected type monocle.function.At[S,Path,A]



试图将我的定义更改为
def setOpened(path: Path): StateStore => StateStore =
index(path) composeLens DirState.opened set true

现在获取:

type mismatch; found : monocle.function.Index[Map[Path,Nothing],Path,Nothing] (which expands to) monocle.function.Index[Map[List[String],Nothing],List[String],Nothing] required: monocle.function.Index[Map[Path,Nothing],Path,A] (which expands to) monocle.function.Index[Map[List[String],Nothing],List[String],A]

Note: Nothing <: A, but trait Index is invariant in type A. You may wish to define A as +A instead. (SLS 4.5)

最佳答案

import monocle.function.index._
import monocle.std.map._
import monocle.syntax._

def setOpened(path: Path)(s: StateStore): StateStore =
(s applyOptional index(path) composeLens DirState.opened).set(true)

我们来看看 index的类型
def index[S, I, A](i: I)(implicit ev: Index[S, I, A]): Optional[S, A] = 
ev.index(i)

trait Index[S, I, A] {
def index(i: I): Optional[S, A]
}

所以 index召唤类型类的实例 Index类型 Index[S, I, A] .
这允许使用 indexMap , List , Vector等等。

问题是scala编译器需要推断3种类型: S , IAindex的调用站点. I很简单,就是你传递给 index 的参数类型.然而, SA只有当你打电话时才知道 set .
apply已创建语法来指导此类场景的类型推断,基本上是 applyOptional捕获 S这是 Map[Path, DirState] .这为编译器提供了足够的信息来推断 A =:= DirState .

关于scala - 如何使用单片眼镜更新 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31919994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com