@@ -1,4 +1,6 @@
1+{-# LANGUAGE DefaultSignatures #-}
12{-# LANGUAGE TypeFamilies #-}
3+{-# LANGUAGE TypeOperators #-}
24-- | The interface for types which represent changes made to other types
35module Data.Patch.Class where
46
@@ -6,13 +8,39 @@ import Data.Functor.Identity
68import Data.Maybe
79import Data.Semigroup (Semigroup(..))
810import Data.Proxy
11+import Data.Type.Equality ((:~:) (..))
12+
13+class PatchHet p where
14+ type PatchSource p :: *
15+ type PatchTarget p :: *
16+ -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
17+ -- 'Nothing'.
18+ applyHet
19+ :: p
20+ -> PatchSource p
21+ -> Either (PatchSource p :~: PatchTarget p) (PatchTarget p)
22+ default applyHet
23+ :: Patch p
24+ => p
25+ -> PatchSource p
26+ -> Either (PatchSource p :~: PatchTarget p) (PatchTarget p)
27+ applyHet p a = case apply p a of
28+ Nothing -> Left Refl
29+ Just a' -> Right a'
30+
31+-- | Apply a 'PatchHet'; if it does nothing, return the original value
32+applyAlwaysHet :: PatchHet p => p -> PatchSource p -> PatchTarget p
33+applyAlwaysHet p t = case applyHet p t of
34+ Left Refl -> t
35+ Right t' -> t'
936
1037-- | A 'Patch' type represents a kind of change made to a datastructure.
1138--
1239-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
1340-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
14−class Patch p where
15− type PatchTarget p :: *
41+class ( PatchHet p
42+ , PatchSource p ~ PatchTarget p
43+ ) => Patch p where
1644 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
1745 -- 'Nothing'.
1846 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
@@ -22,19 +50,27 @@ applyAlways :: Patch p => p -> PatchTarget p -> PatchTarget p
2250applyAlways p t = fromMaybe t $ apply p t
2351
2452-- | 'Identity' can be used as a 'Patch' that always fully replaces the value
25−instance Patch (Identity a) where
53+instance PatchHet (Identity a) where
54+ type PatchSource (Identity a) = a
2655 type PatchTarget (Identity a) = a
56+instance Patch (Identity a) where
2757 apply (Identity a) _ = Just a
2858
2959-- | 'Identity' can be used as a 'Patch' that always fully replaces the value
30−instance Patch (Proxy a) where
60+instance PatchHet (Proxy a) where
61+ type PatchSource (Proxy a) = a
3162 type PatchTarget (Proxy a) = a
63+instance Patch (Proxy a) where
3264 apply ~Proxy _ = Nothing
3365
3466-- | Like '(.)', but composes functions that return patches rather than
3567-- functions that return new values. The Semigroup instance for patches must
3668-- apply patches right-to-left, like '(.)'.
37−composePatchFunctions :: (Patch p, Semigroup p) => (PatchTarget p -> p) -> (PatchTarget p -> p) -> PatchTarget p -> p
69+composePatchFunctions
70+ :: (Patch p, Semigroup p)
71+ => (PatchTarget p -> p)
72+ -> (PatchTarget p -> p)
73+ -> PatchTarget p -> p
3874composePatchFunctions g f a =
3975 let fp = f a
4076 in g (applyAlways fp a) <> fp