on jam@fix-docs help sign in
patch/src/Data/Patch/Class.hs
34 lines 1.4 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(..))
9-- | A 'Patch' type represents a kind of change made to a datastructure.
10--
11-- If an instance of 'Patch' is also an instance of 'Semigroup', it should obey
12-- the law that @applyAlways (f <> g) == applyAlways f . applyAlways g@.
13class Patch p where
14 type PatchTarget p :: *
15 -- | Apply the patch @p a@ to the value @a@. If no change is needed, return
16 -- 'Nothing'.
17 apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
19-- | Apply a 'Patch'; if it does nothing, return the original value
20applyAlways :: Patch p => p -> PatchTarget p -> PatchTarget p
21applyAlways p t = fromMaybe t $ apply p t
23-- | 'Identity' can be used as a 'Patch' that always fully replaces the value
24instance Patch (Identity a) where
25 type PatchTarget (Identity a) = a
26 apply (Identity a) _ = Just a
28-- | Like '(.)', but composes functions that return patches rather than
29-- functions that return new values. The Semigroup instance for patches must
30-- apply patches right-to-left, like '(.)'.
31composePatchFunctions :: (Patch p, Semigroup p) => (PatchTarget p -> p) -> (PatchTarget p -> p) -> PatchTarget p -> p
32composePatchFunctions g f a =
33 let fp = f a
34 in g (applyAlways fp a) <> fp