diff --git a/distributors-core/CHANGELOG.md b/distributors-core/CHANGELOG.md index e0a26bba..f09aebf4 100644 --- a/distributors-core/CHANGELOG.md +++ b/distributors-core/CHANGELOG.md @@ -4,6 +4,31 @@ ### New APIs +- Kleene quantifiers: `quantK`, a `KleeneStarAlgebra` method, & `quantP`, + an `Alternator` method, repeat between some numbers of times, + @x{lo,hi}@ or @x{lo,}@, defaulting to their unfoldings, so static + `Alternator`s & Kleene algebras may keep counts. `inRange`, & so + `exactly`, `atLeast` & `atMost`, are `quantP`. +- More `DisjunctiveMonoid` instances: every `Alternative` of the + dependencies, `base`, `containers`, `vector`, `transformers`, `free`, + `lens` & `witherable`, by `empty` & `<|>`, now with lists, `Seq`s, + `Vector`s, monad transformers, free monads & `ReifiedFold`s; & `Set`s, + `IntSet`s, `Map`s & `IntMap`s, by their monoids, of union. +- `Bits` types are `BooleanAlgebra`s of bit vectors, by `.|.`, `.&.` & + `complement`: every `Int` & `Word`, `Integer`, `IntPtr`, `WordPtr` & the + integers of `Foreign.C.Types`; & `Natural`, without `complement`, only a + `DisjunctiveMonoid`. +- `KleeneStarAlgebra`s: `Predicate`s, whose star is true, & `Ap`s of + `Alternative`s of `Monoid`s, languages, starred by `many`, a + near-semiring. `ReadPrec` is `Filterable`. +- `ctxList` & its combinators, `terminateBy`, `delimitBy`, `balanceBy` + & `countWith`, step through any stream, @(Cons s s a a, AsEmpty s)@, + like a `Data.Sequence.Seq` or `Data.Text.Text`, not only lists. +- `ctxTree`, a deterministic top-down tree machine over the cofree + comonad of a `Traversable`, deciding by each node's focus its children's + states, of which `ctxList` is the case of `Maybe`, of non-empty streams; + & `arityWith`, count-prefixed trees, each node's focus counting its + children, as `countWith` counts a stream's. - `Enumerable`, in `Data.Traversable.Homogeneous`, of `Homogeneous` countable sums of single copies, sequenced `enumerably` by `CocartesianMonoidal`s, with generic defaults by `Generic1`. @@ -50,7 +75,7 @@ `AVarifocal`, `varifocus`, `runVarifocus`, `runVarifocusT` & `cloneVarifocal`; `crossVarifocal`, `altVarifocal`, `orVarifocal` & `bindVarifocal`, - the last choosing a second by what the first built, like a netstring; & `stepping`, a deterministic machine over foci, + the last choosing a second by what the first built, like a netstring; & `ctxList`, a deterministic machine over foci, deciding by each built whether to continue, stop or reject, with its instances `terminateBy`, `delimitBy`, `balanceBy` & `countWith`: sentinel-terminated, matching-delimitBy, nested & count-prefixed diff --git a/distributors-core/distributors.cabal b/distributors-core/distributors.cabal index 2f2b41c5..1a519709 100644 --- a/distributors-core/distributors.cabal +++ b/distributors-core/distributors.cabal @@ -100,6 +100,7 @@ library , containers >=0.6 && <1 , contravariant >=1.5 && <2 , distributive >=0.6 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -167,6 +168,7 @@ test-suite doctests , distributive >=0.6 && <1 , distributors , doctest-parallel >=0.3 && <1 + , free >=5.1 && <6 , lens >=5.0 && <6 , profunctors >=5.6 && <6 , tagged >=0.8 && <1 @@ -181,6 +183,7 @@ test-suite test type: exitcode-stdio-1.0 main-is: Main.hs other-modules: + Properties.Disjunctive Properties.Homogeneous Properties.Nested Properties.Parsing @@ -238,6 +241,7 @@ test-suite test , contravariant >=1.5 && <2 , distributive >=0.6 && <1 , distributors + , free >=5.1 && <6 , hspec >=2.7 && <3 , lens >=5.0 && <6 , profunctors >=5.6 && <6 diff --git a/distributors-core/package.yaml b/distributors-core/package.yaml index 4e1f822f..713bcf89 100644 --- a/distributors-core/package.yaml +++ b/distributors-core/package.yaml @@ -25,6 +25,7 @@ dependencies: - containers >= 0.6 && < 1 - contravariant >= 1.5 && < 2 - distributive >= 0.6 && < 1 +- free >= 5.1 && < 6 - lens >= 5.0 && < 6 - transformers >= 0.5 && < 1 - profunctors >= 5.6 && < 6 diff --git a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs index bb0ebc0d..d160e6c3 100644 --- a/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs +++ b/distributors-core/src/Control/Lens/Internal/Distributor/Orphanage.hs @@ -33,6 +33,7 @@ import Data.Profunctor.Composition import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Text.ParserCombinators.ReadP (ReadP) +import Text.ParserCombinators.ReadPrec (ReadPrec) import Witherable -- Orphanage -- @@ -76,6 +77,8 @@ instance Filterable f => Cochoice (Joker f) where (mapMaybe (either (const Nothing) Just) x) instance Filterable ReadP where catMaybes m = m >>= maybe empty pure +instance Filterable ReadPrec where + catMaybes m = m >>= maybe empty pure deriving via Compose (p a) f instance (Profunctor p, Applicative (p a), Applicative f) => Applicative (WrappedPafb f p a) diff --git a/distributors-core/src/Control/Lens/Prismoid.hs b/distributors-core/src/Control/Lens/Prismoid.hs index f3715ed7..3389dae4 100644 --- a/distributors-core/src/Control/Lens/Prismoid.hs +++ b/distributors-core/src/Control/Lens/Prismoid.hs @@ -42,7 +42,7 @@ module Control.Lens.Prismoid import Control.Applicative import Control.Monad (void) -import Data.Maybe (fromMaybe, isJust) +import Data.Maybe (fromMaybe) import Control.Lens import Control.Lens.Internal.Profunctor import Control.Lens.PartialIso @@ -204,7 +204,7 @@ withPrismoid pat k = {- | Exactly some number of times, or separated by `sepBy`. > prop> exactly n = inRange n (Just n) -> prop> exactly n >?* p = replicateP n p +> prop> exactly n >?* p = replicateP n p, for @n >= 0@ -} exactly :: Int -> Prismoid [a] [b] a b exactly n = inRange n (Just n) @@ -246,7 +246,7 @@ atMost n = inRange 0 (Just n) It takes the mandatory times first, then, unbounded, the `Alternator`'s own `someP` or `manyP`, or, bounded, the optional times, trying more first. -It never matches where @lo > hi@. +It never matches where @lo > hi@, nor where @hi@ is negative. >>> let digits lo hi = runJoker (inRange lo hi >?* Joker (satisfy isDigit)) :: ReadP String >>> [ds | (ds, "") <- readP_to_S (digits 2 (Just 3)) "123"] @@ -255,18 +255,7 @@ It never matches where @lo > hi@. ["12","123"] -} inRange :: Int -> Maybe Int -> Prismoid [a] [b] a b -inRange lo hi = rmap sequenceA . go lo hi - where - go :: Alternator p => Int -> Maybe Int -> p a b -> p [a] [b] - go l h p - | maybe False (l >) h = empty - | l > 1 || (l == 1 && isJust h) = p >:< go (l - 1) (subtract 1 <$> h) p - | l == 1 = someP p - | otherwise = case h of - Nothing -> manyP p - Just m - | m <= 0 -> eotList . swapped >~ empty >+< oneP - | otherwise -> eotList . swapped >~ p >*< go 0 (Just (m - 1)) p >+< oneP +inRange lo hi = rmap sequenceA . quantP lo hi {- | One or zero with default. -} opted :: APrism a b () () -> Prismoid a b a b diff --git a/distributors-core/src/Control/Lens/Varifocal.hs b/distributors-core/src/Control/Lens/Varifocal.hs index 1741ac5a..2dabf629 100644 --- a/distributors-core/src/Control/Lens/Varifocal.hs +++ b/distributors-core/src/Control/Lens/Varifocal.hs @@ -1,3 +1,7 @@ +-- `Varifocal` requires a `Filterable` monad, so that every +-- `Control.Lens.Bifocal.Bifocal` is a `Varifocal`, which `ctxList` & +-- its combinators, generic in their streams, needn't use. +{-# OPTIONS_GHC -Wno-redundant-constraints #-} {- | Module : Control.Lens.Varifocal Description : varifocals @@ -26,19 +30,25 @@ module Control.Lens.Varifocal , contextually , contextuallyT -- * Combinators - , stepping + , ctxList + , ctxTree , terminateBy , delimitBy , balanceBy , countWith + , arityWith ) where import Control.Applicative (Alternative (..)) -import Control.Lens -import Control.Lens.PartialIso ((>?)) +import Control.Comonad.Cofree (Cofree (..)) +import Control.Lens hiding ((:<)) +import Control.Lens.PartialIso ((>?), (>~)) import Control.Monad (MonadPlus (..), ap) import Data.Bool (bool) -import Data.Monoid.Disjunctive (DisjunctiveMonoid (..)) +import Data.Foldable (toList) +import Data.Functor (void) +import Data.Traversable (mapAccumL) +import Data.Monoid.Disjunctive (DisjunctiveMonoid (..), anyP) import Data.Profunctor (Cochoice (..)) import Data.Profunctor.Distributor import Data.Profunctor.Filtrator (Filtrator (..), mfiltrate) @@ -127,6 +137,8 @@ instance Monad m => Monad (Varifocus a b m s) where instance Monad m => Alternative (Varifocus a b m s) where empty = AltsP [] x <|> y = AltsP [x, y] + many = lmap repeat . manyP + some = lmap repeat . someP instance Monad m => DisjunctiveMonoid (Varifocus a b m s t) instance Monad m => Choice (Varifocus a b m) where left' = AlternateP . Left @@ -183,14 +195,10 @@ runVarifocus v p = go v go :: Varifocus a b [] s' t' -> p s' t' go = \case FocusP -> p - LiftP xs -> case map pure xs of - [] -> empty - ys -> foldr1 (<|>) ys + LiftP xs -> anyP pure xs BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) @@ -212,9 +220,7 @@ runVarifocusT v p = go v LiftP mt -> liftP mt BindP x k -> go x >>= go . k LmapP f x -> lmap f (go x) - AltsP xs -> case map go xs of - [] -> empty - ys -> foldr1 (<|>) ys + AltsP xs -> anyP go xs AlternateP e -> alternate (either (Left . go) (Right . go) e) ManyP x -> manyP (go x) OptionalP x -> optionalP (go x) @@ -294,10 +300,13 @@ contextuallyT vari p = joinP (vari (rmap pure p)) deciding by each focus built whether to continue, @`Right` state@, to stop there, @`Left` `True`@, or to reject, @`Left` `False`@, as no `Control.Lens.Bifocal.Bifocal` can. -A list matches when its last focus, & no earlier one, stops it. +A stream, like a list, matches when its last focus, +& no earlier one, stops it. -} -stepping :: st -> (st -> a -> Either Bool st) -> Varifocal' [a] a -stepping st0 step q = rmap pure (go st0) +ctxList + :: (Cons s s a a, AsEmpty s) + => st -> (st -> a -> Either Bool st) -> Varifocal' s a +ctxList st0 step q = rmap pure (go st0) where go st = _Cons >? P.do b <- joinP q @@ -306,24 +315,55 @@ stepping st0 step q = rmap pure (go st0) Left True -> asEmpty Left False -> empty +{- | Foci stepped through by a deterministic top-down tree machine, +from a state, deciding by each node's focus built which children +it has, a state for each position of a `Traversable` @g@, +or rejecting it, by `Nothing`, as no `Control.Lens.Bifocal.Bifocal` can. +Foci are visited in preorder, a node's before its children's. +A tree matches when each node's children have the shape +its focus decides, so that it parses as it prints. + +`ctxList` is `ctxTree` at `Maybe`, of non-empty streams, +as the cofree comonad of `Maybe`, by which +@`Left` `False`@, @`Left` `True`@ & @`Right` state@ +decide `Nothing`, @`Just` `Nothing`@ & @`Just` (`Just` state)@; +`ctxList` steps through a stream directly, rather than through +a `Cofree`, & needn't check a shape, as a stream's is its focus's. +-} +ctxTree + :: (Traversable g, Eq (g ())) + => st -> (st -> a -> Maybe (g st)) -> Varifocal' (Cofree g a) a +ctxTree st0 step q = rmap pure (go st0) + where + go st = cofreed >~ P.do + b <- joinP q + maybe empty offspring (step st b) + offspring states = shaped states >? sequenceA + (snd (mapAccumL (\i st -> (i + 1, child i st)) (0 :: Int) states)) + -- after shaping, the child at a position of the children + child i st = lmap (\kids -> toList kids !! i) (go st) + shaped states = prism' id $ \kids -> + if void kids == void states then Just kids else Nothing + cofreed = iso (\(b :< kids) -> (b, kids)) (uncurry (:<)) + {- | Zero or more foci, then one which @end@s them, deciding by each focus built, like a sentinel-terminated sequence, a C string's. -A list which doesn't end by its first ending focus doesn't match. +A stream which doesn't end by its first ending focus doesn't match. -> prop> terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) +> prop> terminateBy end = ctxList () (\() -> bool (Right ()) (Left True) . end) -} -terminateBy :: (a -> Bool) -> Varifocal' [a] a -terminateBy end = stepping () (\() -> bool (Right ()) (Left True) . end) +terminateBy :: (Cons s s a a, AsEmpty s) => (a -> Bool) -> Varifocal' s a +terminateBy end = ctxList () (\() -> bool (Right ()) (Left True) . end) {- | Foci opened by the first, & closed by the first after it which matches it, deciding by the opening focus built, like a [heredoc](https://en.wikipedia.org/wiki/Here_document)'s tag, or a fenced code block's fence, whose language, of matching delimiters, isn't context-free. -A list which doesn't close by its first match doesn't match. +A stream which doesn't close by its first match doesn't match. -} -delimitBy :: (a -> a -> Bool) -> Varifocal' [a] a -delimitBy same = stepping Nothing $ \st b -> case st of +delimitBy :: (Cons s s a a, AsEmpty s) => (a -> a -> Bool) -> Varifocal' s a +delimitBy same = ctxList Nothing $ \st b -> case st of Nothing -> Right (Just b) Just open -> bool (Right st) (Left True) (same open b) @@ -331,10 +371,12 @@ delimitBy same = stepping Nothing $ \st b -> case st of at the same nesting depth, like nested comments, @/* /* */ */@, or a balanceBy block, whose language, of nested pairs, isn't regular. A focus may not both @open@ & @close@. -A list which doesn't open first, or close only last, doesn't match. +A stream which doesn't open first, or close only last, doesn't match. -} -balanceBy :: (a -> Bool) -> (a -> Bool) -> Varifocal' [a] a -balanceBy open close = stepping (0 :: Int) step +balanceBy + :: (Cons s s a a, AsEmpty s) + => (a -> Bool) -> (a -> Bool) -> Varifocal' s a +balanceBy open close = ctxList (0 :: Int) step where step depth b | open b = Right (depth + 1) @@ -345,9 +387,19 @@ balanceBy open close = stepping (0 :: Int) step {- | A focus counting how many foci follow it, then those, like a length-prefixed record of bytes in a binary format. -A list which doesn't have as many as its first focus counts doesn't match. +A stream which doesn't have as many as its first focus counts +doesn't match. -} -countWith :: (a -> Int) -> Varifocal' [a] a -countWith count = stepping Nothing $ \st b -> case st of +countWith :: (Cons s s a a, AsEmpty s) => (a -> Int) -> Varifocal' s a +countWith count = ctxList Nothing $ \st b -> case st of Nothing -> if count b <= 0 then Left True else Right (Just (count b)) Just n -> if n <= 1 then Left True else Right (Just (n - 1)) + +{- | A tree whose nodes' foci each count their children, +like a count-prefixed tree of records in a binary format, +by `ctxTree`, as `countWith` counts a stream's. +A node counting fewer than none doesn't match. +-} +arityWith :: (a -> Int) -> Varifocal' (Cofree [] a) a +arityWith arity = ctxTree () $ \() b -> + if arity b < 0 then Nothing else Just (replicate (arity b) ()) diff --git a/distributors-core/src/Data/Monoid/Disjunctive.hs b/distributors-core/src/Data/Monoid/Disjunctive.hs index 8f0406da..b7f76ed1 100644 --- a/distributors-core/src/Data/Monoid/Disjunctive.hs +++ b/distributors-core/src/Data/Monoid/Disjunctive.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE DeriveAnyClass #-} {- | Module : Data.Monoid.Disjunctive Description : disjunctive monoids, Boolean & Kleene star algebras @@ -41,10 +42,47 @@ import Data.Profunctor.Cayley import Data.Profunctor.Monad import Data.Profunctor.Yoneda import Data.Proxy +import Control.Alternative.Free qualified as FreeAlt +import Control.Applicative.Backwards (Backwards) +import Control.Applicative.Lift (Lift) +import Control.Lens (ReifiedFold) +import Control.Monad.Free (Free) +import Control.Monad.Free.Church qualified as Church +import Control.Monad.Trans.Accum (AccumT) +import Control.Monad.Trans.Except (ExceptT) +import Control.Monad.Trans.Free (FreeT) +import Control.Monad.Trans.Free.Church (FT) +import Control.Monad.Trans.Identity (IdentityT) +import Control.Monad.Trans.Maybe (MaybeT) +import Control.Monad.Trans.Reader (ReaderT) +import Control.Monad.Trans.RWS.CPS qualified as CPSRWS +import Control.Monad.Trans.RWS.Lazy qualified as LazyRWS +import Control.Monad.Trans.RWS.Strict qualified as StrictRWS +import Control.Monad.Trans.Select (SelectT) +import Control.Monad.Trans.State.Lazy qualified as Lazy +import Control.Monad.Trans.State.Strict qualified as Strict +import Control.Monad.Trans.Writer.CPS qualified as CPSW +import Control.Monad.Trans.Writer.Lazy qualified as LazyW +import Control.Monad.Trans.Writer.Strict qualified as StrictW +import Data.Functor.Reverse (Reverse) +import Data.Bits (Bits (..)) +import Data.Maybe (isJust) +import Data.Int (Int8, Int16, Int32, Int64) +import Data.IntMap (IntMap) +import Data.IntSet (IntSet) +import Data.Map (Map) +import Data.Sequence (Seq) +import Data.Set (Set) +import Data.Vector (Vector) +import Data.Word (Word8, Word16, Word32, Word64) +import Foreign.C.Types +import Foreign.Ptr (IntPtr, WordPtr) import GHC.Conc (STM) +import Numeric.Natural (Natural) import GHC.Generics import Text.ParserCombinators.ReadP (ReadP) import Text.ParserCombinators.ReadPrec (ReadPrec) +import Witherable (WrappedFoldable) {- | A `DisjunctiveMonoid` is simply a monoid, the only difference from `Monoid` being its semantics @@ -140,6 +178,33 @@ class (Monoid k, DisjunctiveMonoid k) => KleeneStarAlgebra k where plusK x = x <> starK x optK x = mempty >|< x + {- | A Kleene quantifier, between some numbers of times, inclusive, + at least a lower bound, & at most an upper bound, if there's one, + like a regular expression's @x{lo,hi}@, or @x{lo,}@. Its counts are those @n >= 0@ within its + bounds, so it fails where they're out of order, or all negative, + as regular expression languages reject such quantifiers. + + > prop> quantK 0 Nothing = starK + > prop> quantK 1 Nothing = plusK + > prop> quantK 0 (Just 1) = optK + > prop> quantK n (Just n) x = mconcat (replicate n x), for @n >= 0@ + > prop> quantK (n + 1) hi x = x <> quantK n (subtract 1 <$> hi) x, for @n >= 0@ + > prop> quantK (-1) hi = quantK 0 hi + > prop> quantK 0 (Just (-1)) x = falseP + -} + quantK :: Int -> Maybe Int -> k -> k + quantK lo hi x + | lo < 0 = quantK 0 hi x + | maybe False (lo >) hi = falseP + | lo > 1 || (lo == 1 && isJust hi) = + x <> quantK (lo - 1) (subtract 1 <$> hi) x + | lo == 1 = plusK x + | otherwise = case hi of + Nothing -> starK x + Just m + | m <= 0 -> mempty + | otherwise -> optK (x <> quantK 0 (Just (m - 1)) x) + --instances instance DisjunctiveMonoid Bool where falseP = False @@ -235,16 +300,176 @@ deriving via Generically (Const a b) deriving via Generically (Proxy a) instance DisjunctiveMonoid (Proxy a) deriving via Generically (Proxy a) instance BooleanAlgebra (Proxy a) deriving via Generically (Proxy a) instance KleeneStarAlgebra (Proxy a) -instance DisjunctiveMonoid (Maybe a) -instance DisjunctiveMonoid (IO a) -instance DisjunctiveMonoid (STM a) -instance DisjunctiveMonoid (ZipList a) -instance DisjunctiveMonoid (ReadP a) -instance DisjunctiveMonoid (ReadPrec a) -instance DisjunctiveMonoid (U1 p) -instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) -instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) -instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) +{- | Bits disjoin by `.|.`, & conjoin by `.&.`, of a Boolean algebra +of bit vectors, `Integer`'s of infinitely many bits, two's complement. +`Natural` has no `complement`, so it only disjoins. +-} +newtype Bitwise a = Bitwise a +instance Bits a => DisjunctiveMonoid (Bitwise a) where + falseP = Bitwise zeroBits + Bitwise x >|< Bitwise y = Bitwise (x .|. y) +instance Bits a => BooleanAlgebra (Bitwise a) where + trueP = Bitwise (complement zeroBits) + notP (Bitwise x) = Bitwise (complement x) + Bitwise x >&< Bitwise y = Bitwise (x .&. y) +deriving via Bitwise Int instance DisjunctiveMonoid Int +deriving via Bitwise Int instance BooleanAlgebra Int +deriving via Bitwise Int8 instance DisjunctiveMonoid Int8 +deriving via Bitwise Int8 instance BooleanAlgebra Int8 +deriving via Bitwise Int16 instance DisjunctiveMonoid Int16 +deriving via Bitwise Int16 instance BooleanAlgebra Int16 +deriving via Bitwise Int32 instance DisjunctiveMonoid Int32 +deriving via Bitwise Int32 instance BooleanAlgebra Int32 +deriving via Bitwise Int64 instance DisjunctiveMonoid Int64 +deriving via Bitwise Int64 instance BooleanAlgebra Int64 +deriving via Bitwise Word instance DisjunctiveMonoid Word +deriving via Bitwise Word instance BooleanAlgebra Word +deriving via Bitwise Word8 instance DisjunctiveMonoid Word8 +deriving via Bitwise Word8 instance BooleanAlgebra Word8 +deriving via Bitwise Word16 instance DisjunctiveMonoid Word16 +deriving via Bitwise Word16 instance BooleanAlgebra Word16 +deriving via Bitwise Word32 instance DisjunctiveMonoid Word32 +deriving via Bitwise Word32 instance BooleanAlgebra Word32 +deriving via Bitwise Word64 instance DisjunctiveMonoid Word64 +deriving via Bitwise Word64 instance BooleanAlgebra Word64 +deriving via Bitwise Integer instance DisjunctiveMonoid Integer +deriving via Bitwise Integer instance BooleanAlgebra Integer +deriving via Bitwise IntPtr instance DisjunctiveMonoid IntPtr +deriving via Bitwise IntPtr instance BooleanAlgebra IntPtr +deriving via Bitwise WordPtr instance DisjunctiveMonoid WordPtr +deriving via Bitwise WordPtr instance BooleanAlgebra WordPtr +deriving via Bitwise CChar instance DisjunctiveMonoid CChar +deriving via Bitwise CChar instance BooleanAlgebra CChar +deriving via Bitwise CSChar instance DisjunctiveMonoid CSChar +deriving via Bitwise CSChar instance BooleanAlgebra CSChar +deriving via Bitwise CUChar instance DisjunctiveMonoid CUChar +deriving via Bitwise CUChar instance BooleanAlgebra CUChar +deriving via Bitwise CShort instance DisjunctiveMonoid CShort +deriving via Bitwise CShort instance BooleanAlgebra CShort +deriving via Bitwise CUShort instance DisjunctiveMonoid CUShort +deriving via Bitwise CUShort instance BooleanAlgebra CUShort +deriving via Bitwise CInt instance DisjunctiveMonoid CInt +deriving via Bitwise CInt instance BooleanAlgebra CInt +deriving via Bitwise CUInt instance DisjunctiveMonoid CUInt +deriving via Bitwise CUInt instance BooleanAlgebra CUInt +deriving via Bitwise CLong instance DisjunctiveMonoid CLong +deriving via Bitwise CLong instance BooleanAlgebra CLong +deriving via Bitwise CULong instance DisjunctiveMonoid CULong +deriving via Bitwise CULong instance BooleanAlgebra CULong +deriving via Bitwise CLLong instance DisjunctiveMonoid CLLong +deriving via Bitwise CLLong instance BooleanAlgebra CLLong +deriving via Bitwise CULLong instance DisjunctiveMonoid CULLong +deriving via Bitwise CULLong instance BooleanAlgebra CULLong +deriving via Bitwise CPtrdiff instance DisjunctiveMonoid CPtrdiff +deriving via Bitwise CPtrdiff instance BooleanAlgebra CPtrdiff +deriving via Bitwise CSize instance DisjunctiveMonoid CSize +deriving via Bitwise CSize instance BooleanAlgebra CSize +deriving via Bitwise CWchar instance DisjunctiveMonoid CWchar +deriving via Bitwise CWchar instance BooleanAlgebra CWchar +deriving via Bitwise CSigAtomic instance DisjunctiveMonoid CSigAtomic +deriving via Bitwise CSigAtomic instance BooleanAlgebra CSigAtomic +deriving via Bitwise CIntPtr instance DisjunctiveMonoid CIntPtr +deriving via Bitwise CIntPtr instance BooleanAlgebra CIntPtr +deriving via Bitwise CUIntPtr instance DisjunctiveMonoid CUIntPtr +deriving via Bitwise CUIntPtr instance BooleanAlgebra CUIntPtr +deriving via Bitwise CIntMax instance DisjunctiveMonoid CIntMax +deriving via Bitwise CIntMax instance BooleanAlgebra CIntMax +deriving via Bitwise CUIntMax instance DisjunctiveMonoid CUIntMax +deriving via Bitwise CUIntMax instance BooleanAlgebra CUIntMax +deriving via Bitwise CBool instance DisjunctiveMonoid CBool +deriving via Bitwise CBool instance BooleanAlgebra CBool +deriving via Bitwise Natural instance DisjunctiveMonoid Natural + +{- | A `Predicate` is a Kleene algebra, as a Boolean algebra is, +of conjunction, `Predicate`'s `Monoid`, & disjunction, +whose star is true. + +> prop> starK p = trueP +-} +instance KleeneStarAlgebra (Predicate a) where + starK _ = trueP + plusK = id + optK _ = trueP + +{- | An `Alternative` of `Monoid`s is a Kleene algebra of languages, +like a parser of words: its sequence is `Ap`'s `Monoid`, its +alternation `<|>`, & its star `many` concatenated. It's a near-semiring, +whose left distribution, @(x >|< y) <> z = (x <> z) >|< (y <> z)@, +a left-biased `Alternative` may not keep, & its star diverges where +`many` does, as of a non-empty list's. + +> prop> starK (Ap x) = Ap (mconcat <$> many x) +> prop> plusK (Ap x) = Ap (mconcat <$> some x) +-} +instance (Alternative f, Monoid a, DisjunctiveMonoid (f a)) + => KleeneStarAlgebra (Ap f a) where + starK (Ap x) = Ap (mconcat <$> many x) + plusK (Ap x) = Ap (mconcat <$> some x) + +-- | Sets & maps disjoin by their monoids, of union. +instance Ord a => DisjunctiveMonoid (Set a) where + falseP = mempty + (>|<) = (<>) +instance DisjunctiveMonoid IntSet where + falseP = mempty + (>|<) = (<>) +instance Ord k => DisjunctiveMonoid (Map k v) where + falseP = mempty + (>|<) = (<>) +instance DisjunctiveMonoid (IntMap v) where + falseP = mempty + (>|<) = (<>) +-- `Alternative`s disjoin by `empty` & `<|>`. +deriving anyclass instance DisjunctiveMonoid [a] +deriving anyclass instance DisjunctiveMonoid (Maybe a) +deriving anyclass instance DisjunctiveMonoid (IO a) +deriving anyclass instance DisjunctiveMonoid (STM a) +deriving anyclass instance DisjunctiveMonoid (ZipList a) +deriving anyclass instance DisjunctiveMonoid (ReadP a) +deriving anyclass instance DisjunctiveMonoid (ReadPrec a) +deriving anyclass instance DisjunctiveMonoid (U1 p) +deriving anyclass instance DisjunctiveMonoid (Seq a) +deriving anyclass instance DisjunctiveMonoid (Vector a) +deriving anyclass instance MonadPlus m => DisjunctiveMonoid (WrappedMonad m a) +deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (WrappedArrow a b c) +deriving anyclass instance ArrowPlus a => DisjunctiveMonoid (ArrowMonad a b) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Backwards f a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Lift f a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Reverse f a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (IdentityT m a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (ReaderT r m a) +deriving anyclass instance (Functor m, Monad m) + => DisjunctiveMonoid (MaybeT m a) +deriving anyclass instance (Functor m, Monad m, Monoid e) + => DisjunctiveMonoid (ExceptT e m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (Lazy.StateT s m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (Strict.StateT s m a) +deriving anyclass instance (Monoid w, Alternative m) + => DisjunctiveMonoid (LazyW.WriterT w m a) +deriving anyclass instance (Monoid w, Alternative m) + => DisjunctiveMonoid (StrictW.WriterT w m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (CPSW.WriterT w m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (LazyRWS.RWST r w s m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (StrictRWS.RWST r w s m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (CPSRWS.RWST r w s m a) +deriving anyclass instance (Monoid w, Functor m, MonadPlus m) + => DisjunctiveMonoid (AccumT w m a) +deriving anyclass instance (Functor m, MonadPlus m) + => DisjunctiveMonoid (SelectT r m a) +deriving anyclass instance Alternative v => DisjunctiveMonoid (Free v a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (Church.F f a) +deriving anyclass instance (Functor f, MonadPlus m) + => DisjunctiveMonoid (FreeT f m a) +deriving anyclass instance Alternative m => DisjunctiveMonoid (FT f m a) +deriving anyclass instance DisjunctiveMonoid (FreeAlt.Alt f a) +deriving anyclass instance DisjunctiveMonoid (ReifiedFold s a) +deriving anyclass instance Alternative f => DisjunctiveMonoid (WrappedFoldable f a) instance DisjunctiveMonoid (f a) => DisjunctiveMonoid (Alt f a) where falseP = Alt falseP Alt x >|< Alt y = Alt (x >|< y) diff --git a/distributors-core/src/Data/Profunctor/Distributor.hs b/distributors-core/src/Data/Profunctor/Distributor.hs index 341fb694..b1cd9a6d 100644 --- a/distributors-core/src/Data/Profunctor/Distributor.hs +++ b/distributors-core/src/Data/Profunctor/Distributor.hs @@ -37,6 +37,7 @@ import Data.Profunctor.Monad import Data.Profunctor.Monoidal import Data.Profunctor.Yoneda import Data.Profunctor.Monoidal.Cocartesian +import Data.Maybe (isJust) -- $setup -- >>> import Data.Bifunctor.Joker (Joker (..)) @@ -193,18 +194,50 @@ class (Distributor p, CocartesianChoice p, forall x. Alternative (p x)) manyTillP :: p a b -> p [a] [b] -> p [a] [b] manyTillP p q = let r = q >|< p >:< r in r + {- | A Kleene quantifier, between some numbers of times, inclusive, + at least a lower bound, & at most an upper bound, if there's one, + like a regular expression's @{lo,hi}@, or @{lo,}@. It takes the mandatory times first, then, + unbounded, `someP` or `manyP`, or, bounded, the optional times, + trying more first. It never matches where @lo > hi@, + nor where @hi@ is negative, its counts being those @n >= 0@ within + its bounds. + + It mirrors a `KleeneStarAlgebra`'s `quantK`, so that a static + `Alternator` may keep its counts, rather than unfolding them. + + > prop> quantP 0 Nothing = manyP + > prop> quantP 1 Nothing = someP + > prop> quantP n (Just n) = replicateP n, for @n >= 0@ + -} + quantP :: Int -> Maybe Int -> p a b -> p [a] [b] + quantP lo hi p + | lo < 0 = quantP 0 hi p + | maybe False (lo >) hi = empty + | lo > 1 || (lo == 1 && isJust hi) = + p >:< quantP (lo - 1) (subtract 1 <$> hi) p + | lo == 1 = someP p + | otherwise = case hi of + Nothing -> manyP p + Just m + | m <= 0 -> eotList . swapped >~ empty >+< oneP + | otherwise -> + eotList . swapped >~ p >*< quantP 0 (Just (m - 1)) p >+< oneP + instance (Alternator p, Applicative f) => Alternator (WrappedPafb f p) where someP (WrapPafb x) = WrapPafb (rmap sequenceA (someP x)) optionP def (WrapPafb x) = WrapPafb (optionP (prism pure pure . def) x) + quantP lo hi (WrapPafb x) = WrapPafb (rmap sequenceA (quantP lo hi x)) instance Alternator p => Alternator (Coyoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + quantP lo hi = proreturn . quantP lo hi . proextract instance Alternator p => Alternator (Yoneda p) where someP = proreturn . someP . proextract optionP def = proreturn . optionP def . proextract manyTillP p q = proreturn (manyTillP (proextract p) (proextract q)) + quantP lo hi = proreturn . quantP lo hi . proextract instance Alternative f => Alternator (Joker f) where someP (Joker x) = Joker (some x) optionP def (Joker x) = diff --git a/distributors-core/test/Main.hs b/distributors-core/test/Main.hs index 55429b23..838ca7a8 100644 --- a/distributors-core/test/Main.hs +++ b/distributors-core/test/Main.hs @@ -5,6 +5,7 @@ import Data.Profunctor.Monoidal (meander) import Data.Profunctor.Types (Star (..)) import Test.Hspec +import Properties.Disjunctive import Properties.Homogeneous import Properties.Nested import Properties.PartialIso @@ -12,6 +13,7 @@ import Properties.Parsing main :: IO () main = hspec $ do + describe "Disjunctive" disjunctiveProperties describe "Homogeneous" homogeneousProperties describe "PartialIso" partialIsoProperties describe "Nested" nestedProperties diff --git a/distributors-core/test/Properties/Disjunctive.hs b/distributors-core/test/Properties/Disjunctive.hs new file mode 100644 index 00000000..d872d9c6 --- /dev/null +++ b/distributors-core/test/Properties/Disjunctive.hs @@ -0,0 +1,47 @@ +module Properties.Disjunctive (disjunctiveProperties) where + +import Data.Functor.Contravariant (Predicate (..)) +import Data.Int (Int8) +import Data.Monoid (Ap (..)) +import Data.Monoid.Disjunctive +import Data.Word (Word8) +import Numeric.Natural (Natural) +import Test.Hspec +import Test.Hspec.QuickCheck (prop) +import Test.QuickCheck +import Text.ParserCombinators.ReadP (ReadP, readP_to_S, string) + +disjunctiveProperties :: Spec +disjunctiveProperties = do + describe "Bits, as a BooleanAlgebra of bit vectors" $ do + booleanLaws "Int" (arbitrary :: Gen Int) + booleanLaws "Int8" (arbitrary :: Gen Int8) + booleanLaws "Word8" (arbitrary :: Gen Word8) + booleanLaws "Integer" (arbitrary :: Gen Integer) + prop "Natural disjoins as a monoid" $ \(NonNegative (x :: Integer)) y -> + let n = fromInteger x :: Natural + m = fromInteger (getNonNegative y) :: Natural + in (falseP >|< n) === n .&&. (n >|< m) === (m >|< n) + describe "Predicate, as a Kleene algebra" $ + prop "its star is true" $ \(Fun _ p) (x :: Int) -> + getPredicate (starK (Predicate p)) x === True + .&&. getPredicate (optK (Predicate p)) x === True + describe "Ap, as a Kleene algebra of languages" $ + it "stars by many, concatenated" $ do + let star = getAp (starK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S star "ababab"] `shouldBe` ["ababab"] + [w | (w, "") <- readP_to_S star ""] `shouldBe` [""] + let plus = getAp (plusK (Ap (string "ab"))) :: ReadP String + [w | (w, "") <- readP_to_S plus ""] `shouldBe` [] + +booleanLaws + :: (Show b, Eq b, BooleanAlgebra b) => String -> Gen b -> Spec +booleanLaws name gen = describe name $ do + prop "x >&< notP x = falseP & x >|< notP x = trueP" $ + forAll gen $ \x -> + (x >&< notP x) === falseP .&&. (x >|< notP x) === trueP + prop "de Morgan" $ forAll gen $ \x -> forAll gen $ \y -> + notP (x >|< y) === (notP x >&< notP y) + prop "notP . notP = id" $ forAll gen $ \x -> notP (notP x) === x + prop "units" $ forAll gen $ \x -> + (x >|< falseP) === x .&&. (x >&< trueP) === x diff --git a/distributors-grammar/test/Properties/Varifocal.hs b/distributors-grammar/test/Properties/Varifocal.hs index d4f96b64..c4d7e535 100644 --- a/distributors-grammar/test/Properties/Varifocal.hs +++ b/distributors-grammar/test/Properties/Varifocal.hs @@ -49,7 +49,7 @@ varifocalProperties = do prop "doesn't print an early end" $ forAll plain $ \s -> forAll plain $ \t -> printed ended (s ++ "." ++ t ++ ".") === Nothing - describe "balanceBy & countWith, by stepping" $ do + describe "balanceBy & countWith, by ctxList" $ do let nested :: Varifocal' String Char nested = balanceBy (== '(') (== ')')