4

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]

次に simple が必要な場所に遭遇した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

ここに来る

あいまいな暗黙の値: 型のメソッドと型のメソッドの両方が 期待 さatMapれる型 と一致 しますtrait MapInstances[K, V]=> monocle.function.At[Map[K,V],K,V]atSettrait SetInstances[A]=> monocle.function.At[Set[A],A,Unit]monocle.function.At[S,Path,A]

私の定義をに変更しようとしています

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

今すぐ取得:

型の不一致; found : monocle.function.Index[Map[Path,Nothing],Path,Nothing] (展開先) monocle.function.Index[Map[List[String],Nothing],List[String],Nothing] required: monocle.function.Index[Map[Path,Nothing],Path,A] (展開先)monocle.function.Index[Map[List[String],Nothing],List[String],A]

注: Nothing <: Aですがtrait Index、型では不変Aです。代わりにAasを定義することもできます。+A(SLS4.5)

4

2 に答える 2

9
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、 type の型 classIndexのインスタンスを呼び出しますIndex[S, I, A]。これにより、 、 などにindex使用MapできListますVector

問題は、scala コンパイラが との呼び出しサイトで のS3つの型を推論する必要があることです。に渡すパラメータの型です。ただし、とは を呼び出したときにしかわかりません。IAindexIindexSAset

構文は、そのapplyようなシナリオの型推論をガイドするために作成されており、基本的にはapplyOptionalどちらSMap[Path, DirState]. これにより、コンパイラが推論するのに十分な情報が得られA =:= DirStateます。

于 2015-08-10T13:34:02.183 に答える