|
| 1 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 2 | +module RefDiffBy (diffBy) where |
| 3 | + |
| 4 | +import Data.TreeDiff.List (Edit (..)) |
| 5 | + |
| 6 | +import qualified Data.Primitive as P |
| 7 | + |
| 8 | +diffBy :: forall a. (a -> a -> Bool) -> [a] -> [a] -> [Edit a] |
| 9 | +diffBy eq xs' ys' = reverse (getCell (lcs xn yn)) |
| 10 | + where |
| 11 | + xn = length xs' |
| 12 | + yn = length ys' |
| 13 | + |
| 14 | + xs = P.arrayFromListN xn xs' |
| 15 | + ys = P.arrayFromListN yn ys' |
| 16 | + |
| 17 | + memo :: P.Array (Cell [Edit a]) |
| 18 | + memo = P.arrayFromListN ((xn + 1) * (yn + 1)) |
| 19 | + [ impl xi yi |
| 20 | + | xi <- [0 .. xn] |
| 21 | + , yi <- [0 .. yn] |
| 22 | + ] |
| 23 | + |
| 24 | + lcs :: Int -> Int -> Cell [Edit a] |
| 25 | + lcs xi yi = P.indexArray memo (yi + xi * (yn + 1)) |
| 26 | + |
| 27 | + impl :: Int -> Int -> Cell [Edit a] |
| 28 | + impl 0 0 = Cell 0 [] |
| 29 | + impl 0 m = case lcs 0 (m - 1) of |
| 30 | + Cell w edit -> Cell (w + 1) (Ins (P.indexArray ys (m - 1)) : edit) |
| 31 | + impl n 0 = case lcs (n - 1) 0 of |
| 32 | + Cell w edit -> Cell (w + 1) (Del (P.indexArray xs (n - 1)) : edit) |
| 33 | + |
| 34 | + impl n m = bestOfThree |
| 35 | + edit |
| 36 | + (bimap (+1) (Ins y :) (lcs n (m - 1))) |
| 37 | + (bimap (+1) (Del x :) (lcs (n - 1) m)) |
| 38 | + where |
| 39 | + x = P.indexArray xs (n - 1) |
| 40 | + y = P.indexArray ys (m - 1) |
| 41 | + |
| 42 | + edit |
| 43 | + | eq x y = bimap id (Cpy x :) (lcs (n - 1) (m - 1)) |
| 44 | + | otherwise = bimap (+1) (Swp x y :) (lcs (n - 1) (m - 1)) |
| 45 | + |
| 46 | +data Cell a = Cell !Int !a |
| 47 | + |
| 48 | +getCell :: Cell a -> a |
| 49 | +getCell (Cell _ x) = x |
| 50 | + |
| 51 | +bestOfThree :: Cell a -> Cell a -> Cell a -> Cell a |
| 52 | +bestOfThree a@(Cell i _x) b@(Cell j _y) c@(Cell k _z) |
| 53 | + | i <= j |
| 54 | + = if i <= k then a else c |
| 55 | + |
| 56 | + | otherwise |
| 57 | + = if j <= k then b else c |
| 58 | + |
| 59 | +bimap :: (Int -> Int) -> (a -> b) -> Cell a -> Cell b |
| 60 | +bimap f g (Cell i x) = Cell (f i) (g x) |
0 commit comments