Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active November 1, 2015 23:55
Show Gist options
  • Save oisdk/ccb6f35f90a0ea15a364 to your computer and use it in GitHub Desktop.
Save oisdk/ccb6f35f90a0ea15a364 to your computer and use it in GitHub Desktop.
import qualified Data.Map as M
import Data.Foldable (Foldable, foldr)
import Prelude hiding (foldr)
import Data.Maybe (fromMaybe)
data Trie a = Trie { endHere :: Bool
, getTrie :: M.Map a (Trie a)
} deriving (Eq)
insert :: (Ord a, Foldable f) => f a -> Trie a -> Trie a
insert = foldr f (\(Trie _ m) -> Trie True m) where
f e a = overMap (M.alter (Just . a . fromMaybe (Trie False M.empty)) e)
foldrTrie :: ([a] -> b -> b) -> b -> Trie a -> b
foldrTrie f i (Trie a m) = M.foldrWithKey ff s m where
s = if a then f [] i else i
ff k = flip (foldrTrie $ f . (k :))
overMap :: Ord b => (M.Map a (Trie a) -> M.Map b (Trie b)) -> Trie a -> Trie b
overMap f (Trie e m) = Trie e (f m)
fromList :: (Ord a, Foldable f, Foldable g) => f (g a) -> Trie a
fromList = foldr insert (Trie False M.empty)
toList :: Trie a -> [[a]]
toList = foldrTrie (:) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment