module Data.Trie.Pred.Disjoint.Tail
( NDPTrie (..)
, lookup
, merge
, areDisjoint
) where
import Prelude hiding (lookup)
import Data.List.NonEmpty hiding (map)
import Data.List.NonEmpty as NE hiding (map)
data NDPTrie p t x where
NDMore :: t
-> Maybe x
-> [NDPTrie p t x]
-> NDPTrie p t x
NDPred :: p
-> (t -> Maybe r)
-> Maybe (r -> x)
-> [NDPTrie p t (r -> x)]
-> NDPTrie p t x
merge :: (Eq p, Eq t) => NDPTrie p t x -> NDPTrie p t x -> NDPTrie p t x
merge xx@(NDMore t mx xs) yy@(NDMore p my ys)
| t == p = NDMore p my $ foldr go [] $ xs ++ ys
| otherwise = xx
where
go :: (Eq p, Eq t) => NDPTrie p t x -> [NDPTrie p t x] -> [NDPTrie p t x]
go a [] = [a]
go a (b:bs) | areDisjoint a b = a : b : bs
| otherwise = (merge a b) : bs
merge xx@(NDPred t q mrx xrs) yy@(NDPred p w mry yrs)
| t == p = yy
| otherwise = xx
merge xx@(NDMore t mx xs) yy@(NDPred p w mrx xrs) = yy
merge xx@(NDPred t q mrx xrs) yy@(NDMore p my ys) = yy
areDisjoint :: (Eq p, Eq t) => NDPTrie p t x -> NDPTrie p t x -> Bool
areDisjoint (NDMore t _ _) (NDMore p _ _) = t == p
areDisjoint (NDPred t _ _ _) (NDPred p _ _ _) = t == p
areDisjoint _ _ = True
lookup :: Eq t => NonEmpty t -> NDPTrie p t x -> Maybe x
lookup (t:|ts) (NDMore t' mx xs)
| t == t' = case ts of
[] -> mx
_ -> getFirst $ map (lookup $ NE.fromList ts) xs
| otherwise = Nothing
lookup (t:|ts) (NDPred _ p mrx xrs) =
p t >>=
\r -> case ts of
[] -> ($ r) <$> mrx
_ -> ($ r) <$> (getFirst $ map (lookup $ NE.fromList ts) xrs)
getFirst :: [Maybe a] -> Maybe a
getFirst [] = Nothing
getFirst (Nothing:xs) = getFirst xs
getFirst (Just x :xs) = Just x