@@ -0,0 +1,399 @@
1+{-# LANGUAGE RankNTypes #-}
3+-- | This module implements the 'Boggle' type which exists for its
4+-- 'Applicative' instance that takes advantage of the laws of the
5+-- 'Applicative' class to rearrange the applications of the underlying
6+-- type's 'Applicative' instance. These transformations collect all of
7+-- the pure values using in 'pure' and 'fmap' calls into a single place
8+-- which enables GHC to aggressively optimize them.
10+-- == Optimization Goals
12+-- The goal for rewriting values defined in terms of 'Applicative' operations
13+-- will be to normalize them into a form that gives GHC the most opportunity
14+-- to simply the resulting expression as possible without knowing anything
15+-- about the particular 'Applicative' instance that that it satisfies the class
18+-- The following type characterizes our desired normal form.
20+-- > data Normal :: (* -> *) -> * -> * where
21+-- > Pure :: a -> Normal f a
22+-- > Normal1 :: Normal1 f a -> Normal f a
24+-- > data Normal1 :: (* -> *) -> * -> * where
25+-- > Ap :: Normal1 f (a -> b) -> f a -> Normal1 f b
26+-- > Normal2 :: Normal2 f a -> Normal1 f a
28+-- > data Normal2 :: (* -> *) -> * -> * where
29+-- > Fmap :: (a -> b) -> f a -> Normal2 f b -- function ≠ 'id'
30+-- > Lift :: f a -> Normal2 f a
32+-- While this type on its own is simpler than some of the types that follow,
33+-- implementing '<$>' and '<*>' for this type would require recusion to deal
34+-- with the left-recursion found in this type:
36+-- > f <$> Ap mg mx = Ap ((f .) <$> mg) mx
37+-- > f <$> Normal2 mx = Normal2 (f <$> x)
39+-- == Optimization Techniques
41+-- This transformation uses four primary techniques to achieve optimization.
43+-- [/avoid recursion/]
45+-- Recursive functions interfere with GHC's ability to inline and optimize
46+-- function applications. Each of the following transformations will need
47+-- to be written in a way that enables GHC to inline all of the definitions
48+-- and optimize away all of the intermediate structures. If the
49+-- intermediate structures or the operations on them were written
50+-- recursively this would not be possible.
52+-- [/multiple equivalent representations/]
54+-- There are cases where we don't know what the optimal representation for
55+-- a value will be until that value is actually used. In the following code
56+-- we see this happen with 'MapK1' and 'ApK1'. Due to inlining and
57+-- optimization the representation that was not needed can be eliminated
60+-- [/free structures/]
62+-- In order to optimize values according to laws that they satisfy, we'll
63+-- need the structures that these laws operate over to be explicit. This
64+-- will enable the operations to determine when a transformation is
65+-- appropriate and apply it.
67+-- 'MapK' tracks the eventual argument to 'fmap'. 'ApK' tracks the eventual
68+-- left-most argument to '<.>'. 'PureK' tracks uses of 'pure'.
70+-- [/typed tagless final encodings/]
72+-- The /typed tagless final/ approach for writing a computation involves
73+-- defining the signature of the operations that a compution can be
74+-- constructed from and then defining values completely within that
75+-- signature. This technique will specifically apply to computations
76+-- written generically in terms of the 'Applicative' signature.
78+-- Because the 'Applicative' signature carries a number of laws that
79+-- any interpretation of it must satisfy, we are able to write our
80+-- own interpretations in terms of existing interpretations but which
81+-- use the laws that these existing interpretations must satisfy.
83+-- It happens that it is now quite common to define computations in this
84+-- style with classes like 'Functor' and 'Applicative' due to the
85+-- popularlity of the @lens@ package and it's heavy use of this pattern.
90+ , liftBoggle, lowerBoggle
94+ , ApWrap(..), liftApWrap, lowerApWrap
96+ , MapK(..), (<<$>), liftMapK, lowerMapK
97+ -- * fmap fusion with fmap id law
98+ , MapK1(..), liftMapK1, lowerMapK1
99+ -- * '<*>' reassociation
100+ , ApK(..), (<<.>), liftApK, lowerApK
101+ -- * '<.>' reassociation
102+ , ApK1(..), liftApK1, lowerApK1
103+ -- * pure elminination
104+ , PureK(..), liftPureK, lowerPureK
105+ -- * '>>=' reassociation
106+ , BindK(..), liftBindK, lowerBindK, liftBindK1, liftBindK2
109+import Control.Applicative
112+infixl 4 <<$>, <<.>, <.>
114+type LensLike f s t a b = (a -> f b) -> (s -> f t)
115+type Traversal s t a b = forall f. Applicative f => LensLike f s t a b
116+type Traversal' s a = Traversal s s a a
118+-- | This class is a mid-point between 'Functor' and 'Applicative'
119+-- for types that support the '<*>' operation but not 'pure'
121+-- It provides an operation for lifted function application ('<.>')
123+-- Implementations of this class must follow these laws:
127+-- * @(\\f g x -> f (g x)) '<$>' mf '<.>' mg '<.>' mx = mf '<.>' (mg '<.>' mx)@
131+-- * @(\\g x -> f (g x)) '<$>' mg '<.>' mx = f '<$>' (mg '<.>' mx)@
132+-- * @(\\g x -> g (f x)) '<$>' mg '<.>' mx = mg '<.>' (f '<$>' mx)@
134+-- If @f@ is an 'Applicative', it should satisfy
137+class Functor f => Apply f where
138+ -- | Lifted application
139+ (<.>) :: f (a -> b) -> f a -> f b
140+ {-# MINIMAL (<.>) #-}
142+------------------------------------------------------------------------
144+-- | 'ApWrap' provides an 'Apply' instance in terms of an underlying
145+-- 'Applicative' instance.
146+newtype ApWrap f a = ApWrap (f a)
148+liftApWrap :: f a -> ApWrap f a
151+lowerApWrap :: ApWrap f a -> f a
152+lowerApWrap (ApWrap fa) = fa
154+instance Functor f => Functor (ApWrap f) where
155+ fmap f (ApWrap x) = ApWrap (f <$> x)
157+-- | @('<.>') = ('<*>')@
158+instance Applicative f => Apply (ApWrap f) where
159+ ApWrap f <.> ApWrap x = ApWrap (f <*> x)
162+------------------------------------------------------------------------
164+-- | This type fuses all uses of 'fmap' into a single use of 'fmap' on
165+-- the underlying 'Functor' @f@.
167+-- There is a natural isomorphism between @f@ and @'MapK' f@ witnessed by
168+-- 'liftMapK' and 'lowerMapK' which is respected by the 'Functor' instance
170+newtype MapK f a = MapK (forall b. (a -> b) -> f b)
172+liftMapK :: Functor f => f a -> MapK f a
173+liftMapK fa = MapK (<$> fa)
175+lowerMapK :: MapK f a -> f a
176+lowerMapK fa = id <<$> fa
178+-- | Like '<$>' but removes the 'MapK'
179+(<<$>) :: (a -> b) -> MapK f a -> f b
182+-- | Note: no underlying 'Functor' required
183+instance Functor (MapK f) where
184+ fmap f x = MapK (\z -> (z . f) <<$> x)
186+------------------------------------------------------------------------
188+-- | 'MapK1' extends 'MapK' to detect when a lift is immediately followed
189+-- by a lower. In this case no 'fmap' will be used at all!
191+-- There is a natural isomorphism between @f@ and @'MapK1' f@ witnessed by
192+-- 'liftMapK1' and 'lowerMapK1' which is respected by the 'Functor' and
193+-- 'Apply' instance of @'MapK1' f@.
194+data MapK1 f a = MapK1 (f a) (MapK f a)
195+ -- ^ Invariant: @(x :: f a) == 'lowerMapK' (y :: 'MapK' f a)
197+liftMapK1 :: Functor f => f a -> MapK1 f a
198+liftMapK1 fa = MapK1 fa (liftMapK fa)
200+lowerMapK1 :: MapK1 f a -> f a
201+lowerMapK1 (MapK1 fa _) = fa
203+-- | Note: no underlying 'Functor' required
204+instance Functor (MapK1 f) where
205+ fmap f (MapK1 _ g) = MapK1 (f <<$> g) (f <$> g)
207+instance Apply f => Apply (MapK1 f) where
208+ MapK1 f g <.> MapK1 x _ =
209+ MapK1 (f <.> x) (MapK (\k -> (\a b -> k (a b)) <<$> g <.> x))
211+------------------------------------------------------------------------
213+-- | 'ApK' provides an 'Apply' instance in terms of the underlying @f@'s
214+-- 'Apply' instance, but left-associates all '<.>'. Lowering this type
215+-- requires an 'Applicative' instance.
217+-- There is a natural isomorphism between @f@ and @'ApK' f@ witnessed by
218+-- 'liftApK' and 'lowerApK' which is respected by the 'Functor' and
219+-- 'Apply' instance of @'ApK' f@.
220+newtype ApK f a = ApK (forall b. f (a -> b) -> f b)
222+liftApK :: Apply f => f a -> ApK f a
223+liftApK fa = ApK (<.> fa)
225+lowerApK :: Applicative f => ApK f a -> f a
226+lowerApK fa = pure id <<.> fa
228+-- | Like '<.>' but removes 'ApK'
229+(<<.>) :: f (a -> b) -> ApK f a -> f b
232+instance Functor f => Functor (ApK f) where
233+ fmap f x = ApK (\g -> (\a b -> a (f b)) <$> g <<.> x)
235+-- | Note that this 'Apply' instance only uses the underlying 'Functor'
236+instance Functor f => Apply (ApK f) where
237+ f <.> x = ApK (\g -> (.) <$> g <<.> f <<.> x)
239+------------------------------------------------------------------------
241+-- | This type provides an 'Apply' instance in terms of the underlying @f@
242+-- type's 'Apply' instance, but it left-associates all uses of '<.>'
244+-- There is a natural isomorphism between @f@ and @'ApK1' f@ witnessed by
245+-- 'liftApK1' and 'lowerApK1' which is respected by the 'Functor' and
246+-- 'Apply' instance of @'ApK1' f@.
247+data ApK1 f a = ApK1 (f a) (ApK f a)
248+ -- ^ Invariant: @(x :: f a) == 'lowerApK' (y :: 'ApK' f a)@
250+instance Functor f => Functor (ApK1 f) where
251+ fmap f (ApK1 x y) = ApK1 (f <$> x) (f <$> y)
253+-- | Note that this 'Apply' instance only uses the underlying 'Functor'
254+instance Functor f => Apply (ApK1 f) where
255+ ApK1 fl fr <.> ApK1 _ x = ApK1 (fl <<.> x) (fr <.> x)
257+liftApK1 :: Apply f => f a -> ApK1 f a
258+liftApK1 fa = ApK1 fa (liftApK fa)
260+lowerApK1 :: ApK1 f a -> f a
261+lowerApK1 (ApK1 fa _) = fa
263+------------------------------------------------------------------------
265+-- | 'PureK' lifts a type @f@ having an 'Apply' instance to a type
266+-- having an 'Applicative' instance. The 'Applicative' laws for 'pure'
267+-- are used to rewrite all uses of pure into either a single 'pure' or
268+-- into uses of 'fmap' where possible.
270+-- There is a natural isomorphism between @f@ and @'PureK' f@ witnessed by
271+-- 'liftPureK' and 'lowerPureK' which is respected by the 'Functor',
272+-- 'Apply', and 'Applicative' instance of @'PureK' f@.
273+data PureK f a = Pure a | Dirty (f a)
275+lowerPureK :: Applicative f => PureK f a -> f a
276+lowerPureK (Pure a) = pure a
277+lowerPureK (Dirty fa) = fa
279+liftPureK :: f a -> PureK f a
282+instance Functor f => Functor (PureK f) where
283+ fmap f (Pure x) = Pure (f x)
284+ fmap f (Dirty x) = Dirty (f <$> x)
286+instance Apply f => Apply (PureK f) where
287+ Dirty f <.> Dirty x = Dirty (f <.> x)
288+ Pure f <.> x = f <$> x
289+ f <.> Pure x = ($ x) <$> f
291+-- Note that this 'Applicative' instance only uses the underlying 'Apply'
292+instance Apply f => Applicative (PureK f) where
296+-- | Transform the underlying type.
297+natPureK :: (f a -> g a) -> PureK f a -> PureK g a
298+natPureK f (Dirty fa) = Dirty (f fa)
299+natPureK _ (Pure a) = Pure a
301+------------------------------------------------------------------------
303+-- | @'Boggle' f@ is isomorphic to @f@ up to the 'Applicative' laws.
304+-- Uses of '<$>' on this type are combined into a single use of '<$>'
305+-- on the underlying @f@ type. Uses of 'pure' are combined and transformed
306+-- to '<$>' where possible. Uses of '<*>' are reassociated to the left.
308+-- 'PureK' is on the outside because any use of 'pure' is immediately
309+-- intercepted and translated into 'fmap' when needed. 'ApK1' doesn't
310+-- even have/need an 'Applicative' instance.
312+-- 'ApK1' is next because it uses the 'Functor' instance from its underlying
313+-- type and we want the 'MapK' layer to intercept and fuse all of those 'fmap'
316+-- 'MapK1' is down toward the bottom of the stack to be able to fuse the uses
317+-- of 'fmap' from all the previous layers into one single use.
319+-- 'ApWrap' is at the very bottom. It only exists to provide an 'Apply'
320+-- instance to the underlying type @f@.
322+-- There is a natural isomorphism between @f@ and @'Boggle' f@ witnessed by
323+-- 'liftBoggle' and 'lowerBoggle' which is respected by the 'Functor',
324+-- 'Apply', and 'Applicative' instance of @'Boggle' f@.
325+newtype Boggle f a = Boggle (PureK (ApK1 (MapK1 (ApWrap f))) a)
327+instance Functor (Boggle f) where
328+ fmap f (Boggle x) = Boggle (f <$> x)
331+instance Applicative (Boggle f) where
332+ pure x = Boggle (pure x)
334+ Boggle x <*> Boggle y = Boggle (x <*> y)
335+ {-# INLINE (<*>) #-}
337+liftBoggle :: Applicative f => f a -> Boggle f a
338+liftBoggle = Boggle . liftPureK . liftApK1 . liftMapK1 . liftApWrap
339+{-# INLINE liftBoggle #-}
341+-- | 'lowerBoggle' lowers the 'ApK1' and 'MapK' layers first before lowering
342+-- the 'PureK' layer. This ensures that any 'fmap' uses in the 'PureK' layer
343+-- are intercepted by the 'MapK' layer, but the final (possible) use of 'pure'
344+-- in the case that 'pure' is going to be used will happen in the underlying
346+lowerBoggle :: Applicative f => Boggle f a -> f a
348+ = lowerPureK . natPureK (lowerApWrap . lowerMapK1 . lowerApK1) . (\(Boggle b) -> b)
349+{-# INLINE lowerBoggle #-}
351+-- | Optimize a 'Traversal' by fusing the '<$>'s and left-associating the '<*>'s
353+-- This function will only work well on non-recursive traversals. For an example
354+-- of using this technique on recursive cases see "Data.Traversable.Generic".
355+boggling :: Applicative f => LensLike (Boggle f) s t a b -> LensLike f s t a b
356+boggling l = \f x -> lowerBoggle (l (liftBoggle . f) x)
357+{-# INLINE boggling #-}
360+------------------------------------------------------------------------
362+-- | Local implementation of @Codensity@ type from @kan-extensions@.
363+-- This type captures the concept of a partially applied '>>=' function.
364+newtype BindK f a = BindK { runBindK :: forall b. (a -> f b) -> f b }
366+instance Functor (BindK f) where
369+instance Applicative (BindK f) where
370+ pure x = BindK $ \k -> k x
373+instance Alternative f => Alternative (BindK f) where
374+ empty = BindK $ \_ -> empty
375+ (<|>) = liftBindK2 (<|>)
376+ {-# INLINE (<|>) #-}
378+instance Monad (BindK f) where
379+ BindK m >>= f = BindK $ \k -> m $ \a -> runBindK (f a) k
381+instance Alternative f => MonadPlus (BindK f)
383+-- | Run a @'BindK' f@ computation with 'pure' as the final continuation.
384+lowerBindK :: Applicative f => BindK f a -> f a
385+lowerBindK (BindK k) = k pure
387+liftBindK :: Monad f => f a -> BindK f a
388+liftBindK fa = BindK (fa >>=)
390+liftBindK1 :: (forall a. f a -> f a) -> BindK f b -> BindK f b
391+liftBindK1 f (BindK k) = BindK (f . k)
393+liftBindK2 :: (forall a. f a -> f a -> f a) -> BindK f b -> BindK f b -> BindK f b
394+liftBindK2 f (BindK m) (BindK n) = BindK (\k -> f (m k) (n k))
396+traversePair f (a, b) = (,) <$> f a <*> f b
398+test :: Applicative f => (a -> f a) -> (a, a) -> f (a, a)
399+test = boggling traversePair