ekmett/free — pull request #18 by fizruk (2013-09-22 11:10:50+00:00)
Title: Added wrapT

I found this function useful in a rather specific case — transformation of monadic values of type `t (Free f) a`. The type signature of `wrapT` suggested though that it could be useful elsewhere.

This implementation seems to work for my purposes, though I'm not sure about:

* whether it is properly handling monadic effects and
* whether it could be made efficient (if it's not).

Below I present my thoughts on the first issue.

```haskell
wrapT :: (Functor f, MonadFree f m, MonadTrans t, Monad (t m)) => f (t m a) -> t m a
wrapT = join . lift . liftF
```

From `liftF = wrap . fmap return`:

```haskell
fmap return :: f a -> f (m a)
wrap :: f (m a) -> m a
```

`f (m a)` is a monadic value m a wrapped in a container/context `f`. `wrap` may use monadic value `m a` multiple times, but its type `f (m a) -> m a` ensures that the value is used at least once.

Since in `wrap . fmap return` monadic value is has form `return x`, it is irrelevant whether it is called multiple times or not and when it is called inside the result.

Thus we can assume that application of `wrap . fmap return` results in somewhat like `mf >> m`, where `mf` is monadic computation, obtained from the actual form of `f` and `m` is computation stored inside value of type `f (m a)`.

If I'm correct, this implicates that monadic effects are carried out properly. `wrap . fmap return` internally differs from `return . wrap`, but observationally they are equivalent.

Thus `join . lift . liftF` should equivalent to `join . lift . return . wrap` which is equivallent to `wrap` (when it is defined, i.e. there exists an instance `MonadFree f (t m)`).