Expressing the notion of validation using lenses?

65 views
Skip to first unread message

harv...@cse.ohio-state.edu

unread,
Nov 30, 2014, 8:08:41 PM11/30/14
to scala-...@googlegroups.com
Dear Monocle crew,

This library is fantastic! Thank you very much for putting it together and releasing it for the community!

If you don't mind, I have a question about whether or not it is possible to express some scalaz validation-like stuff using the optics available in monocle. (More generally, I am fiddling around with the algebra and trying to understand the precise relationships between picklers, parsers, and lenses.)

Consider a "pickler":
pickle: A => B
unpickle: B => Either<E, A>

...which can convert ("pickle") things of type A into "pickles" of type B. It can also try to "unpickle" something of type B, which results in an Either<E, A>, where E represents an error. (Usually, in practice, E is string, and its value contains an error message).

Scalaz has (or had?) some nice functionality with the Validation type where you could do something like this using its "require" method:

(42).require(x => x > 0, "Must be positive!");
res0: Right[string, int](42)

(-100).require(x => x > 0, "Must be positive!");
res1: Left[string, int]("Must be positive!")

Once you use the require method, you can then just do a "foo.map(new Thingy(_))" or whatever if you want to transform foo into a Thingy. You get back an Either[string, Thingy], so you get a chance to handle any errors that occurred during the transformation.

Is there any way to model this kind of validation using optics? Prisms are pretty close, but the types don't seem to work out quite right. Specifically, I was hoping for something with these type signatures:

getOrModify: Func[S, Either[E, A]]
reverseGet: Func[A, S]

to unpickle x. However, a prism seems to look like this:

getOrModify: Func[S, Either[S, A]]
reverseGet: Func[A, S]

Does anyone have an idea if it's possible to emulate something that captures the spirit of the scalaz validation stuff above using monocle?

Thanks!

William

Julien Truffaut

unread,
Dec 1, 2014, 10:41:15 AM12/1/14
to scala-...@googlegroups.com, harv...@cse.ohio-state.edu
Hi William,

As you mentioned, Prism is the correct Optic to describe an encoding / decoding relation. However, a Prism can only tell you if it succeeds or fails via Maybe but you cannot get the reason of the failure. It would definitely be a useful feature but I don't know if it can fit in the Optic theory. I will try to have a look but feel free to make any proposal.

Thank you for the nice feedback :)
Reply all
Reply to author
Forward
0 new messages