{-# LANGUAGE Safe #-}
module Algebra.PartialOrd (
PartialOrd(..),
partialOrdEq,
lfpFrom, unsafeLfpFrom,
gfpFrom, unsafeGfpFrom
) where
import qualified Data.Set as S
import qualified Data.IntSet as IS
import qualified Data.Map as M
import qualified Data.IntMap as IM
class Eq a => PartialOrd a where
leq :: a -> a -> Bool
partialOrdEq :: PartialOrd a => a -> a -> Bool
partialOrdEq x y = leq x y && leq y x
instance Ord a => PartialOrd (S.Set a) where
leq = S.isSubsetOf
instance PartialOrd IS.IntSet where
leq = IS.isSubsetOf
instance (Ord k, PartialOrd v) => PartialOrd (M.Map k v) where
m1 `leq` m2 = m1 `M.isSubmapOf` m2 && M.fold (\(x1, x2) b -> b && x1 `leq` x2) True (M.intersectionWith (,) m1 m2)
instance PartialOrd v => PartialOrd (IM.IntMap v) where
im1 `leq` im2 = im1 `IM.isSubmapOf` im2 && IM.fold (\(x1, x2) b -> b && x1 `leq` x2) True (IM.intersectionWith (,) im1 im2)
instance (PartialOrd a, PartialOrd b) => PartialOrd (a, b) where
(x1, y1) `leq` (x2, y2) = x1 `leq` x2 && y1 `leq` y2
lfpFrom :: PartialOrd a => a -> (a -> a) -> a
lfpFrom = lfpFrom' leq
unsafeLfpFrom :: Eq a => a -> (a -> a) -> a
unsafeLfpFrom = lfpFrom' (\_ _ -> True)
{-# INLINE lfpFrom' #-}
lfpFrom' :: Eq a => (a -> a -> Bool) -> a -> (a -> a) -> a
lfpFrom' check init_x f = go init_x
where go x | x' == x = x
| x `check` x' = go x'
| otherwise = error "lfpFrom: non-monotone function"
where x' = f x
{-# INLINE gfpFrom #-}
gfpFrom :: PartialOrd a => a -> (a -> a) -> a
gfpFrom = gfpFrom' leq
{-# INLINE unsafeGfpFrom #-}
unsafeGfpFrom :: Eq a => a -> (a -> a) -> a
unsafeGfpFrom = gfpFrom' (\_ _ -> True)
{-# INLINE gfpFrom' #-}
gfpFrom' :: Eq a => (a -> a -> Bool) -> a -> (a -> a) -> a
gfpFrom' check init_x f = go init_x
where go x | x' == x = x
| x' `check` x = go x'
| otherwise = error "gfpFrom: non-antinone function"
where x' = f x