加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何使用单片眼镜更新地图

发布时间:2020-12-16 09:51:03 所属栏目:安全 来源:网络整理
导读:我想试试 Monocle库. 但我找不到基本语法的帮助资源. 总之,我需要光学Map [K,V] – 具有光学系数V – A,我怎么能定义这个? 假设我有一些 import monocle.macros.GenLenscase class DirState(opened: Boolean)object DirState { val opened = GenLens[DirSta
我想试试 Monocle库.
但我找不到基本语法的帮助资源.

总之,我需要光学Map [K,V] – >具有光学系数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],Nothing]
(which expands to) monocle.function.Index[Map[List[String],List[String],Nothing]
required:
monocle.function.Index[Map[Path,A]
(which expands to) monocle.function.Index[Map[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)

让我们来看看索引的类型

def index[S,I,A](i: I)(implicit ev: Index[S,A]): Optional[S,A] = 
  ev.index(i)

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

因此索引召唤类型为Index [S,A]的索引类型的实例.
这允许使用Map,List,Vector等索引.

问题是scala编译器需要在索引的调用站点推断出3种类型:S,I和A.我很简单,它是您传递给索引的参数的类型.但是,只有在调用set时才会知道S和A.

已经创建了apply语法来引导这种场景的类型推断,基本上是applyOptionalcaptures S,即Map [Path,DirState].这为编译器提供了足够的信息来推断A =:= DirState.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读