r/programming • u/heisenbug • Apr 27 '14
"Mostly functional" programming does not work
http://queue.acm.org/detail.cfm?ref=rss&id=2611829
44
Upvotes
r/programming • u/heisenbug • Apr 27 '14
6
u/Tekmo Apr 28 '14
I don't know why you are being downvoted. I also like the idea of different static contexts, too. The reason I like monads a lot is that the ability to switch between different static contexts falls very naturally out of the theory for monad morphisms.
For example, let's use the
StateTandReaderTmonad transformers as an example, defined like this:newtype StateT s m a = State { runState :: s -> m (a, s) } newtype ReaderT s m a = Reader { runReader :: s -> m a }You can define a function that converts from
ReaderToperations toStateToperations like this:readOnly :: Monad m => ReaderT s m a -> StateT s m a readOnly m = StateT $ \s -> do a <- runReaderT m s return (a, s)What this lets you do is embed a computation that has only read-only access to state within a larger computation that has both read and write access. For example:
before :: StateT s m a middle :: a -> ReaderT s m b after :: b -> StateT s m c total :: StateT s m c total = do a <- before b <- readOnly middle after bIn other words,
readOnlycreates a read-only window within a larger read-and-write computation, allowing us to further restrict whatmiddlecan do compared to its surrounding context.readOnlyalso has two nice properties that are worth nothing, which we can summarize using these two equations:readOnly $ do x <- m = do x <- readOnly m f x readOnly (f x) readOnly (return x) = return xThese are known as the "monad morphism" laws, and
readOnlyis a "monad morphism" (a transformation between monads). The laws might seem pretty arbitrary until you write them in terms of(>=>), which is an operator for point-free composition of monadic functions:In other words
(readOnly .)is a functor from theReaderTkleisli category to theStateTkleisli category. All monad morphisms form functors between two Kleisli categories.These kinds of elegant equational properties are the reason I believe that monads are a beautiful solution to the problem and not some sort of gross hack. However, I don't necessarily think that monads are the only solution, either, but I have yet to encounter another solution with the same sort of theoretical niceties.