Monocle Options are the same as partial lenses?

Monocle options have the following access functions (for Optional[C,A]):

getOption: C => Option[A]
set: A => C => C

This contradicts the initial definition of (partial) asymmetric data lenses. I would expect:

getOption: C => Option[A]
setOption: A => C => Option[C]

What is the reason for this? How to get classic partial lenses with Monocle? When programming lenses, I found that it is much more problematic to provide an aggregate set than to get ...

+4
source share
1 answer

Consider the following partial lens for finding values ​​in a list by index (note that this is just a pedagogical example, as it monocle.std.list.listIndexprovides this functionality from a shelf):

import monocle.Optional

def listIndexOptional[A](i: Int): Optional[List[A], A] =
  Optional[List[A], A](_.lift(i))(a => l =>
    if (l.isDefinedAt(i)) l.updated(i, a) else l
  )

Optional, :

val thirdString = listIndexOptional[String](2)

:

scala> thirdString.set("0")(List("a", "b", "c"))
res4: List[String] = List(a, b, 0)

scala> thirdString.set("0")(List("a", "b"))
res5: List[String] = List(a, b)

, , . , , setOption:

scala> thirdString.setOption("0")(List("a", "b", "c"))
res6: Option[List[String]] = Some(List(a, b, 0))

scala> thirdString.setOption("0")(List("a", "b"))
res7: Option[List[String]] = None

, Optional.apply A => S => S, , , , getOption setOption , .

, Optional A => S => Option[S], getOrElse(s) .

+6

Source: https://habr.com/ru/post/1615992/


All Articles