Lens on a Map do not set a key if it doesn't exist in this Map already

Open
#775 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
scala
Domain
tooling

Research direction

Start with the Index and At abstractions and implicits described in the issue, then compare their behavior with the supplied fromAt implementation for an absent Map key. Decide whether the expected insertion behavior belongs in Index or another abstraction; the issue is complete only when that scope and behavior are resolved.

Written by the indexing model from the issue text.

Description

FAQ

Hi, thank you very much for this library, it helps me a lot every day, but I've faced a strange issue, I'm not sure if it is a bug or not, but it's behavior is unexpected for me. What I want to do is to have a Lens for a collection like Map, that allows me to do something like this:

val map: Map[String, Vector[String]] = Map.empty
val result = map.applyLens(defaultIndex("foo")).modify(_ +: "foo")
assert(result == Map("foo" -> Vector("foo")))

But with the default implementation of monocle.function.Index and all it's implicits it doesn't work, I had to define a custom fromAt for it.

Here is my code:

def fromAt[S, I, A](implicit ev: At[S, I, Option[A]]): Index[S, I, A] =
  Index { i =>
    val lens = ev.at(i)
    Optional(lens.get)(a => s => lens.set(Some(a))(s))
  }

Would that be a good idea to add something like this to the Monocle? Or maybe there is something that solves my problem better? I have a working implementation already.

I think however that Index might not be the best solution for this use case, and maybe it should be a different abstraction for it.

Dominant language
Scala
Stars
1.7k
Forks
207
Avg merge
7h 59m
Merged PRs (30d)
5

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from optics-dev/Monocle

All issues in optics-dev/Monocle

Similar issues

More Scala issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.