diff --git a/src/Guide/State.hs b/src/Guide/State.hs index 347ded8..2c1917c 100644 --- a/src/Guide/State.hs +++ b/src/Guide/State.hs @@ -556,7 +556,7 @@ restoreCategory catId pos = do Nothing -> return (Left "category not found in deleted categories") Just category -> do categoriesDeleted %= deleteFirst (hasUid catId) - categories %= insertAtGuaranteed pos category + categories %= insertOrAppend pos category return (Right ()) restoreItem :: Uid Item -> Int -> Acid.Update GlobalState (Either String ()) @@ -569,7 +569,7 @@ restoreItem itemId pos = do let item = fromJust (find (hasUid itemId) (category^.itemsDeleted)) let category' = category & itemsDeleted %~ deleteFirst (hasUid itemId) - & items %~ insertAtGuaranteed pos item + & items %~ insertOrAppend pos item categories . each . filtered ourCategory .= category' categoriesDeleted . each . filtered ourCategory .= category' return (Right ()) @@ -590,7 +590,7 @@ restoreTrait itemId traitId pos = do (Just trait, _) -> do let item' = item & prosDeleted %~ deleteFirst (hasUid traitId) - & pros %~ insertAtGuaranteed pos trait + & pros %~ insertOrAppend pos trait let category' = category & items . each . filtered (hasUid itemId) .~ item' & itemsDeleted . each . filtered (hasUid itemId) .~ item' @@ -600,7 +600,7 @@ restoreTrait itemId traitId pos = do (_, Just trait) -> do let item' = item & consDeleted %~ deleteFirst (hasUid traitId) - & cons %~ insertAtGuaranteed pos trait + & cons %~ insertOrAppend pos trait let category' = category & items . each . filtered (hasUid itemId) .~ item' & itemsDeleted . each . filtered (hasUid itemId) .~ item' diff --git a/src/Guide/Utils.hs b/src/Guide/Utils.hs index 4b78cbb..f11489d 100644 --- a/src/Guide/Utils.hs +++ b/src/Guide/Utils.hs @@ -19,7 +19,7 @@ module Guide.Utils moveUp, moveDown, deleteFirst, - insertAtGuaranteed, + insertOrAppend, ordNub, -- * 'Eq' @@ -134,10 +134,14 @@ deleteFirst f (x:xs) = if f x then xs else x : deleteFirst f xs -- | Insert given element into the list, or append it to the list if the -- position is outside the list bounds. -insertAtGuaranteed :: Int -> a -> [a] -> [a] -insertAtGuaranteed _ a [] = [a] -insertAtGuaranteed 0 a xs = a:xs -insertAtGuaranteed n a (x:xs) = x : insertAtGuaranteed (n-1) a xs +insertOrAppend + :: Int -- ^ Preferred position + -> a -- ^ Element to insert + -> [a] + -> [a] +insertOrAppend _ a [] = [a] +insertOrAppend 0 a xs = a:xs +insertOrAppend n a (x:xs) = x : insertOrAppend (n-1) a xs -- | A version of 'works in @O(n log n)@ instead of @O(n^2)@. ordNub :: Ord a => [a] -> [a]