2015-11-18 05:21:51 +03:00
|
|
|
module Patch where
|
2015-11-18 05:23:53 +03:00
|
|
|
|
2016-04-15 05:00:00 +03:00
|
|
|
import Data.These
|
2016-05-26 19:58:04 +03:00
|
|
|
import Prologue
|
2016-03-02 22:13:01 +03:00
|
|
|
|
2016-01-14 19:18:57 +03:00
|
|
|
-- | An operation to replace, insert, or delete an item.
|
2015-11-18 05:44:55 +03:00
|
|
|
data Patch a =
|
|
|
|
Replace a a
|
|
|
|
| Insert a
|
|
|
|
| Delete a
|
2016-04-11 23:50:48 +03:00
|
|
|
deriving (Foldable, Functor, Show, Eq)
|
2015-11-20 02:26:40 +03:00
|
|
|
|
2016-01-14 19:18:57 +03:00
|
|
|
-- | Return the item from the after side of the patch.
|
2015-11-20 02:26:40 +03:00
|
|
|
after :: Patch a -> Maybe a
|
2016-03-22 06:56:03 +03:00
|
|
|
after = maybeFst . unPatch
|
2015-11-20 04:25:28 +03:00
|
|
|
|
2016-01-14 19:18:57 +03:00
|
|
|
-- | Return the item from the before side of the patch.
|
2015-11-20 04:25:28 +03:00
|
|
|
before :: Patch a -> Maybe a
|
2016-03-22 06:56:03 +03:00
|
|
|
before = maybeSnd . unPatch
|
2015-12-01 03:08:28 +03:00
|
|
|
|
2016-03-02 22:13:01 +03:00
|
|
|
-- | Return both sides of a patch.
|
2016-03-14 22:40:35 +03:00
|
|
|
unPatch :: Patch a -> These a a
|
|
|
|
unPatch (Replace a b) = These a b
|
|
|
|
unPatch (Insert b) = That b
|
|
|
|
unPatch (Delete a) = This a
|
2016-03-02 22:13:01 +03:00
|
|
|
|
2016-01-14 19:18:57 +03:00
|
|
|
-- | Calculate the cost of the patch given a function to compute the cost of a item.
|
2015-12-01 03:08:28 +03:00
|
|
|
patchSum :: (a -> Integer) -> Patch a -> Integer
|
2016-02-23 20:15:06 +03:00
|
|
|
patchSum termCost patch = maybe 0 termCost (before patch) + maybe 0 termCost (after patch)
|
2016-04-15 04:19:21 +03:00
|
|
|
|
|
|
|
-- | Return Just the value in This, or the first value in These, if any.
|
|
|
|
maybeFst :: These a b -> Maybe a
|
|
|
|
maybeFst = these Just (const Nothing) ((Just .) . const)
|
|
|
|
|
|
|
|
-- | Return Just the value in That, or the second value in These, if any.
|
|
|
|
maybeSnd :: These a b -> Maybe b
|
|
|
|
maybeSnd = these (const Nothing) Just ((Just .) . flip const)
|