Skip to content

Commit bf6048e

Browse files
committed
readme: Add map patching example/explanation
1 parent 139e64e commit bf6048e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,40 @@ class Patch p where
1111
-- 'Nothing'.
1212
apply :: p -> PatchTarget p -> Maybe (PatchTarget p)
1313
```
14+
15+
### Patching Maps
16+
For example, `Data.Patch.Map` defines the `PatchMap` type which can be used to patch `Map`s. A `PatchMap` represents updates to a `Map` that can insert, remove, or replace items in the `Map`. In this example, the `Map` is the `PatchTarget` and the `PatchMap` is the `Patch`. Keep in mind that there are many other possible `Patch`es that can be applied to a `Map` (i.e., `Map` can be the `PatchTarget` for many different `Patch` instances).
17+
18+
`PatchMap` is defined as:
19+
20+
```haskell
21+
newtype PatchMap k v = PatchMap { unPatchMap :: Map k (Maybe v) }
22+
```
23+
24+
The `Maybe` around the value is used to represent insertion/updates or deletion of the element at a given key.
25+
26+
It's `Patch` instance begins with:
27+
28+
```haskell
29+
instance Ord k => Patch (PatchMap k v) where
30+
type PatchTarget (PatchMap k v) = Map k v
31+
...
32+
```
33+
34+
When a `PatchMap` is applied to its `PatchTarget`, the following changes can occur:
35+
36+
- If the key is present in the `Patch` and the `PatchTarget`...
37+
38+
- And the `Patch` value at that key is `Nothing`: delete that key from the `PatchTarget`.
39+
40+
- And the `Patch` value at that key is `Just x`: update the value at that key in the `PatchTarget` to `x`.
41+
42+
- If the key is present in the `Patch` and not present in the `PatchTarget`...
43+
44+
- And the `Patch` value at that key is `Nothing`: do nothing because we're trying to delete a key that doesn't exist in the target in the first place.
45+
46+
- And the `Patch` value at that key is `Just x`: insert the key and the value `x` into the `PatchTarget`
47+
48+
- If the key is *not* present in the `Patch` but present in the `PatchTarget`: do nothing.
49+
50+
There are, of course, more complicated ways of patching maps involving, for example, moving values from one key to another. You can find the code for that in `Data.Patch.PatchMapWithMove`. Note that the `PatchTarget` type associated with the `PatchMapWithMove` patch instance is still `Map k v`!

0 commit comments

Comments
 (0)