Question

Trying to wrap my mind around Scalaz State monad and monad transformers.

What I want to do is to implement something like:

def transform[S,A](o: State[Option[S], A]) :Option[State[S,A]]

Is this even possible ? How would I do it ?

Was it helpful?

Solution

There is a legitimate implementation that you will not like

def transform[S,A](o: State[Option[S], A]: Option[State{S,A]] = None

If you try for another implementation, the question is when can transform return a Some? State[Option[S], A] is Option[S] => (Option[S], A). And you are trying to get a S => (S,A). Given s: S, you must return an (S,A) pair. Passing s to the original state is ok, you just wrap it in Some. But you get an (Option[S], A) which may lack an S. No way to transform that to an (S,A). Except if you accept that the state will sometime fail.

There is no way you can know in advance that o will never return a None state (even if you further constraint to not returning a None state when given a Some state), so there is no way you can make an useful decision as to whether transform should return Some or None. You can either return None all the time, or Some all the time, and have State application sometime fail. Whichever one you choose, the result type is useless. If None, the transform function itself is useless, if Some, typing the result as an Option brings you nothing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top