on c97c126 help sign in
patch/src/Data/Patch/Class.hs
40 lines 1.6 kB history raw
1{-# LANGUAGE TypeFamilies #-}
2-- | The interface for types which represent changes made to other types
3module Data.Patch.Class where
5import Data.Functor.Identity
6import Data.Maybe
7import Data.Semigroup (Semigroup(..))
8import Data.Proxy
10-- | A 'Patch' type represents a kind of change made to a datastructure.
11--
12-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
13-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
14class Patch p where
15 type PatchTarget p :: *
16 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
17 -- 'Nothing'.
18 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
20-- | Apply a 'Patch'; if it does nothing, return the original value
21applyAlways :: Patch p => p -> PatchTarget p -> PatchTarget p
22applyAlways p t = fromMaybe t $ apply p t
24-- | 'Identity' can be used as a 'Patch' that always fully replaces the value
25instance Patch (Identity a) where
26 type PatchTarget (Identity a) = a
27 apply (Identity a) _ = Just a
29-- | 'Proxy' can be used as a 'Patch' that does nothing.
30instance Patch (Proxy a) where
31 type PatchTarget (Proxy a) = a
32 apply ~Proxy _ = Nothing
34-- | Like '(.)', but composes functions that return patches rather than
35-- functions that return new values. The Semigroup instance for patches must
36-- apply patches right-to-left, like '(.)'.
37composePatchFunctions :: (Patch p, Semigroup p) => (PatchTarget p -> p) -> (PatchTarget p -> p) -> PatchTarget p -> p
38composePatchFunctions g f a =
39 let fp = f a
40 in g (applyAlways fp a) <> fp