/
Internal.hs
2202 lines (1806 loc) · 71.3 KB
/
Internal.hs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# Language CPP #-}
{-# Language GeneralizedNewtypeDeriving #-}
{-# Language Unsafe #-}
{-# options_haddock not-home #-}
-- |
-- Copyright : (c) 2011-2021 Edward Kmett,
-- (c) 2017-2021 Aaron Vargo,
-- (c) 2021 Oleg Grenrus
-- License : BSD-2-Clause OR Apache-2.0
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : non-portable (ghc 8.6+)
module Data.Rep.Internal where
import Control.Applicative
import Control.Applicative.Backwards
import Control.Arrow
import Control.Monad.Fix
import Control.Monad.Reader
import Control.Monad.Trans.Identity
import Control.Monad.Zip
import Data.Coerce
import Data.Complex
import Data.Data
import Data.Dependent.Sum
import Data.Function.Coerce
import Data.Foldable (fold)
import Data.Foldable.WithIndex
import Data.Function
import Data.Functor
import Data.Functor.Classes
import Data.Functor.Compose
import Data.Functor.Identity
import Data.Functor.Product
import Data.Functor.Reverse
import Data.Functor.WithIndex
import Data.GADT.Compare
import Data.HKD
import Data.HKD.Contravariant
import Data.HKD.Index.Internal
import Data.Kind
import Data.Maybe
import qualified Data.Monoid as Monoid
import Data.Ord (Down(..))
import Data.Orphans ()
import Data.Profunctor
import qualified Data.Semigroup as Semigroup
import Data.Some
import Data.Traversable
import Data.Traversable.WithIndex
import Data.Type.Bool
import Data.Type.Coercion
import Data.Type.Equality
import Data.Void
import GHC.Generics
import GHC.TypeLits
import Numeric
import Numeric.Fin.Internal
import Unsafe.Coerce
#ifdef MIN_VERSION_tagged
import Data.Tagged
#endif
#ifdef MIN_VERSION_comonad
import Control.Comonad
import Control.Comonad.Trans.Traced
#endif
#if MIN_VERSION_ghc_prim(0,7,0)
import GHC.Tuple (Solo)
#endif
-- |
--
-- Due to the lack of non-trivial comonoids in Haskell, we can restrict
-- ourselves to requiring a 'Functor' rather than some Coapplicative class.
-- Categorically every 'Representable' functor is actually a right adjoint,
-- and so it must be 'Representable' endofunctor and preserve all limits.
-- This is a fancy way of saying @f@ is isomorphic to @(->) x@ for some x.
-- We use the name @'Log' f@ for @x@.
--
--
-- @
-- 'tabulate' '.' 'index' ≡ 'id'
-- 'index' '.' 'tabulate' ≡ 'id'
-- @
--
-- To be distributable a container will need to have a way to consistently
-- zip a potentially infinite number of copies of itself. This effectively
-- means that the holes in all values of that type, must have the same
-- cardinality, fixed sized vectors, infinite streams, functions, etc.
-- and no extra information to try to merge together.
class Indexable f where
-- | Defaults to @'Log' ('Rep1' f)@ when @f@ is non-recursive, otherwise to 'Logarithm'.
type Log f
type Log f = DefaultLog f
type KnownSize f :: Maybe Nat
type KnownSize f = DefaultKnownSize f
-- | Defaults to 'indexLogarithm' when @'Log' f = 'Logarithm' f@, otherwise to 'indexGeneric'
index :: f a -> Log f -> a
default index :: DefaultIndex f => f a -> Log f -> a
index = defaultIndex
{-# inline index #-}
class (Indexable f, Functor f) => Representable f where
-- | Defaults to 'tabulateLogarithm' when @'Log' f = 'Logarithm' f@, otherwise to 'tabulateGeneric'
tabulate :: (Log f -> a) -> f a
default tabulate :: DefaultTabulate f => (Log f -> a) -> f a
tabulate = defaultTabulate
{-# inline tabulate #-}
-- | Scatter the contents of an 'FFunctor'. This admittedly complicated operation
-- is necessary to get asymptotically optimal performance for 'Representable' functors
-- like Mealy and Moore machines that have many layers to them.
--
-- If you have a 'Generic1' instance for your 'Functor', this should be able to be
-- generated automatically. Otherwise, if you must, you can use 'scatterDefault' as
-- a fallback in terms of 'tabulate' and 'index', which is offered in terms of the
-- law relating 'scatter' to 'tabulate' and 'index':
--
-- @
-- 'scatter' phi wg ≡ 'tabulate' \\x -> 'ffmap' (\\g -> 'Identity' '$' 'index' (phi g) x) wg
-- @
--
-- Defaults to 'scatterGeneric'
--
-- The obvious API for this function is the much simpler
--
-- @
-- 'dist ':: ('Representable' f, 'FFunctor' w) => w f -> f (w 'Identity')
-- @
--
-- However, most uses of this function aren't interested in leaving a @w 'Identity'@ inside @f@
-- and immediately 'ffmap' to replace it. However, most implementations have to 'ffmap' to put
-- it there. This leads to two unfused 'ffmap' calls. By adding a @(w 'Identity' -> r)@ step
-- we clean up that concern.
--
-- Another concern with the obvious implementation as a class method is that 'w f' knows nothing
-- about whether 'w' takes a representational argument. As a result, @GeneralizedNewtypeDeriving@
-- wouldn't work for this class if this was a member. (For an example of this, try to use GND on
-- 'Traversable' today!) Adding a natural transformation before we process allows this
-- dictionary to be derived with GND. This latter mapping is a lot less useful, so we supply
--
-- @
-- 'distrib' :: ('Representable' f, 'FFunctor' w) => w f -> (w 'Identity' -> r) -> f r
-- @
--
-- as well, outside o the class, which is quite concise for many workloads.
scatter :: FFunctor w => (w Identity -> r) -> (g ~> f) -> w g -> f r
default scatter
:: (Generic1 f, Representable (Rep1 f), FFunctor w)
=> (w Identity -> r) -> (g ~> f) -> w g -> f r
scatter = scatterGeneric
{-# inline scatter #-}
-- | derive tabulate via 'Generic1' when @'Log' f@ is (a possible newtype of)
-- @'Log' ('Rep1' f)@
tabulateGeneric
:: forall f a.
(Representable (Rep1 f), Generic1 f, Coercible (Log f) (Log (Rep1 f)))
=> (Log f -> a) -> f a
tabulateGeneric = coerce (to1 . tabulate :: (Log (Rep1 f) -> a) -> f a)
{-# inline tabulateGeneric #-}
-- | derive 'index' via 'Generic1' when @'Log' f@ is (a possible newtype of)
-- @'Log' ('Rep1' f)@
indexGeneric
:: forall f a.
(Indexable (Rep1 f), Generic1 f, Coercible (Log f) (Log (Rep1 f)))
=> f a -> Log f -> a
indexGeneric = coerce (index . from1 :: f a -> Log (Rep1 f) -> a)
{-# inline indexGeneric #-}
-- | derive 'scatter' via 'Generic1'
scatterGeneric
:: (Representable (Rep1 f), Generic1 f, FFunctor w)
=> (w Identity -> r) -> (g ~> f) -> w g -> f r
scatterGeneric = \k phi -> to1 . scatter k (from1 . phi)
{-# inline scatterGeneric #-}
-- | This pattern synonym lets you work with any 'Representable' functor as if
-- it were a function.
pattern Tabulate :: Representable f => (Log f -> a) -> f a
pattern Tabulate i <- (index -> i) where
Tabulate i = tabulate i
-- * Generic derivation
data LogType
= UseLogarithm
| UseLogFin
| UseLogRep
type family HasLogType f t :: LogType where
HasLogType f (Logarithm f) = 'UseLogarithm
HasLogType f (Fin x) = If (x == Size f) 'UseLogFin 'UseLogRep
HasLogType f t = 'UseLogRep
type LogTypeOf f = HasLogType f (Log f)
type DefaultLog f = DefaultLog' (GInvalid (Rep1 f)) f
type family DefaultLog' (containsRec1 :: Bool) f :: Type where
DefaultLog' 'True f = Logarithm f
DefaultLog' 'False f = DefaultLog'' (GUnknownSize (Rep1 f)) f
type family DefaultLog'' (hasUnknownSize :: Bool) f :: Type where
DefaultLog'' 'True f = Log (Rep1 f)
DefaultLog'' 'False f = Fin (Size f)
type family DefaultTabulateImplC (t :: LogType) f :: Constraint where
DefaultTabulateImplC 'UseLogarithm f = (Representable f, Log f ~ Logarithm f)
DefaultTabulateImplC 'UseLogRep f = (Generic1 f, Representable (Rep1 f), Coercible (Log f) (Log (Rep1 f)))
DefaultTabulateImplC 'UseLogFin f = (Generic1 f, GTabulateFin (Rep1 f), Size f ~ GSize (Rep1 f), Log f ~ Fin (GSize (Rep1 f)))
type family DefaultIndexImplC (t :: LogType) f :: Constraint where
DefaultIndexImplC 'UseLogarithm f = (Log f ~ Logarithm f)
DefaultIndexImplC 'UseLogRep f = (Generic1 f, Representable (Rep1 f), Coercible (Log f) (Log (Rep1 f)))
DefaultIndexImplC 'UseLogFin f = (Generic1 f, GIndexFin (Rep1 f), Size f ~ GSize (Rep1 f), Log f ~ Fin (GSize (Rep1 f)))
-- individual type classes, so GHC needs to do less work
class DefaultTabulateImplC logType f => DefaultTabulate' (logType :: LogType) f where
defaultTabulate' :: (Log f -> a) -> f a
instance DefaultTabulateImplC 'UseLogarithm f => DefaultTabulate' 'UseLogarithm f where
defaultTabulate' = tabulateLogarithm
{-# inline defaultTabulate' #-}
instance DefaultTabulateImplC 'UseLogRep f => DefaultTabulate' 'UseLogRep f where
defaultTabulate' = tabulateGeneric
{-# inline defaultTabulate' #-}
instance DefaultTabulateImplC 'UseLogFin f => DefaultTabulate' 'UseLogFin f where
defaultTabulate' = gtabulateFin
{-# inline defaultTabulate' #-}
type DefaultTabulate f = DefaultTabulate' (LogTypeOf f) f
defaultTabulate :: forall f a. DefaultTabulate f => (Log f -> a) -> f a
defaultTabulate = defaultTabulate' @(LogTypeOf f)
{-# inline defaultTabulate #-}
class DefaultIndexImplC logType f => DefaultIndex' (logType :: LogType) f where
defaultIndex' :: f a -> Log f -> a
instance DefaultIndexImplC 'UseLogarithm f => DefaultIndex' 'UseLogarithm f where
defaultIndex' = indexLogarithm
{-# inline defaultIndex' #-}
instance DefaultIndexImplC 'UseLogRep f => DefaultIndex' 'UseLogRep f where
defaultIndex' = indexGeneric
{-# inline defaultIndex' #-}
instance DefaultIndexImplC 'UseLogFin f => DefaultIndex' 'UseLogFin f where
defaultIndex' = gindexFin
{-# inline defaultIndex' #-}
type DefaultIndex f = DefaultIndex' (LogTypeOf f) f
defaultIndex :: forall f a. DefaultIndex f => f a -> (Log f -> a)
defaultIndex = defaultIndex' @(LogTypeOf f)
{-# inline defaultIndex #-}
-- | A helper for the most common usage pattern when working with 'scatter'.
--
-- @
-- 'distrib' w k ≡ 'scatter' k id w
-- @
--
-- flipped version of 'cotrav'
distrib :: (Representable f, FFunctor w) => w f -> (w Identity -> r) -> f r
distrib = \ w k -> scatter k id w
{-# inline distrib #-}
-- | The essential essence of the new 'scatter' with administrative mapping removed.
dist :: (Representable f, FFunctor w) => w f -> f (w Identity)
dist = scatter id id
{-# inline dist #-}
-- | Implements 'scatter' in terms of 'tabulate' and 'index' by the law
-- that relates 'scatter' to its canonical implementation.
--
-- This might be useful if you define custom 'tabulate' and 'index' functions
-- but do not need to carefully peel apart your structure layer by layer and
-- for some reason you are unable to define 'Generic1' and so canot simply use
-- 'DeriveAnyClass'.
scatterDefault
:: (Representable f, FFunctor w)
=> (w Identity -> r)
-> (g ~> f)
-> w g -> f r
scatterDefault = \k phi wg ->
tabulate \x -> k $ ffmap (\g -> Identity $ index (phi g) x) wg
{-# inline scatterDefault #-}
-- | Default definition for 'tabulate' when @'Log' f@ = @'Logarithm' f@. Can be used
-- to manipulate 'Logarithm's regardless of the choice of 'Log' for your distributive
-- functor.
tabulateLogarithm :: Representable f => (Logarithm f -> a) -> f a
tabulateLogarithm = \ f ->
distrib (Tab f) \(Tab f') -> f' (Logarithm runIdentity)
{-# inline tabulateLogarithm #-}
-- | @'Logarithm' f = f ~> 'Identity'@
--
-- When @f@ is 'Representable', this is the representation/logarithm of @f@, up to isomorphism. i.e.
--
-- @f a ≅ Logarithm f -> a@
--
-- Consider the case where @f = (->) r@. It follows from the yoneda lemma that
--
-- @(->) r '~>' 'Identity' ≅ r@
--
-- i.e. we have
--
-- @'Logarithm' ((->) r) = forall a. (r -> a) -> a ≅ r@
--
-- This works more generally for any 'Representable' functor. E.g. given
--
-- @data V2 a = V2 a a@
--
-- we have
--
-- @
-- V2 a ≅ Bool -> a
-- 'Logarithm' V2 ≅ Bool
-- @
type role Logarithm representational
newtype Logarithm f = Logarithm { runLogarithm :: forall a. f a -> a }
-- | A 'Log' for a distributive functor needs to support 'index' and 'tabulate'.
--
-- 'Logarithm' is a universal choice for 'Log'.
indexLogarithm :: f a -> Logarithm f -> a
indexLogarithm = \fa (Logarithm fa2a) -> fa2a fa
{-# inline indexLogarithm #-}
instance FContravariant Logarithm where
fcontramap = \f g -> Logarithm (runLogarithm g . f)
{-# inline fcontramap #-}
-- | Tabulation.
newtype Tab a f = Tab { runTab :: Logarithm f -> a }
instance FFunctor (Tab a) where
ffmap = \ f g -> Tab (runTab g . fcontramap f)
{-# inline ffmap #-}
-- | The dual of 'Data.Traversable.sequenceA'
--
-- >>> distribute [(+1),(+2)] 1
-- [2,3]
--
-- @
-- 'distribute' ≡ 'collect' 'id'
-- 'distribute' . 'distribute' ≡ 'id'
-- @
distribute
:: (Functor f, Representable g)
=> f (g a) -> g (f a)
distribute = \f -> distrib (FCompose f) \(FCompose f') -> runIdentity <$> f'
{-# inline distribute #-}
-- |
-- @
-- 'collect' f ≡ 'distribute' . 'fmap' f
-- 'fmap' f ≡ 'runIdentity' . 'collect' ('Identity' . f)
-- 'fmap' 'distribute' . 'collect' f ≡ 'getCompose' . 'collect' ('Compose' . f)
-- @
collect
:: (Functor f, Representable g)
=> (a -> g b)
-> f a -> g (f b)
collect = \ f fa -> distrib (FCompose f) \(FCompose f') -> coerce f' <$> fa
{-# inline collect #-}
-- | The dual of 'Data.Traversable.traverse'
--
-- @
-- 'cotraverse' f ≡ 'fmap' f . 'distribute'
-- @
cotraverse
:: (Functor f, Representable g)
=> (f a -> b)
-> f (g a) -> g b
cotraverse = \fab fga ->
distrib (FCompose fga) \(FCompose f') -> fab (runIdentity <$> f')
{-# inline cotraverse #-}
instance Indexable (Coe a) where
type Log (Coe a) = a
index = runCoe
{-# inline index #-}
instance Representable (Coe a) where
tabulate = Fun
{-# inline tabulate #-}
scatter k f (ffmap f -> w) = Fun \a -> k $ ffmap (\g -> Identity $ runCoe g a) w
{-# inline scatter #-}
instance (Indexable f, Indexable g) => Indexable (f :*: g) where
type Log (f :*: g) = Either (Log f) (Log g)
index = \(f :*: g) -> \case
Left x -> index f x
Right y -> index g y
{-# inline index #-}
instance (Representable f, Representable g) => Representable (f :*: g) where
scatter = \ k f (ffmap f -> w) ->
scatter k (\(l :*: _) -> l) w
:*: scatter k (\(_ :*: r) -> r) w
tabulate = \ f -> tabulate (f . Left) :*: tabulate (f . Right)
{-# inline scatter #-}
{-# inline tabulate #-}
deriving newtype instance Indexable f => Indexable (M1 i c f)
deriving newtype instance Representable f => Representable (M1 i c f)
instance Indexable U1 where
type Log U1 = Void
index = \_ -> absurd
{-# inline index #-}
instance Representable U1 where
scatter = \_ _ _ -> U1
tabulate = \_ -> U1
{-# inline scatter #-}
{-# inline tabulate #-}
deriving newtype instance Indexable f => Indexable (Rec1 f)
deriving newtype instance Representable f => Representable (Rec1 f)
instance Indexable Par1 where
type Log Par1 = ()
index = \x _ -> unPar1 x
{-# inline index #-}
instance Representable Par1 where
scatter = \k f -> coerce $ k . ffmap ((Identity . unPar1) #. f)
tabulate = \f -> Par1 $ f ()
{-# inline scatter #-}
{-# inline tabulate #-}
instance (Indexable f, Indexable g) => Indexable (f :.: g) where
type Log (f :.: g) = (Log f, Log g)
index = \ (Comp1 f) (x, y) -> index (index f x) y
{-# inline index #-}
instance (Representable f, Representable g) => Representable (f :.: g) where
scatter = \ k phi wg ->
Comp1 $
scatter
(scatter k coerce .# runAppDot)
id
(AppDot (ffmap phi wg))
tabulate = \f -> Comp1 $ tabulate \i -> tabulate \j -> f (i, j)
{-# inline scatter #-}
{-# inline tabulate #-}
instance (Indexable f, Indexable g) => Indexable (Compose f g) where
type Log (Compose f g) = Log (Rep1 (Compose f g))
index (Compose fg) (i,j) = index (index fg i) j
{-# inline index #-}
instance (Representable f, Representable g) => Representable (Compose f g) where
tabulate f = Compose $ tabulate \i -> tabulate \j -> f (i,j)
{-# inline tabulate #-}
scatter = \ k phi wg ->
Compose $
scatter
(scatter k coerce .# runAppCompose)
id
(AppCompose (ffmap phi wg))
{-# inline scatter #-}
instance (Indexable f, Indexable g) => Indexable (Product f g) where
type Log (Product f g) = Log (Rep1 (Product f g))
index = indexGeneric
{-# inline index #-}
instance (Representable f, Representable g) => Representable (Product f g) where
tabulate = tabulateGeneric
{-# inline tabulate #-}
instance Indexable Proxy
instance Representable Proxy
instance Indexable Identity
instance Representable Identity
#if MIN_VERSION_ghc_prim(0,7,0)
instance Indexable Solo
instance Representable Solo
#endif
instance Indexable ((->) x) where
type Log ((->) x) = x
index = id
{-# inline index #-}
instance Representable ((->) x) where
scatter = \ k phi wg x -> k $ ffmap (\g -> Identity $ phi g x) wg
tabulate = id
{-# inline scatter #-}
{-# inline tabulate #-}
instance Indexable Down
instance Representable Down
instance Indexable Monoid.Product
instance Representable Monoid.Product
instance Indexable Monoid.Sum
instance Representable Monoid.Sum
deriving newtype instance Indexable f => Indexable (Backwards f)
deriving newtype instance Representable f => Representable (Backwards f)
deriving newtype instance Indexable f => Indexable (Reverse f)
deriving newtype instance Representable f => Representable (Reverse f)
deriving newtype instance Indexable f => Indexable (Monoid.Alt f)
deriving newtype instance Representable f => Representable (Monoid.Alt f)
instance Indexable Monoid.Dual
instance Representable Monoid.Dual
deriving newtype instance Indexable f => Indexable (Monoid.Ap f)
deriving newtype instance Representable f => Representable (Monoid.Ap f)
instance Indexable Semigroup.First
instance Representable Semigroup.First
instance Indexable Semigroup.Last
instance Representable Semigroup.Last
instance Indexable Semigroup.Min
instance Representable Semigroup.Min
instance Indexable Semigroup.Max
instance Representable Semigroup.Max
deriving newtype instance (Indexable f, Monad f) => Indexable (WrappedMonad f)
deriving newtype instance (Representable f, Monad f) => Representable (WrappedMonad f)
instance Indexable f => Indexable (Kleisli f a) where
type Log (Kleisli f a) = (a, Log f)
index = index .# (Comp1 . runKleisli)
{-# inline index #-}
instance Representable f => Representable (Kleisli f a) where
scatter = \k f -> coerce $ scatter k ((Comp1 . runKleisli) #. f)
tabulate = (Kleisli . unComp1) #. tabulate
{-# inline scatter #-}
{-# inline tabulate #-}
#ifdef MIN_VERSION_tagged
instance Indexable (Tagged r)
instance Representable (Tagged r)
#endif
instance Indexable Complex where
type Log Complex = Bool
index = \ (r :+ i) -> \case
False -> r
True -> i
{-# inline index #-}
instance Representable Complex where
tabulate = \ f -> f False :+ f True
{-# inline tabulate #-}
deriving newtype instance Indexable f => Indexable (IdentityT f)
deriving newtype instance Representable f => Representable (IdentityT f)
deriving via (((->) e :.: f) :: Type -> Type)
instance Indexable f => Indexable (ReaderT e f)
deriving via (((->) e :.: f) :: Type -> Type)
instance Representable f => Representable (ReaderT e f)
-- * DerivingVia
-- | Provides defaults definitions for other classes in terms of
-- 'Representable'. Supplied for use with @DerivingVia@ in GHC 8.6+
--
-- Deriving 'Representable', 'Foldable', or 'Traversable' via 'Dist' f leads to non-termination
-- but all other instances are fine for use and are defined in terms of these three.
type role Dist representational nominal
newtype Dist f a = Dist { runDist :: f a }
deriving stock (Foldable, Traversable)
instance Representable f => Functor (Dist f) where
fmap = fmapRep
{-# inline fmap #-}
(<$) = const . pure
{-# inline (<$) #-}
-- | A default definition for 'fmap' from 'Functor' in terms of 'Representable'
fmapRep :: Representable f => (a -> b) -> f a -> f b
fmapRep = \ f fa -> distrib (F1 fa) \(F1 a) -> coerce f a
{-# inline fmapRep #-}
instance Indexable f => Indexable (Dist f) where
type Log (Dist f) = Log f
index = index .# runDist
{-# inline index #-}
instance Representable f => Representable (Dist f) where
scatter = \ k f -> Dist #. scatter k (runDist #. f)
tabulate = Dist #. tabulate
{-# inline scatter #-}
{-# inline tabulate #-}
-- * Applicative
instance Representable f => Applicative (Dist f) where
pure = pureRep
{-# inline pure #-}
(<*>) = apRep
{-# inline (<*>) #-}
_ *> m = m
{-# inline (*>) #-}
(<*) = const
{-# inline (<*) #-}
liftA2 = liftR2
{-# inline liftA2 #-}
-- | A default definition for 'pure' from 'Applicative' in terms of 'Representable'
pureRep :: Representable f => a -> f a
pureRep = scatter getConst id .# Const
-- pureRep = distrib Proxy . const
{-# inline pureRep #-}
-- | A default definition for '(<*>)' from 'Applicative' in terms of 'Representable'
apRep :: Representable f => f (a -> b) -> f a -> f b
apRep = \fab fa ->
distrib (F2 fab fa) \(F2 ab a) -> coerce ab a
{-# inline apRep #-}
-- | A default definition 'liftA2' from 'Applicative' in terms of 'Representable'
liftR2 :: Representable f => (a -> b -> c) -> f a -> f b -> f c
liftR2 = \f fa fb ->
distrib (F2 fa fb) \(F2 a b) -> coerce f a b
{-# inline liftR2 #-}
-- | An implementation of 'liftA3' in terms of 'Representable'.
liftR3 :: Representable f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
liftR3 = \ f fa fb fc ->
distrib (F3 fa fb fc) \(F3 a b c) -> coerce f a b c
{-# inline liftR3 #-}
-- | An implementation of 'liftA4' in terms of 'Representable'.
liftR4 :: Representable f => (a -> b -> c -> d -> e) -> f a -> f b -> f c -> f d -> f e
liftR4 = \f fa fb fc fd ->
distrib (F4 fa fb fc fd) \(F4 a b c d) -> coerce f a b c d
{-# inline liftR4 #-}
-- | An implementation of 'liftA5' in terms of 'Representable'.
liftR5 :: Representable f => (a -> b -> c -> d -> e -> x) -> f a -> f b -> f c -> f d -> f e -> f x
liftR5 = \f fa fb fc fd fe ->
distrib (F5 fa fb fc fd fe) \(F5 a b c d e) -> coerce f a b c d e
{-# inline liftR5 #-}
-- * Monad
instance Representable f => Monad (Dist f) where
(>>=) = bindRep
{-# inline (>>=) #-}
#if !MIN_VERSION_base(4,13,0)
-- | What are you still doing using 'fail', anyways?
fail x = tabulate $ \_ -> error x
#endif
-- | A default implementation of '(>>=)' in terms of 'Representable'
bindRep :: Representable f => f a -> (a -> f b) -> f b
bindRep = \ m f -> distrib (F1 m :*: FCompose f) \(F1 a :*: FCompose f') -> coerce f' a
{-# inline bindRep #-}
-- * MonadFix
instance Representable f => MonadFix (Dist f) where
mfix = mfixRep
{-# inline mfix #-}
-- | A default definition for 'mfix' in terms of 'Representable'
mfixRep :: Representable f => (a -> f a) -> f a
mfixRep = \ama -> distrib (FCompose ama) (fix . coerce)
{-# inline mfixRep #-}
instance Representable f => MonadZip (Dist f) where
mzipWith = liftR2
{-# inline mzipWith #-}
munzip = fmap fst &&& fmap snd
{-# inline munzip #-}
instance (Representable f, e ~ Log f) => MonadReader e (Dist f) where
ask = askRep
{-# inline ask #-}
local = localRep
{-# inline local #-}
reader = tabulate
{-# inline reader #-}
instance (Representable f, Num a) => Num (Dist f a) where
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
negate = fmap negate
abs = fmap abs
signum = fmap signum
fromInteger = pure . fromInteger
{-# inline (+) #-}
{-# inline (-) #-}
{-# inline (*) #-}
{-# inline negate #-}
{-# inline abs #-}
{-# inline signum #-}
{-# inline fromInteger #-}
instance (Representable f, Fractional a) => Fractional (Dist f a) where
(/) = liftA2 (/)
recip = fmap recip
fromRational = pure . fromRational
{-# inline (/) #-}
{-# inline recip #-}
{-# inline fromRational #-}
instance (Representable f, Floating a) => Floating (Dist f a) where
pi = pure pi
exp = fmap exp
log = fmap log
sqrt = fmap sqrt
(**) = liftA2 (**)
logBase = liftA2 logBase
sin = fmap sin
cos = fmap cos
tan = fmap tan
asin = fmap asin
acos = fmap acos
atan = fmap atan
sinh = fmap sinh
cosh = fmap cosh
tanh = fmap tanh
asinh = fmap asinh
acosh = fmap acosh
atanh = fmap atanh
log1p = fmap log1p
expm1 = fmap expm1
log1pexp = fmap log1pexp
log1mexp = fmap log1mexp
{-# inline pi #-}
{-# inline exp #-}
{-# inline log #-}
{-# inline sqrt #-}
{-# inline (**) #-}
{-# inline logBase #-}
{-# inline sin #-}
{-# inline cos #-}
{-# inline tan #-}
{-# inline asin #-}
{-# inline acos #-}
{-# inline atan #-}
{-# inline sinh #-}
{-# inline cosh #-}
{-# inline tanh #-}
{-# inline asinh #-}
{-# inline acosh #-}
{-# inline atanh #-}
{-# inline log1p #-}
{-# inline expm1 #-}
{-# inline log1pexp #-}
{-# inline log1mexp #-}
instance (Representable f, Semigroup a) => Semigroup (Dist f a) where
(<>) = liftR2 (<>)
{-# inline (<>) #-}
instance (Representable f, Monoid a) => Monoid (Dist f a) where
mempty = pure mempty
{-# noinline[0] mempty #-}
instance (Representable f, Foldable f, Eq a) => Eq (Dist f a) where
(==) = eqRep
{-# inline (==) #-}
(/=) = neRep
{-# inline (/=) #-}
eqRep
:: (Representable f, Foldable f, Eq a)
=> f a -> f a -> Bool
eqRep = \ xs ys ->
Monoid.getAll $ fold $ liftR2 (\x y -> Monoid.All (x == y)) xs ys
{-# inline eqRep #-}
neRep
:: (Representable f, Foldable f, Eq a)
=> f a -> f a -> Bool
neRep = \ xs ys ->
Monoid.getAny $ fold $ liftR2 (\x y -> Monoid.Any (x /= y)) xs ys
instance (Representable f, Foldable f, Ord a) => Ord (Dist f a) where
compare = \xs ys -> fold $ liftR2 compare xs ys
{-# inline compare #-}
compareRep
:: (Representable f, Foldable f, Ord a)
=> f a -> f a -> Ordering
compareRep = \xs ys -> fold $ liftR2 compare xs ys
{-# inline compareRep #-}
liftCompareRep
:: (Representable f, Foldable f)
=> (a -> b -> Ordering)
-> f a -> f b -> Ordering
liftCompareRep = \f xs ys -> fold $ liftR2 f xs ys
{-# inline liftCompareRep #-}
liftEqRep :: (Representable f, Foldable f) => (a -> b -> Bool) -> f a -> f b -> Bool
liftEqRep = \f xs ys ->
Monoid.getAll $ fold $ liftR2 (\x y -> Monoid.All (f x y)) xs ys
{-# inline liftEqRep #-}
instance (Representable f, Foldable f) => Eq1 (Dist f) where
liftEq = liftEqRep
{-# inline liftEq #-}
instance (Representable f, Foldable f) => Ord1 (Dist f) where
liftCompare = liftCompareRep
{-# inline liftCompare #-}
-- * MonadZip
-- | A default definition for 'mzipWith' in terms of 'Representable'
mzipWithRep :: Representable f => (a -> b -> c) -> f a -> f b -> f c
mzipWithRep = liftR2
{-# inline mzipWithRep #-}
-- * Comonad
#ifdef MIN_VERSION_comonad
instance (Representable f, Monoid (Log f)) => Comonad (Dist f) where
extract = extractRep
{-# inline extract #-}
duplicate = duplicateRep
{-# inline duplicate #-}
extend = extendRep
{-# inline extend #-}
instance (Representable f, Monoid (Log f)) => ComonadApply (Dist f) where
(<@>) = apRep
{-# inline (<@>) #-}
(<@) = const
{-# inline (<@) #-}
(@>) = \_ x -> x
{-# inline (@>) #-}
#endif
-- | A default definition for 'extract' from @Comonad@ in terms of 'Representable'
extractRep :: (Indexable f, Monoid (Log f)) => f a -> a
extractRep = flip index mempty
{-# inline extractRep #-}
-- | A default definition for 'extend' from @Comonad@ in terms of 'Representable'
extendRep :: (Representable f, Semigroup (Log f)) => (f a -> b) -> f a -> f b
extendRep = \f g -> tabulate \i -> f $ tabulate \j -> index g (i <> j)
{-# inline extendRep #-}
-- | A default definition for 'duplicate' from @Comonad@ in terms of 'Representable'
duplicateRep :: (Representable f, Semigroup (Log f)) => f a -> f (f a)
duplicateRep = \f -> tabulate \i -> tabulate \j -> index f (i <> j)
{-# inline duplicateRep #-}
-- | A default definition for 'extract' from @Comonad@ in terms of 'Representable'
-- where the user chooses to supply a 'unit' logarithm other than 'mempty'
extractRepBy :: Indexable f => Log f -> f a -> a
extractRepBy = flip index
{-# inline extractRepBy #-}
-- | A default definition for 'extend' from @Comonad@ in terms of 'Representable'
-- where the user chooses to supply a semigroup on logarithms other than '<>'
extendRepBy :: Representable f => (Log f -> Log f -> Log f) -> (f a -> b) -> f a -> f b
extendRepBy = \t f g -> tabulate \i -> f $ tabulate \j -> index g (t i j)
{-# inline extendRepBy #-}
-- | A default definition for 'duplicate' from @Comonad@ in terms of 'Representable'
-- where the user chooses to supply an semigroup on logarithms other than '<>'
duplicateRepBy :: Representable f => (Log f -> Log f -> Log f) -> f a -> f (f a)
duplicateRepBy = \t f -> tabulate \i -> tabulate \j -> index f (t i j)
{-# inline duplicateRepBy #-}
-- * MonadReader
-- deriving via (f :.: ((->) e)) instance Representable f => Representable (TracedT e f)
-- | A default definition for 'ask' from 'MonadReader' in terms of 'Representable'
askRep :: Representable f => f (Log f)
askRep = tabulate id
{-# noinline[0] askRep #-}
-- | A default definition for 'local' from 'MonadReader' in terms of 'Representable'
localRep :: Representable f => (Log f -> Log f) -> f a -> f a
localRep = \f m -> tabulate (index m . f)
{-# inline localRep #-}
-- * ComonadTrace
-- | A default definition for 'trace' from @ComonadTrace@ in terms of 'Representable'
traceRep :: Indexable f => Log f -> f a -> a
traceRep = flip index
{-# inline traceRep #-}
-- * FunctorWithIndex
instance (Representable f, Log f ~ i) => FunctorWithIndex i (Dist f) where
imap = imapRep
{-# inline imap #-}
-- | A default definition for 'imap' from @FunctorWithIndex@ in terms of 'Representable'
imapRep
:: Representable f
=> (Log f -> a -> b) -> f a -> f b
imapRep = \f xs -> tabulate (f <*> index xs)
{-# inline imapRep #-}
-- * FoldableWithIndex
instance (Representable f, Foldable f, Log f ~ i) => FoldableWithIndex i (Dist f) where
ifoldMap = ifoldMapRep
{-# inline ifoldMap #-}
-- | A default definition for 'ifoldMap' from @FoldableWithIndex@ in terms of 'Representable'
ifoldMapRep
:: forall f m a.
(Representable f, Foldable f, Monoid m)
=> (Log f -> a -> m) -> f a -> m
ifoldMapRep = \ix xs -> fold (tabulate (\i -> ix i $ index xs i) :: f m)
{-# inline ifoldMapRep #-}
-- * TraversableWithIndex
instance (Representable f, Traversable f, Log f ~ i) => TraversableWithIndex i (Dist f) where
itraverse = itraverseRep
{-# inline itraverse #-}
-- | A default definition for 'itraverse' from @TraversableWithIndex@ in terms of 'Representable'
itraverseRep
:: forall f m a b.
(Representable f, Traversable f, Applicative m)
=> (Log f -> a -> m b) -> f a -> m (f b)
itraverseRep = \ix xs -> sequenceA $ tabulate (ix <*> index xs)
{-# inline itraverseRep #-}
leftAdjunctRep :: Representable u => ((a, Log u) -> b) -> a -> u b
leftAdjunctRep = \f a -> tabulate (\s -> f (a,s))
{-# inline leftAdjunctRep #-}
rightAdjunctRep :: Indexable u => (a -> u b) -> (a, Log u) -> b
rightAdjunctRep = \f ~(a, k) -> f a `index` k
{-# inline rightAdjunctRep #-}
logarithmPath :: (Representable f, Traversable f) => Logarithm f -> Path
logarithmPath = \ f -> runLogarithm f $ runTrail (traverse id $ pureRep end) id
{-# inline logarithmPath #-}
logPath :: forall f. (Representable f, Traversable f) => Log f -> Path
logPath = index (runTrail (traverse id $ pureRep @f end) id)
{-# inline logPath #-}
#ifdef MIN_VERSION_comonad
instance (Representable f, Comonad f) => Semigroup (Logarithm f) where
(<>) = \(Logarithm f) (Logarithm g) -> Logarithm \x -> f $ g $ duplicate x
{-# inline (<>) #-}
instance (Representable f, Comonad f) => Monoid (Logarithm f) where
mempty = Logarithm extract
{-# inline mempty #-}
#endif
-- unfortunate orphans, caused by having @hkd@ export the data type
-- rather than making it up here.
instance (Representable f, Traversable f) => Eq (Logarithm f) where
(==) = on (==) logarithmPath
{-# inline (==) #-}
instance (Representable f, Traversable f) => Ord (Logarithm f) where
(<) = on (<) logarithmPath
(<=) = on (<=) logarithmPath
(>=) = on (>=) logarithmPath
(>) = on (>) logarithmPath
compare = on compare logarithmPath
{-# inline compare #-}
{-# inline (<) #-}
{-# inline (<=) #-}
{-# inline (>=) #-}
{-# inline (>) #-}
-- | Use explicit type application to call this function. e.g. @'eqLog' \@f@
--