Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion distributors-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions distributors-core/distributors.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions distributors-core/package.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 --
Expand Down Expand Up @@ -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)
Expand Down
19 changes: 4 additions & 15 deletions distributors-core/src/Control/Lens/Prismoid.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"]
Expand All @@ -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
Expand Down
110 changes: 81 additions & 29 deletions distributors-core/src/Control/Lens/Varifocal.hs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -306,35 +315,68 @@ 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)

{- | Foci opened by one which @open@s, & closed by the one which @close@s,
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)
Expand All @@ -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) ())
Loading
Loading