Skip to content

Instantly share code, notes, and snippets.

@forestbelton
Last active August 12, 2018 02:26
Show Gist options
  • Save forestbelton/ed4db03d88f5f916867761cbcb433d06 to your computer and use it in GitHub Desktop.
Save forestbelton/ed4db03d88f5f916867761cbcb433d06 to your computer and use it in GitHub Desktop.
tries are monoids
import qualified Data.Map as M
newtype Trie c = Trie { getTrie :: M.Map c (Trie c) }
deriving (Show)
type Word c = [c]
instance Ord c => Monoid (Trie c) where
mempty = Trie M.empty
(Trie t) `mappend` (Trie t') = Trie $ M.unionWith mappend t t'
fromWord :: Ord c => Word c -> Trie c
fromWord = foldr (\c t -> Trie $ M.singleton c t) mempty
fromWords :: Ord c => [Word c] -> Trie c
fromWords = foldMap fromWord
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment