Free (monad over monads)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}

import Control.Monad.Morph

data HFree t m a where
    Lift :: m a -> HFree t m a
    Gen :: t m a -> HFree t m a
    Hoist :: (forall x . n x -> m x) -> HFree t n a -> HFree t m a
    Embed :: (forall x . n x -> HFree t m x) -> HFree t n a -> HFree t m a

instance MonadTrans (HFree t) where
    lift = Lift

instance MFunctor (HFree t) where
    hoist = Hoist

instance MMonad (HFree t :: (* -> *) -> * -> *) where
    embed = Embed

-- foldMap  :: Monoid m => (a -> m) -> [a] -> m

-- foldMap1 :: Monad m => (forall x . f x -> m x) -> Free f a -> m a

foldMap0
    :: (MMonad s, Monad m)
    => (forall n x . t n x -> s n x) -> HFree t m a -> s m a
foldMap0 _ (Lift m) = lift m
foldMap0 k (Gen t)  = k t
foldMap0 k (Hoist f x) = hoist f (foldMap0 k x)
foldMap0 k (Embed f x) = embed (\y -> foldMap0 k (f y)) (foldMap0 k x)

{-
data DB f x = Select (String -> Producer Row (Free f) x)

newtype Dest m a = Dest (IO (m a))

Dest (Dest m) a -> Dest m a

foo :: IO (IO (m a)) -> IO (m a)

foldMap0
    :: (forall x . DB IO x -> Dest IO x) -> HFree DB IO a -> Dest IO a
-}


{-
foo :: StateT s (StateT s m) a -> StateT s m a

runStateT foo :: s -> StateT s m (s, a)

runStateT . runStateT foo :: s -> s -> m (s, (s, a))
-}
32:33: Warning: Avoid lambda
Found:
\ y -> foldMap0 k (f y)
Why not:
foldMap0 k . f