softwaremill/quicklens

Support `optionalSetTo` or `setToOptional`

jedesah opened this issue · 10 comments

I think it would be useful to have a version of setTo which accepts an Option and only changes the object if the value being passed in is Some.

Speaking of this, I was also wondering if the following feature would be useful:

// map
Person(35).modify(_.age).setToM(List(20, 28)) shouldEqual
  List(Person(20), Person(28))

// flatMap
List(Person(35)).modify(_.each.age).setToM(List(20, 28)) shouldEqual
  List(Person(20), Person(28))

I will probably implement it and send a PR if I like it.

adamw commented

Maybe it would be enough to locally pimp the PathModify and use its members: obj and doModify to implement both an optional/replicating modification?

Monadic modification is really useful, for example, given a Monad[Gen] and a QuicklensFunctor[Gen], one can use that in conjunction with ScalaCheck:

val genValidPerson: Gen[Person] =
  Gen.const(Person("John", 30))

val genInvalidPersonAge: Gen[Person] =
  genValidPerson.modify(_.each.age).setToM(Gen.oneOf(-1, 0))

forAll(genInvalidPersonAge) { person =>
  // should be invalid
}

Of course this can also be added on top in other ways, e.g. using monadic workflows:

val genValidPerson: Gen[Person] =
  Gen.const(Person("John", 30))

val genInvalidPersonAge: Gen[Person] = monadic[Gen] {
  genValidPerson.each.modify(_.age).setTo(Gen.oneOf(-1, 0).each)
}

forAll(genInvalidPersonAge) { person =>
  // should be invalid
}

But I think it does not work with closures, so it wouldn’t be possible to emulate usingM(f: A => M[A]).

adamw commented

But that would add a dependency on scalaz's/cat's/... Monad implementation?

adamw commented

Though I really like the example with quickcheck :)

IMHO scalaz/cats will add too much weight to this library. The idea was to add QuicklensMonad and let the users define their own instances (they can also define a bridge to scalaz/cats and get the instances for free). Alternatively the bridge can live in a separate module like quicklens-scalaz.

adamw commented

Definitely, adding scalaz/cats dependency would be way too much :)

I'm not at all happy having to define yet another XxxFunctor trait, but I guess there are no better options for now. That's why I'd like to avoid defining yet another Monad trait, and while the use-case is compelling, I think I would sway towards using an implicit class to extend PathModify with whatever monad implementation is available locally.

Maybe it would be good to document the approach instead of coding?

This seems fair, although the said functionality might as well be a library. Would you be interested in a PR with that as a separate module (“project” in SBT terms)?

adamw commented

Sure, a separate module sounds good as well :)