Skip to content

Instantly share code, notes, and snippets.

@kazu-yamamoto
Created October 30, 2012 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazu-yamamoto/3977762 to your computer and use it in GitHub Desktop.
Save kazu-yamamoto/3977762 to your computer and use it in GitHub Desktop.
Trie 2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
data Trie m k v = Trie (Maybe v) (m k (Trie m k v))
class FiniteMap m k where
empty' :: m k v
look' :: k -> m k v -> Maybe v
bind' :: k -> v -> m k v -> m k v
empty :: FiniteMap m k => Trie m k v
empty = Trie Nothing empty'
look :: (FiniteMap m k, Ord k) => [k] -> Trie m k v -> Maybe v
look [] (Trie b _) = b
look (k:ks) (Trie _ m) = look' k m >>= look ks
bind :: (FiniteMap m k, Ord k) => [k] -> v -> Trie m k v -> Trie m k v
bind [] x (Trie _ m) = Trie (Just x) m
bind (k:ks) x (Trie b m) = Trie b (bind' k t' m)
where
t = fromMaybe empty $ look' k m
t' = bind ks x t
instance FiniteMap Map Char where
empty' = M.empty
look' = M.lookup
bind' = M.insert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment