0 | module Libraries.Data.StringTrie
3 | import Libraries.Data.StringMap
10 | record StringTrie a where
11 | constructor MkStringTrie
12 | node : These a (StringMap (StringTrie a))
15 | Show a => Show (StringTrie a) where
16 | show (MkStringTrie node) = assert_total $
show node
19 | Functor StringTrie where
20 | map f (MkStringTrie node) = MkStringTrie $
assert_total $
bimap f (map (map f)) node
23 | empty : StringTrie a
24 | empty = MkStringTrie $
That empty
27 | singleton : List String -> a -> StringTrie a
28 | singleton [] v = MkStringTrie $
This v
29 | singleton (k::ks) v = MkStringTrie $
That $
singleton k (singleton ks v)
33 | insertWith : List String -> (Maybe a -> a) -> StringTrie a -> StringTrie a
34 | insertWith [] f (MkStringTrie nd) =
35 | MkStringTrie $
these (This . f . Just) (Both (f Nothing)) (Both . f . Just) nd
36 | insertWith (k::ks) f (MkStringTrie nd) =
37 | MkStringTrie $
these (\x => Both x (singleton k end)) (That . rec) (\x => Both x . rec) nd
40 | end = singleton ks (f Nothing)
41 | rec : StringMap (StringTrie a) -> StringMap (StringTrie a)
42 | rec sm = maybe (insert k end sm) (\tm => insert k (insertWith ks f tm) sm) (lookup k sm)
45 | insert : List String -> a -> StringTrie a -> StringTrie a
46 | insert ks v = insertWith ks (const v)
51 | foldWithKeysM : (Monad m, Monoid b) => (List String -> m b) -> (List String -> a -> m b) -> StringTrie a -> m b
52 | foldWithKeysM {a} {m} {b} fk fv = go []
54 | go : List String -> StringTrie a -> m b
55 | go ks (MkStringTrie nd) =
56 | bifold <$> bitraverse
59 | (\x, (k, vs) => do let ks' = ks++[k]
60 | y <- assert_total $
go ks' vs
62 | pure $
x <+> y <+> z)
64 | (StringMap.toList sm))