5 ms·
How would you apply monads to solve the context problem? Hard for me to imagine what that would look like
by philosopher1234 6y ago
How would you apply monads to solve the context problem? Hard for me to imagine what that would look like
- dllthomas 6y agoI think what they have in mind is a Reader monad. newtype Reader r a = Reader { runReader :: r -> a } instance Monad (Reader r) where pure x = Reader (\ _ -> x) m >>= f = Reader (\ r -> runReader (f (runReader m r)) r) which allows us to define: getContext :: Reader r r getContext = Reader (\ r -> r) and which spares us threading the context manually. I don't think that's such a big deal, so long as there's only one thing we're threading. In some languages, we can be generic over "contexts which provide the thing I want, whether they do other things or not", which is sometimes a much bigger win.
- solatic 6y agoContext is like Schrödinger's Cat, you don't know if the Context you're working in is alive or dead (i.e. cancelled, timed out, etc.), but you have to keep passing it forward, one intermediate network call after the next, as long as its status is uncertain. Only when the request fully returns, or is actively cancelled, do you know whether the request is alive or dead. The Maybe monad deals with the same issue. You have a series of function calls, each of which might or might not be legal, because you never know if you actually have the parameter for the next function call. Maybe you do, maybe you don't. If you take the naive approach to solving the issue, you pass along Schrödinger's Cat each step along the way. You intertwine the concern of the algorithm you're trying to write with the uncertainty of whether you're carrying a live cat or a dead one. It can work, but it's ugly. The monadic approach allows you to separate these concerns. You write your algorithm as if you know for a fact that the cat is alive. If the cat were ever to be revealed to be dead along the path, it doesn't matter, the monad separated the consequences of dealing with the live or dead cat from the rest of your algorithm. The rest of your algorithm simply doesn't get run. Context is the same. You get to write code as if the context is always valid. You don't have to worry about context being cancelled, or timed out, or anything else. You take all those concerns and relate to them separately, in one place, where they can be neatly dealt with. The whole point of the monadic pattern is to propagate state in such a way that it doesn't interfere with the pure algorithm which you're trying to write. You write the pure algorithm separately, and then use it within the monadic context of Context, so to speak.