Last active
December 3, 2018 00:31
-
-
Save incinirate/b4322d9762f04d1d56ec0fda8130c772 to your computer and use it in GitHub Desktop.
Trie Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extract :: (a -> Bool) -> [a] -> (Maybe a, [a]) | |
extract _ [] = (Nothing, []) | |
extract pred (x:xs) | |
| pred x = (Just x, xs) | |
| otherwise = (x:) <$> extract pred xs | |
data Trie a = Node { datum :: Maybe a | |
, children :: [Trie a] } | |
instance Show a => Show (Trie a) where | |
show Node{datum = d, children = kids} | |
= showD d ++ (case length kids of | |
0 -> "" | |
1 -> " => " ++ show (head kids) | |
_ -> " => {" ++ intercalate " | " (show <$> kids) ++ "}") | |
where showD (Just x) = show x | |
showD Nothing = "Root" | |
getDepth :: (Ord b, Num b) => Trie a -> b | |
getDepth Node{children = kids} | |
| null kids = 1 | |
| otherwise = 1 + maximum (getDepth <$> kids) | |
insertStr :: Eq a => Trie a -> [a] -> Trie a | |
insertStr root [] = root | |
insertStr root@Node{children = kids} xs | |
| (Just node, otherKids) <- extract (\x -> datum x == Just (head xs)) kids | |
= Node{datum = datum root | |
,children = insertStr node (tail xs) : otherKids} | |
| otherwise | |
= Node{datum = datum root | |
,children = insertStr Node{datum = Just (head xs), children = []} (tail xs) : kids} | |
emptyTrie :: Trie a | |
emptyTrie = Node{datum = Nothing, children = []} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment