Skip to content

Commit

Permalink
[#2] Add IntMap applyMergeNonEmpty
Browse files Browse the repository at this point in the history
  • Loading branch information
pgujjula committed May 9, 2024
1 parent 9046fe9 commit 7675571
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions src/ApplyMerge/IntMap.hs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Control.Monad (guard)
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IntMap
import Data.List (unfoldr)
import Data.List.NonEmpty (NonEmpty, nonEmpty)
import Data.List.NonEmpty (NonEmpty ((:|)), nonEmpty)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Maybe (fromMaybe)
import Data.PQueue.Prio.Min (MinPQueue)
Expand All @@ -32,15 +32,32 @@ applyMerge :: (Ord c) => (a -> b -> c) -> [a] -> [b] -> [c]
applyMerge f as bs = fromMaybe [] $ do
as' <- nonEmpty as
bs' <- nonEmpty bs
pure (unfoldr (step f) (initialFrontier f as' bs'))
pure (NonEmpty.toList (applyMergeNonEmpty f as' bs'))

initialFrontier :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> Frontier a b c
initialFrontier f as bs =
let node = mkNode f (0, 0) as bs
in Frontier
{ queue = MinPQueue.singleton node.value node,
indexMap = IntMap.singleton 0 0
}
applyMergeNonEmpty ::
(Ord c) => (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c
applyMergeNonEmpty f as bs =
let (c, frontier) = initialState f as bs
in c :| unfoldr (step f) frontier

initialState ::
forall a b c.
(Ord c) =>
(a -> b -> c) ->
NonEmpty a ->
NonEmpty b ->
(c, Frontier a b c)
initialState f as bs =
let initialNode :: Node a b c
initialNode = mkNode f (0, 0) as bs

emptyFrontier :: Frontier a b c
emptyFrontier =
Frontier
{ queue = MinPQueue.empty,
indexMap = IntMap.empty
}
in peekInsertChildren f initialNode emptyFrontier

step :: (Ord c) => (a -> b -> c) -> Frontier a b c -> Maybe (c, Frontier a b c)
step f = fmap (uncurry (peekInsertChildren f)) . deleteMinNode
Expand Down

0 comments on commit 7675571

Please sign in to comment.