module Data.Tree.AVL.Read
(
assertReadL,tryReadL,
assertReadR,tryReadR,
assertRead,tryRead,tryReadMaybe,defaultRead,
contains,
) where
import Prelude
import Data.COrdering
import Data.Tree.AVL.Types(AVL(..))
assertReadL :: AVL e -> e
assertReadL E = error "assertReadL: Empty tree."
assertReadL (N l e _) = readLE l e
assertReadL (Z l e _) = readLE l e
assertReadL (P l _ _) = readLNE l
tryReadL :: AVL e -> Maybe e
tryReadL E = Nothing
tryReadL (N l e _) = Just $! readLE l e
tryReadL (Z l e _) = Just $! readLE l e
tryReadL (P l _ _) = Just $! readLNE l
readLNE :: AVL e -> e
readLNE E = error "readLNE: Bug."
readLNE (N l e _) = readLE l e
readLNE (Z l e _) = readLE l e
readLNE (P l _ _) = readLNE l
readLE :: AVL e -> e -> e
readLE E e = e
readLE (N l e _) _ = readLE l e
readLE (Z l e _) _ = readLE l e
readLE (P l _ _) _ = readLNE l
assertReadR :: AVL e -> e
assertReadR E = error "assertReadR: Empty tree."
assertReadR (P _ e r) = readRE r e
assertReadR (Z _ e r) = readRE r e
assertReadR (N _ _ r) = readRNE r
tryReadR :: AVL e -> Maybe e
tryReadR E = Nothing
tryReadR (P _ e r) = Just $! readRE r e
tryReadR (Z _ e r) = Just $! readRE r e
tryReadR (N _ _ r) = Just $! readRNE r
readRNE :: AVL e -> e
readRNE E = error "readRNE: Bug."
readRNE (P _ e r) = readRE r e
readRNE (Z _ e r) = readRE r e
readRNE (N _ _ r) = readRNE r
readRE :: AVL e -> e -> e
readRE E e = e
readRE (P _ e r) _ = readRE r e
readRE (Z _ e r) _ = readRE r e
readRE (N _ _ r) _ = readRNE r
assertRead :: AVL e -> (e -> COrdering a) -> a
assertRead t c = genRead' t where
genRead' E = error "assertRead failed."
genRead' (N l e r) = genRead'' l e r
genRead' (Z l e r) = genRead'' l e r
genRead' (P l e r) = genRead'' l e r
genRead'' l e r = case c e of
Lt -> genRead' l
Eq a -> a
Gt -> genRead' r
tryRead :: AVL e -> (e -> COrdering a) -> Maybe a
tryRead t c = tryRead' t where
tryRead' E = Nothing
tryRead' (N l e r) = tryRead'' l e r
tryRead' (Z l e r) = tryRead'' l e r
tryRead' (P l e r) = tryRead'' l e r
tryRead'' l e r = case c e of
Lt -> tryRead' l
Eq a -> Just a
Gt -> tryRead' r
tryReadMaybe :: AVL e -> (e -> COrdering (Maybe a)) -> Maybe a
tryReadMaybe t c = tryRead' t where
tryRead' E = Nothing
tryRead' (N l e r) = tryRead'' l e r
tryRead' (Z l e r) = tryRead'' l e r
tryRead' (P l e r) = tryRead'' l e r
tryRead'' l e r = case c e of
Lt -> tryRead' l
Eq mba -> mba
Gt -> tryRead' r
defaultRead :: a -> AVL e -> (e -> COrdering a) -> a
defaultRead d t c = genRead' t where
genRead' E = d
genRead' (N l e r) = genRead'' l e r
genRead' (Z l e r) = genRead'' l e r
genRead' (P l e r) = genRead'' l e r
genRead'' l e r = case c e of
Lt -> genRead' l
Eq a -> a
Gt -> genRead' r
contains :: AVL e -> (e -> Ordering) -> Bool
contains t c = contains' t where
contains' E = False
contains' (N l e r) = contains'' l e r
contains' (Z l e r) = contains'' l e r
contains' (P l e r) = contains'' l e r
contains'' l e r = case c e of
LT -> contains' l
EQ -> True
GT -> contains' r