Skip to content

Instantly share code, notes, and snippets.

@fmap
Last active August 29, 2015 14:02
Show Gist options
  • Save fmap/e5ebbfd338d38416d9e1 to your computer and use it in GitHub Desktop.
Save fmap/e5ebbfd338d38416d9e1 to your computer and use it in GitHub Desktop.
import Prelude hiding (foldr, filter)
import Data.Maybe (fromJust, isJust)
import Data.Foldable (Foldable(foldr))
import Data.HashMap.Lazy (HashMap, singleton, unionWith, foldrWithKey)
import Data.Hashable (Hashable(..))
import Data.Monoid (Monoid(mappend, mempty))
import Data.Vector (Vector, find, cons, filter)
-- sniEquivalence describes a surjective but non-injective relation between
-- {b, a}.
integrate' :: Eq a => Hashable a => (a -> b -> Bool) -> Vector a -> Vector b -> HashMap a (Vector b)
integrate' sniEquivalance as = foldr (unionWith mappend) mempty . catMaybes . fmap (flip associate as)
where associate term = flip singleton (return term) <$$> find (`sniEquivalance` term)
integrate :: Eq a => Hashable a => (a -> Vector b -> c) -> (a -> b -> Bool) -> Vector a -> Vector b -> Vector c
integrate constructor = (uncurry constructor <$$> toVector) <$$$> integrate'
toVector :: HashMap k v -> Vector (k, v)
toVector = cons <$$> (,) `foldrWithKey` mempty
catMaybes :: Vector (Maybe a) -> Vector a
catMaybes = fmap fromJust . filter isJust
(<$$>) :: Functor f => Functor g => (a -> b) -> g (f a) -> g (f b)
(<$$>) = fmap fmap fmap
(<$$$>) :: Functor f => Functor g => Functor h => (a -> b) -> h (g (f a)) -> h (g (f b))
(<$$$>) = fmap `fmap` fmap fmap fmap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment