on b328393 help sign in
patch/src/Reflex/Patch/MapWithMove.hs
224 lines 11 kB history raw
1{-# LANGUAGE DeriveFoldable #-}
2{-# LANGUAGE DeriveFunctor #-}
3{-# LANGUAGE DeriveTraversable #-}
4{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE LambdaCase #-}
6{-# LANGUAGE PatternGuards #-}
7{-# LANGUAGE ScopedTypeVariables #-}
8{-# LANGUAGE TypeFamilies #-}
9-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
10-- another
11module Reflex.Patch.MapWithMove where
13import Reflex.Patch.Class
15import Control.Arrow
16import Control.Monad.State
17import Data.Foldable
18import Data.Function
19import Data.List
20import Data.Map (Map)
21import qualified Data.Map as Map
22import Data.Maybe
23import Data.Semigroup
24import qualified Data.Set as Set
25import Data.These
26import Data.Tuple
28-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
29-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
30-- and vice versa. There should never be any unpaired From/To keys.
31newtype PatchMapWithMove k v = PatchMapWithMove (Map k (NodeInfo k v)) deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
33-- | Holds the information about each key: where its new value should come from,
34-- and where its old value should go to
35data NodeInfo k v = NodeInfo
36 { _nodeInfo_from :: !(From k v)
37 -- ^ Where do we get the new value for this key?
38 , _nodeInfo_to :: !(To k)
39 -- ^ If the old value is being kept (i.e. moved rather than deleted or
40 -- replaced), where is it going?
41 }
42 deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
44-- | Create a 'PatchMapWithMove', validating it
45patchMapWithMove :: Ord k => Map k (NodeInfo k v) -> Maybe (PatchMapWithMove k v)
46patchMapWithMove m = if valid then Just $ PatchMapWithMove m else Nothing
47 where valid = forwardLinks == backwardLinks
48 forwardLinks = Map.mapMaybe _nodeInfo_to m
49 backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, v) ->
50 case _nodeInfo_from v of
51 From_Move from -> Just (from, to)
52 _ -> Nothing
54-- | Create a 'PatchMapWithMove' that inserts everything in the given 'Map'
55patchMapWithMoveInsertAll :: Map k v -> PatchMapWithMove k v
56patchMapWithMoveInsertAll m = PatchMapWithMove $ flip fmap m $ \v -> NodeInfo
57 { _nodeInfo_from = From_Insert v
58 , _nodeInfo_to = Nothing
59 }
61-- | Extract the internal representation of the 'PatchMapWithMove'
62unPatchMapWithMove :: PatchMapWithMove k v -> Map k (NodeInfo k v)
63unPatchMapWithMove (PatchMapWithMove p) = p
65-- | Warning: when using this function, you must ensure that the invariants of
66-- 'PatchMapWithMove' are preserved; they will not be checked.
67unsafePatchMapWithMove :: Map k (NodeInfo k v) -> PatchMapWithMove k v
68unsafePatchMapWithMove = PatchMapWithMove
70-- | Describe how a key's new value should be produced
71data From k v
72 = From_Insert v -- ^ Insert the given value here
73 | From_Delete -- ^ Delete the existing value, if any, from here
74 | From_Move !k -- ^ Move the value here from the given key
75 deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable)
77-- | Describe where a key's old value will go. If this is 'Just', that means
78-- the key's old value will be moved to the given other key; if it is 'Nothing',
79-- that means it will be deleted.
80type To = Maybe
82-- | Apply the insertions, deletions, and moves to a given 'Map'
83instance Ord k => Patch (PatchMapWithMove k v) where
84 type PatchTarget (PatchMapWithMove k v) = Map k v
85 apply (PatchMapWithMove p) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
86 where insertions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
87 From_Insert v -> Just v
88 From_Move k -> Map.lookup k old
89 From_Delete -> Nothing
90 deletions = flip Map.mapMaybeWithKey p $ \_ ni -> case _nodeInfo_from ni of
91 From_Delete -> Just ()
92 _ -> Nothing
94-- | Returns all the new elements that will be added to the 'Map'
95patchMapWithMoveNewElements :: PatchMapWithMove k v -> [v]
96patchMapWithMoveNewElements = Map.elems . patchMapWithMoveNewElementsMap
98patchMapWithMoveNewElementsMap :: PatchMapWithMove k v -> Map k v
99patchMapWithMoveNewElementsMap (PatchMapWithMove p) = Map.mapMaybe f p
100 where f ni = case _nodeInfo_from ni of
101 From_Insert v -> Just v
102 From_Move _ -> Nothing
103 From_Delete -> Nothing
105-- | Create a 'PatchMapWithMove' that, if applied to the given 'Map', will sort
106-- its values using the given ordering function. The set keys of the 'Map' is
107-- not changed.
108patchThatSortsMapWith :: Ord k => (v -> v -> Ordering) -> Map k v -> PatchMapWithMove k v
109patchThatSortsMapWith cmp m = PatchMapWithMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
110 where unsorted = Map.toList m
111 sorted = sortBy (cmp `on` snd) unsorted
112 f (to, _) (from, _) = if to == from then Nothing else
113 Just (from, to)
114 reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
115 g (to, _) (from, _) = if to == from then Nothing else
116 let Just movingTo = Map.lookup from reverseMapping
117 in Just (to, NodeInfo (From_Move from) $ Just movingTo)
119-- | Create a 'PatchMapWithMove' that, if applied to the first 'Map' provided,
120-- will produce a 'Map' with the same values as the second 'Map' but with the
121-- values sorted with the given ordering function.
122patchThatChangesAndSortsMapWith :: forall k v. (Ord k, Ord v) => (v -> v -> Ordering) -> Map k v -> Map k v -> PatchMapWithMove k v
123patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patch
124 where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
125 newList = Map.toList newByIndexUnsorted
126 newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
127 insertsAndMoves :: Map k (NodeInfo k v)
128 (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
129 let f k v = do
130 remainingValues <- get
131 let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
132 then Map.delete v remainingValues
133 else Map.insert v remainingKeys remainingValues
134 case Map.lookup v remainingValues of
135 Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
136 Just fromKs ->
137 if k `Set.member` fromKs
138 then do
139 putRemainingKeys $ Set.delete k fromKs
140 return $ NodeInfo (From_Move k) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
141 else do
142 Just (fromK, remainingKeys) <- return $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
143 putRemainingKeys remainingKeys
144 return $ NodeInfo (From_Move fromK) $ Just undefined
145 Map.traverseWithKey f newByIndex
146 unusedOldKeys = fold unusedValuesByValue
147 pointlessMove k = \case
148 From_Move k' | k == k' -> True
149 _ -> False
150 keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
151 then Just undefined
152 else Nothing
153 patch = unsafePatchMapWithMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
155-- | Change the 'From' value of a 'NodeInfo'
156nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
157nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
159-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
160-- 'Applicative', 'Monad', etc.) action to get the new value
161nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
162nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
164-- | Set the 'To' field of a 'NodeInfo'
165nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
166nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
168-- |Helper data structure used for composing patches using the monoid instance.
169data Fixup k v
170 = Fixup_Delete
171 | Fixup_Update (These (From k v) (To k))
173-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
174instance Ord k => Semigroup (PatchMapWithMove k v) where
175 PatchMapWithMove ma <> PatchMapWithMove mb = PatchMapWithMove m
176 where
177 connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
178 h :: (k, (Maybe k, From k v)) -> [(k, Fixup k v)]
179 h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
180 (Just toAfter, From_Move fromBefore)
181 | fromBefore == toAfter
182 -> [(toAfter, Fixup_Delete)]
183 | otherwise
184 -> [ (toAfter, Fixup_Update (This editBefore))
185 , (fromBefore, Fixup_Update (That mToAfter))
186 ]
187 (Nothing, From_Move fromBefore) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
188 (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
189 (Nothing, _) -> []
190 mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
191 mergeFixups _ (Fixup_Update a) (Fixup_Update b)
192 | This x <- a, That y <- b
193 = Fixup_Update $ These x y
194 | That y <- a, This x <- b
195 = Fixup_Update $ These x y
196 mergeFixups _ _ _ = error "PatchMapWithMove: incompatible fixups"
197 fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
198 combineNodeInfos _ nia nib = NodeInfo
199 { _nodeInfo_from = _nodeInfo_from nia
200 , _nodeInfo_to = _nodeInfo_to nib
201 }
202 applyFixup _ ni = \case
203 Fixup_Delete -> Nothing
204 Fixup_Update u -> Just $ NodeInfo
205 { _nodeInfo_from = fromMaybe (_nodeInfo_from ni) $ getHere u
206 , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
207 }
208 m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
209 getHere :: These a b -> Maybe a
210 getHere = \case
211 This a -> Just a
212 These a _ -> Just a
213 That _ -> Nothing
214 getThere :: These a b -> Maybe b
215 getThere = \case
216 This _ -> Nothing
217 These _ b -> Just b
218 That b -> Just b
220--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
221-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
222instance Ord k => Monoid (PatchMapWithMove k v) where
223 mempty = PatchMapWithMove mempty
224 mappend = (<>)