{-# LANGUAGE CPP #-}
module Agda.Utils.Cluster
( cluster
, cluster'
) where
import Control.Monad
import Data.Equivalence.Monad (runEquivT, equateAll, classDesc)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Map.Strict as MapS
#if __GLASGOW_HASKELL__ < 804
import Data.Semigroup
#endif
import Agda.Utils.Functor
import Agda.Utils.Singleton
import Agda.Utils.Fail
cluster :: Ord c => (a -> NonEmpty c) -> [a] -> [NonEmpty a]
cluster :: forall c a. Ord c => (a -> NonEmpty c) -> [a] -> [NonEmpty a]
cluster a -> NonEmpty c
f [a]
as = forall c a. Ord c => [(a, NonEmpty c)] -> [NonEmpty a]
cluster' forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (\ a
a -> (a
a, a -> NonEmpty c
f a
a)) [a]
as
cluster' :: Ord c => [(a, NonEmpty c)] -> [NonEmpty a]
cluster' :: forall c a. Ord c => [(a, NonEmpty c)] -> [NonEmpty a]
cluster' [(a, NonEmpty c)]
acs = forall a. Fail a -> a
runFail_ forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) v c a.
(Monad m, Applicative m) =>
(v -> c) -> (c -> c -> c) -> (forall s. EquivT s c v m a) -> m a
runEquivT forall a. a -> a
id forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ do
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [(a, NonEmpty c)]
acs forall a b. (a -> b) -> a -> b
$ \ (a
_, c
c :| [c]
cs) -> forall c v d (m :: * -> *). MonadEquiv c v d m => [v] -> m ()
equateAll forall a b. (a -> b) -> a -> b
$ c
cforall a. a -> [a] -> [a]
:[c]
cs
[Map c (NonEmpty a)]
cas <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [(a, NonEmpty c)]
acs forall a b. (a -> b) -> a -> b
$ \ (a
a, c
c :| [c]
_) -> forall c v d (m :: * -> *). MonadEquiv c v d m => v -> m d
classDesc c
c forall (m :: * -> *) a b. Functor m => m a -> (a -> b) -> m b
<&> \ c
k -> forall k a. k -> a -> Map k a
MapS.singleton c
k (forall el coll. Singleton el coll => el -> coll
singleton a
a)
let m :: Map c (NonEmpty a)
m = forall (f :: * -> *) k a.
(Foldable f, Ord k) =>
(a -> a -> a) -> f (Map k a) -> Map k a
MapS.unionsWith forall a. Semigroup a => a -> a -> a
(<>) [Map c (NonEmpty a)]
cas
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall k a. Map k a -> [a]
MapS.elems Map c (NonEmpty a)
m