machines 0.6.4 → 0.7
raw patch · 13 files changed
+436/−236 lines, 13 filesdep ~basedep ~doctest
Dependency ranges changed: base, doctest
Files
- .travis.yml +135/−120
- CHANGELOG.markdown +9/−0
- README.markdown +1/−1
- examples/Examples.hs +3/−3
- examples/machines-examples.cabal +4/−3
- machines.cabal +9/−5
- src/Data/Machine/Group.hs +5/−30
- src/Data/Machine/Group/General.hs +219/−0
- src/Data/Machine/Mealy.hs +2/−24
- src/Data/Machine/MealyT.hs +12/−48
- src/Data/Machine/Moore.hs +11/−2
- src/Data/Machine/Plan.hs +2/−0
- src/Data/Machine/Process.hs +24/−0
.travis.yml view
@@ -1,162 +1,177 @@ # This Travis job script has been generated by a script via #-# runghc make_travis_yml_2.hs '-o' '.travis.yml' '--ghc-head' '--irc-channel=irc.freenode.org#haskell-lens' '--no-no-tests-no-bench' '--no-unconstrained' 'cabal.project'+# haskell-ci '--output=.travis.yml' '--config=cabal.haskell-ci' 'cabal.project' #-# For more information, see https://github.com/hvr/multi-ghc-travis+# For more information, see https://github.com/haskell-CI/haskell-ci #+# version: 0.3.20190425+# language: c-sudo: false-+dist: xenial git:- submodules: false # whether to recursively clone submodules-+ # whether to recursively clone submodules+ submodules: false notifications: irc: channels:- - "irc.freenode.org#haskell-lens"+ - irc.freenode.org#haskell-lens skip_join: true template:- - "\x0313machines\x03/\x0306%{branch}\x03 \x0314%{commit}\x03 %{build_url} %{message}"-+ - "\"\\x0313machines\\x03/\\x0306%{branch}\\x03 \\x0314%{commit}\\x03 %{build_url} %{message}\"" cache: directories: - $HOME/.cabal/packages - $HOME/.cabal/store- before_cache:- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log+ - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log # remove files that are regenerated by 'cabal update'- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.*- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/*.json- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.cache- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar- - rm -fv $HOME/.cabal/packages/hackage.haskell.org/01-index.tar.idx-- - rm -rfv $HOME/.cabal/packages/head.hackage-+ - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.*+ - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx+ - rm -rfv $CABALHOME/packages/head.hackage matrix: include:- - compiler: "ghc-8.6.1"+ - compiler: ghc-8.8.1+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}} env: GHCHEAD=true- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-8.6.1], sources: [hvr-ghc]}}- - compiler: "ghc-8.4.3"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.4.3], sources: [hvr-ghc]}}- - compiler: "ghc-8.2.2"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.2.2], sources: [hvr-ghc]}}- - compiler: "ghc-8.0.2"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-8.0.2], sources: [hvr-ghc]}}- - compiler: "ghc-7.10.3"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.10.3], sources: [hvr-ghc]}}- - compiler: "ghc-7.8.4"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.8.4], sources: [hvr-ghc]}}- - compiler: "ghc-7.6.3"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.6.3], sources: [hvr-ghc]}}- - compiler: "ghc-7.4.2"- # env: TEST=--disable-tests BENCH=--disable-benchmarks- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-2.2,ghc-7.4.2], sources: [hvr-ghc]}}- - compiler: "ghc-head"+ - compiler: ghc-8.6.5+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-2.4"]}}+ - compiler: ghc-8.4.4+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-2.4"]}}+ - compiler: ghc-8.2.2+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-2.4"]}}+ - compiler: ghc-8.0.2+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-2.4"]}}+ - compiler: ghc-7.10.3+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.10.3","cabal-install-2.4"]}}+ - compiler: ghc-7.8.4+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.8.4","cabal-install-2.4"]}}+ - compiler: ghc-7.6.3+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.6.3","cabal-install-2.4"]}}+ - compiler: ghc-7.4.2+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-7.4.2","cabal-install-2.4"]}}+ - compiler: ghc-head+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-head","cabal-install-head"]}} env: GHCHEAD=true- addons: {apt: {packages: [ghc-ppa-tools,cabal-install-head,ghc-head], sources: [hvr-ghc]}}- allow_failures:- - compiler: "ghc-head"- - compiler: "ghc-8.6.1"-+ - compiler: ghc-head+ - compiler: ghc-8.8.1 before_install:- - HC=${CC}- - HCVER=${HC/ghc-/}- - HCPKG=${HC/ghc/ghc-pkg}+ - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')+ - HCPKG="$HC-pkg" - unset CC- - ROOTDIR=$(pwd)- - mkdir -p $HOME/.local/bin- - "PATH=/opt/ghc/bin:/opt/ghc-ppa-tools/bin:$HOME/local/bin:$PATH"+ - CABAL=/opt/ghc/bin/cabal+ - CABALHOME=$HOME/.cabal+ - export PATH="$CABALHOME/bin:$PATH"+ - TOP=$(pwd) - HCNUMVER=$(( $(${HC} --numeric-version|sed -E 's/([0-9]+)\.([0-9]+)\.([0-9]+).*/\1 * 10000 + \2 * 100 + \3/') )) - echo $HCNUMVER-+ - CABAL="$CABAL -vnormal+nowrap+markoutput"+ - set -o pipefail+ - |+ echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk+ echo 'BEGIN { state = "output"; }' >> .colorful.awk+ echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk+ echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk+ echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk+ echo ' if (state == "cabal") {' >> .colorful.awk+ echo ' print blue($0)' >> .colorful.awk+ echo ' } else {' >> .colorful.awk+ echo ' print $0' >> .colorful.awk+ echo ' }' >> .colorful.awk+ echo '}' >> .colorful.awk+ - cat .colorful.awk+ - |+ color_cabal_output () {+ awk -f $TOP/.colorful.awk+ }+ - echo text | color_cabal_output install:- - cabal --version+ - ${CABAL} --version - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"- - |- if dpkg --compare-versions "${HCVER}" ge "8.0"; then- BENCH=${BENCH---enable-benchmarks}- else- BENCH=${BENCH---disable-benchmarks}- fi- - TEST=${TEST---enable-tests}- - HADDOCK=${HADDOCK-true}- - UNCONSTRAINED=${UNCONSTRAINED-true}- - NOINSTALLEDCONSTRAINTS=${NOINSTALLEDCONSTRAINTS-false}+ - TEST=--enable-tests+ - BENCH=--enable-benchmarks+ - if [ $HCNUMVER -lt 80000 ] ; then BENCH=--disable-benchmarks ; fi - GHCHEAD=${GHCHEAD-false}- - travis_retry cabal update -v- - "sed -i.bak 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config"- - rm -fv cabal.project cabal.project.local- # Overlay Hackage Package Index for GHC HEAD: https://github.com/hvr/head.hackage+ - rm -f $CABALHOME/config - |+ echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config+ echo "remote-build-reporting: anonymous" >> $CABALHOME/config+ echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config+ echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config+ echo "world-file: $CABALHOME/world" >> $CABALHOME/config+ echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config+ echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config+ echo "installdir: $CABALHOME/bin" >> $CABALHOME/config+ echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config+ echo "store-dir: $CABALHOME/store" >> $CABALHOME/config+ echo "install-dirs user" >> $CABALHOME/config+ echo " prefix: $CABALHOME" >> $CABALHOME/config+ echo "repository hackage.haskell.org" >> $CABALHOME/config+ echo " url: http://hackage.haskell.org/" >> $CABALHOME/config+ - | if $GHCHEAD; then- sed -i 's/-- allow-newer: .*/allow-newer: *:base/' ${HOME}/.cabal/config- for pkg in $($HCPKG list --simple-output); do pkg=$(echo $pkg | sed 's/-[^-]*$//'); sed -i "s/allow-newer: /allow-newer: *:$pkg, /" ${HOME}/.cabal/config; done-- echo 'repository head.hackage' >> ${HOME}/.cabal/config- echo ' url: http://head.hackage.haskell.org/' >> ${HOME}/.cabal/config- echo ' secure: True' >> ${HOME}/.cabal/config- echo ' root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740' >> ${HOME}/.cabal/config- echo ' 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb' >> ${HOME}/.cabal/config- echo ' 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e' >> ${HOME}/.cabal/config- echo ' key-threshold: 3' >> ${HOME}/.cabal.config-- grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$'-- cabal new-update head.hackage -v+ echo "allow-newer: $($HCPKG list --simple-output | sed -E 's/([a-zA-Z-]+)-[0-9.]+/*:\1/g')" >> $CABALHOME/config+ + echo "repository head.hackage" >> $CABALHOME/config+ echo " url: http://head.hackage.haskell.org/" >> $CABALHOME/config+ echo " secure: True" >> $CABALHOME/config+ echo " root-keys: 07c59cb65787dedfaef5bd5f987ceb5f7e5ebf88b904bbd4c5cbdeb2ff71b740" >> $CABALHOME/config+ echo " 2e8555dde16ebd8df076f1a8ef13b8f14c66bad8eafefd7d9e37d0ed711821fb" >> $CABALHOME/config+ echo " 8f79fd2389ab2967354407ec852cbe73f2e8635793ac446d09461ffb99527f6e" >> $CABALHOME/config+ echo " key-threshold: 3" >> $CABALHOME/config fi- - grep -Ev -- '^\s*--' ${HOME}/.cabal/config | grep -Ev '^\s*$'- - "printf 'packages: \".\" \"./examples\"\\n' > cabal.project"- - touch cabal.project.local- - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi"+ - cat $CABALHOME/config+ - rm -fv cabal.project cabal.project.local cabal.project.freeze+ - travis_retry ${CABAL} v2-update -v+ # Generate cabal.project+ - rm -rf cabal.project cabal.project.local cabal.project.freeze+ - touch cabal.project+ - |+ echo 'packages: "."' >> cabal.project+ echo 'packages: "./examples"' >> cabal.project+ - |+ echo "write-ghc-environment-files: always" >> cabal.project+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(machines|machines-examples)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true- - if [ -f "./configure.ac" ]; then- (cd "." && autoreconf -i);- fi- - if [ -f "./examples/configure.ac" ]; then- (cd "./examples" && autoreconf -i);- fi- - rm -f cabal.project.freeze- - cabal new-build -w ${HC} ${TEST} ${BENCH} --project-file="cabal.project" --dep -j2 all- - rm -rf .ghc.environment.* "."/dist "./examples"/dist- - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)--# Here starts the actual work to be performed for the package under test;-# any command which exits with a non-zero exit code causes the build to fail.+ - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi+ - if [ -f "./examples/configure.ac" ]; then (cd "./examples" && autoreconf -i); fi+ - ${CABAL} v2-freeze -w ${HC} ${TEST} ${BENCH} | color_cabal_output+ - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"+ - rm cabal.project.freeze+ - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} --dep -j2 all | color_cabal_output script:- # test that source-distributions can be generated- - (cd "." && cabal sdist)- - (cd "./examples" && cabal sdist)- - mv "."/dist/machines-*.tar.gz "./examples"/dist/machines-examples-*.tar.gz ${DISTDIR}/+ - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)+ # Packaging...+ - ${CABAL} v2-sdist all | color_cabal_output+ # Unpacking...+ - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/ - cd ${DISTDIR} || false - find . -maxdepth 1 -name '*.tar.gz' -exec tar -xvf '{}' \;- - "printf 'packages: machines-*/*.cabal machines-examples-*/*.cabal\\n' > cabal.project"- - touch cabal.project.local- - "if ! $NOINSTALLEDCONSTRAINTS; then for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/^/constraints: /' | sed 's/-[^-]*$/ installed/' >> cabal.project.local; done; fi"+ # Generate cabal.project+ - rm -rf cabal.project cabal.project.local cabal.project.freeze+ - touch cabal.project+ - |+ echo 'packages: "machines-*/*.cabal"' >> cabal.project+ echo 'packages: "machines-examples-*/*.cabal"' >> cabal.project+ - |+ echo "write-ghc-environment-files: always" >> cabal.project+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | grep -vE -- '^(machines|machines-examples)$' | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done" - cat cabal.project || true - cat cabal.project.local || true-+ # Building with tests and benchmarks... # build & run tests, build benchmarks- - cabal new-build -w ${HC} ${TEST} ${BENCH} all- - if [ "x$TEST" = "x--enable-tests" ]; then cabal new-test -w ${HC} ${TEST} ${BENCH} all; fi-- # cabal check- - (cd machines-* && cabal check)- - (cd machines-examples-* && cabal check)-- # haddock- - rm -rf ./dist-newstyle- - if $HADDOCK; then cabal new-haddock -w ${HC} ${TEST} ${BENCH} all; else echo "Skipping haddock generation";fi+ - ${CABAL} v2-build -w ${HC} ${TEST} ${BENCH} all | color_cabal_output+ # Testing...+ - ${CABAL} v2-test -w ${HC} ${TEST} ${BENCH} all | color_cabal_output+ # cabal check...+ - (cd machines-* && ${CABAL} -vnormal check)+ - (cd machines-examples-* && ${CABAL} -vnormal check)+ # haddock...+ - ${CABAL} v2-haddock -w ${HC} ${TEST} ${BENCH} all | color_cabal_output -# REGENDATA ["-o",".travis.yml","--ghc-head","--irc-channel=irc.freenode.org#haskell-lens","--no-no-tests-no-bench","--no-unconstrained","cabal.project"]+# REGENDATA ["--output=.travis.yml","--config=cabal.haskell-ci","cabal.project"] # EOF
CHANGELOG.markdown view
@@ -1,3 +1,12 @@+0.7 [2019.05.10]+----------------+* Remove the `Monad` instances for `Mealy` and `MealyT`, as they were+ inconsistent with the `Applicative` instances.+* Add a `Data.Machine.Group.General` module.+* Add a `takingJusts` function to `Data.Machine.Process`.+* Add `Semigroup` and `Monoid` instances for `Moore`.+* Support building with `base-4.13` (GHC 8.8).+ 0.6.4 [2018.07.03] ------------------ * Add `Semigroup` and `Monoid` instances for `Mealy` and `MealyT`.
README.markdown view
@@ -23,7 +23,7 @@ A port of this design to scala is available from runarorama/scala-machines -Runar's slides are also available from https://dl.dropbox.com/u/4588997/Machines.pdf+Runar's slides are also available from http://web.archive.org/web/20161029161813/https://dl.dropboxusercontent.com/u/4588997/Machines.pdf Some worked examples are here https://github.com/alanz/machines-play
examples/Examples.hs view
@@ -9,7 +9,7 @@ import Control.Exception import Control.Monad.Trans import Data.Machine-import Data.Machine.Group+import Data.Machine.Group.General import System.IO -- this slurp slurps until an eof exception is raised.@@ -96,11 +96,11 @@ uniq :: Bool uniq = run (supply xs uniqMachine) == [1,2,3] where- -- | Unix's "uniq" command using groupingOn+ -- | Unix's "uniq" command using groupingOn_ -- (==) means "groups are contiguous values" -- final means "run the 'final' machine over each group" uniqMachine :: (Monad m, Eq a) => ProcessT m a a- uniqMachine = groupingOn (==) final+ uniqMachine = groupingOn_ (==) final xs :: [Int] xs = [1,2,2,3,3,3]
examples/machines-examples.cabal view
@@ -22,8 +22,9 @@ , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2- , GHC == 8.4.3- , GHC == 8.6.1+ , GHC == 8.4.4+ , GHC == 8.6.5+ , GHC == 8.8.1 source-repository head type: git@@ -32,7 +33,7 @@ library build-depends: base == 4.*,- machines == 0.6.*,+ machines == 0.7.*, mtl >= 2 && < 2.3 exposed-modules:
machines.cabal view
@@ -1,6 +1,6 @@ name: machines category: Control, Enumerator-version: 0.6.4+version: 0.7 license: BSD3 cabal-version: >= 1.10 license-file: LICENSE@@ -15,7 +15,7 @@ Networked stream transducers . Rúnar Bjarnason's talk on machines can be downloaded from:- <https://dl.dropbox.com/u/4588997/Machines.pdf>+ <http://web.archive.org/web/20161029161813/https://dl.dropboxusercontent.com/u/4588997/Machines.pdf> build-type: Custom tested-with: GHC == 7.4.2 , GHC == 7.6.3@@ -23,8 +23,9 @@ , GHC == 7.10.3 , GHC == 8.0.2 , GHC == 8.2.2- , GHC == 8.4.3- , GHC == 8.6.1+ , GHC == 8.4.4+ , GHC == 8.6.5+ , GHC == 8.8.1 extra-source-files: .travis.yml .gitignore@@ -80,6 +81,7 @@ Data.Machine.Type Data.Machine.Wye Data.Machine.Group+ Data.Machine.Group.General Data.Machine.Pipe default-language: Haskell2010@@ -94,7 +96,9 @@ -- See https://ghc.haskell.org/trac/ghc/wiki/Migration/8.0#base-4.9.0.0 if impl(ghc >= 8.0)- ghc-options: -Wcompat -Wnoncanonical-monad-instances -Wnoncanonical-monadfail-instances+ ghc-options: -Wcompat -Wnoncanonical-monad-instances+ if !impl(ghc >= 8.8)+ ghc-options: -Wnoncanonical-monadfail-instances else build-depends: fail == 4.9.*
src/Data/Machine/Group.hs view
@@ -7,13 +7,11 @@ , awaitUntil )where import Data.Machine--isLeft :: Either a b -> Bool-isLeft = either (const True) (const False)+import qualified Data.Machine.Group.General as Group -- | Using a function to signal group changes, apply a machine independently over each group. groupingOn :: Monad m => (a -> a -> Bool) -> ProcessT m a b -> ProcessT m a b-groupingOn f m = taggedBy f ~> partitioning m+groupingOn = Group.groupingOn_ -- | Mark a transition point between two groups as a function of adjacent elements. -- Examples@@ -21,39 +19,16 @@ -- >>> runT $ supply [1,2,2] (taggedBy (==)) -- [Right 1,Left (),Right 2,Right 2] taggedBy :: Monad m => (a -> a -> Bool) -> ProcessT m a (Either () a)-taggedBy f = construct $ await >>= go- where go x = do- yield (Right x)- y <- await- if not (f x y) then yield (Left ()) >> go y else go y+taggedBy = Group.taggedOn_ -- | Run a machine multiple times over partitions of the input stream specified by -- Left () values. partitioning :: Monad m => ProcessT m a b -> ProcessT m (Either () a) b-partitioning s = go s where- go m = MachineT $ runMachineT m >>= \v -> case v of- -- Machine stops (possibly before inputs)- Stop -> runMachineT $ awaitUntil isLeft (const $ go s)-- -- Machine yields a value- Yield o r -> return $ Yield o (go r)-- -- Machine waits for a value- Await f Refl r -> return $ Await g Refl (starve r $ encased Stop)- where- -- No change: unwrap input and give to underlying machine.- g (Right a) = go (f a)- -- New group: starve r, then wait for more input (restarting machine)- -- NOTE: if Left () happens with no more input, this will be wrong-ish(?)- -- Meaning of "Left ()" is "stop old machine and immediately start new one."- -- That means input [Right 1, Left ()] is different to [Right 1]- g (Left ()) = starve r $ go s-+partitioning = Group.partitioning_ -- | Read inputs until a condition is met, then behave as cont with -- | input matching condition as first input of cont. -- | If await fails, stop. awaitUntil :: Monad m => (a -> Bool) -> (a -> ProcessT m a b) -> ProcessT m a b-awaitUntil f cont = encased $ Await g Refl stopped- where g a = if f a then cont a else awaitUntil f cont+awaitUntil = Group.awaitUntil
+ src/Data/Machine/Group/General.hs view
@@ -0,0 +1,219 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE GADTs #-}++-- | Split up input streams into groups with separator values and process the+-- groups with their own 'MachineT'.++module Data.Machine.Group.General+ ( groupingOn+ , groupingOn_+ , groupingN+ -- * Tagging a stream+ , taggedState+ , taggedM+ , taggedOn+ , taggedOnM+ , taggedOn_+ , taggedAt+ , taggedAt_+ , taggedCount+ -- * Reset a machine for each group+ , partitioning+ , partitioning_+ -- * Helpers+ , starve+ , awaitUntil+ ) where++import Control.Monad (guard)+import Data.Machine++#if __GLASGOW_HASKELL__ < 710+-- $setup+-- >>> import Control.Monad.Trans.Reader (ask, runReader)+-- >>> import Control.Applicative ((<$))+#else+-- $setup+-- >>> import Control.Monad.Trans.Reader (ask, runReader)+#endif++-- A strict tuple type.+data Strict2 a b = Strict2 !a !b++isLeft :: Either a b -> Bool+isLeft = either (const True) (const False)++-- | Using a function to signal group changes, run a machine independently over+-- each group.+groupingOn_ :: Monad m => (a -> a -> Bool) -> ProcessT m a b -> ProcessT m a b+groupingOn_ f m = taggedOn_ f ~> partitioning_ m+{-# INLINE groupingOn_ #-}++-- | Using a function to signal group changes, run a machine independently over+-- each group with the value returned provided.+groupingOn :: Monad m => i -> (a -> a -> Maybe i) -> (i -> ProcessT m a b) -> ProcessT m a b+groupingOn i0 f m = taggedOn f ~> partitioning i0 m+{-# INLINE groupingOn #-}++-- | Run a machine repeatedly over 'n'-element segments of the stream, providing+-- an incrementing value to each run.+groupingN :: Monad m => Int -> (Int -> ProcessT m a b) -> ProcessT m a b+groupingN n m = taggedAt n 1 succ ~> partitioning 0 m+{-# INLINE groupingN #-}++-- | Mark a transition point between two groups when a state passing function+-- returns a 'Just' i.+-- Examples+--+-- >>> runT $ supply [1,3,3,2] (taggedState (-1) (\x y -> (even x <$ guard (x /= y), x)))+-- [Left False,Right 1,Left False,Right 3,Right 3,Left True,Right 2]+taggedState :: Monad m => s -> (a -> s -> (Maybe i, s)) -> ProcessT m a (Either i a)+taggedState s0 f = go s0+ where+ go s = encased+ $ Await (\x -> MachineT $ case f x s of+ (Nothing, s') -> return $+ Yield (Right x) (go s')+ (Just i, s') -> return $+ Yield (Left i) (encased (Yield (Right x) (s' `seq` go s'))))+ Refl+ stopped+{-# INLINE taggedState #-}++-- | Mark a transition point between two groups when an action returns a 'Just'+-- i. Could be useful for breaking up a stream based on time passed.+-- Examples+--+-- >>> let f x = do{ y <- ask; return (even x <$ guard (x > y)) }+-- >>> flip runReader 1 . runT $ supply [1,3,3,2] (taggedM f)+-- [Right 1,Left False,Right 3,Left False,Right 3,Left True,Right 2]+taggedM :: Monad m => (a -> m (Maybe i)) -> ProcessT m a (Either i a)+taggedM f = go+ where+ go = encased+ $ Await (\x -> MachineT $ f x >>= \v -> case v of+ Nothing -> return $+ Yield (Right x) go+ Just i -> return $+ Yield (Left i) (encased (Yield (Right x) go))+ )+ Refl+ stopped+{-# INLINE taggedM #-}++-- | Mark a transition point between two groups as a function of adjacent+-- elements, and insert the value returned as the separator.+-- Examples+--+-- >>> runT $ supply [1,3,3,2] (taggedOn (\x y -> (x < y) <$ guard (x /= y)))+-- [Right 1,Left True,Right 3,Right 3,Left False,Right 2]+taggedOn :: Monad m => (a -> a -> Maybe i) -> ProcessT m a (Either i a)+taggedOn f = encased+ $ Await (\x0 -> encased $ Yield (Right x0) (taggedState x0 (\y x -> (f x y, y))))+ Refl+ stopped+{-# INLINE taggedOn #-}++-- | Mark a transition point between two groups using an action on adjacent+-- elements, and insert the value returned as the separator.+-- Examples+--+-- >>> let f x y = do{ z <- ask; return ((x + y <$ guard (z < x + y))) }+-- >>> flip runReader 5 . runT $ supply [1..5] (taggedOnM f)+-- [Right 1,Right 2,Right 3,Left 7,Right 4,Left 9,Right 5]+taggedOnM :: Monad m => (a -> a -> m (Maybe i)) -> ProcessT m a (Either i a)+taggedOnM f = encased $ Await go Refl stopped+ where+ go x = encased+ $ Yield (Right x) $ encased+ $ Await (\y -> MachineT $ f x y >>= \v -> case v of+ Nothing -> runMachineT (go y)+ Just z -> return $ Yield (Left z) (go y))+ Refl+ stopped+{-# INLINE taggedOnM #-}++-- | Mark a transition point between two groups as a function of adjacent+-- elements.+-- Examples+--+-- >>> runT $ supply [1,2,2] (taggedOn_ (==))+-- [Right 1,Left (),Right 2,Right 2]+taggedOn_ :: Monad m => (a -> a -> Bool) -> ProcessT m a (Either () a)+taggedOn_ f = taggedOn (\x y -> guard (not (f x y)))+{-# INLINE taggedOn_ #-}++-- | Mark a transition point between two groups at every 'n' values, stepping+-- the separator by a function.+-- Examples+--+-- >>> runT $ supply [1..5] (taggedAt 2 True not)+-- [Right 1,Right 2,Left True,Right 3,Right 4,Left False,Right 5]+taggedAt :: Monad m => Int -> s -> (s -> s) -> ProcessT m a (Either s a)+taggedAt n s0 f = taggedState (Strict2 n s0) g+ where+ g _ (Strict2 i s) =+ if i <= 0 then (Just s, Strict2 (n-1) (f s))+ else (Nothing, Strict2 (i-1) s)+{-# INLINE taggedAt #-}++-- | Mark a transition point between two groups at every 'n' values.+-- Examples+--+-- >>> runT $ supply [1..5] (taggedAt_ 2)+-- [Right 1,Right 2,Left (),Right 3,Right 4,Left (),Right 5]+taggedAt_ :: Monad m => Int -> ProcessT m a (Either () a)+taggedAt_ n = taggedAt n () id+{-# INLINE taggedAt_ #-}++-- | Mark a transition point between two groups at every 'n' values, using the+-- counter as the separator.+-- Examples+--+-- >>> runT $ supply [1..5] (taggedCount 2)+-- [Right 1,Right 2,Left 1,Right 3,Right 4,Left 2,Right 5]+taggedCount :: Monad m => Int -> ProcessT m a (Either Int a)+taggedCount n = taggedAt n 1 succ+{-# INLINE taggedCount #-}++-- | Run a machine multiple times over partitions of the input stream specified+-- by 'Left' () values.+-- Examples+--+-- >>> let input = [Right 1,Left (),Right 3,Right 4,Left ()]+-- >>> runT $ supply input (partitioning_ (fold (flip (:)) []))+-- [[1],[4,3],[]]+partitioning_ :: Monad m => ProcessT m a b -> ProcessT m (Either () a) b+partitioning_ m = partitioning () (const m)+{-# INLINE partitioning_ #-}++-- | Run a machine multiple times over partitions of the input stream specified+-- by 'Left' i values, passing the 'i's to each 'MachineT' run.+-- Examples+--+-- >>> let input = [Right 1, Right 2,Left 1, Right 3,Left 2, Right 4]+-- >>> runT $ supply input (partitioning 0 (\x -> mapping (\y -> (x,y))))+-- [(0,1),(0,2),(1,3),(2,4)]+partitioning :: Monad m => i -> (i -> ProcessT m a b) -> ProcessT m (Either i a) b+partitioning i0 k0 = go (k0 i0) where+ go m = MachineT $ runMachineT m >>= \v -> case v of+ -- Machine stops (possibly before inputs)+ Stop -> runMachineT $ awaitUntil isLeft (const $ go (k0 i0))++ -- Machine yields a value+ Yield o r -> return $ Yield o (go r)++ -- Machine waits for a value+ Await f Refl r -> return $ Await g Refl (starve r $ encased Stop)+ where+ -- No change: unwrap input and give to underlying machine.+ g (Right a) = go (f a)+ -- New group: starve r, then wait for more input, restarting machine+ -- with next input.+ g (Left i) = starve r $ go (k0 i)++-- | Read inputs until a condition is met, then behave as cont with input+-- matching condition as first input of cont. If await fails, stop.+awaitUntil :: Monad m => (a -> Bool) -> (a -> ProcessT m a b) -> ProcessT m a b+awaitUntil f cont = encased $ Await g Refl stopped+ where g a = if f a then cont a else awaitUntil f cont
src/Data/Machine/Mealy.hs view
@@ -26,9 +26,6 @@ import Control.Applicative import Control.Arrow import Control.Category-import Control.Monad.Fix-import Control.Monad.Reader.Class-import Control.Monad.Zip import Data.Distributive import Data.Functor.Extend import Data.Functor.Rep as Functor@@ -93,16 +90,6 @@ (b, t) -> (b, go t) {-# INLINE unfoldMealy #-} --- | slow diagonalization-instance Monad (Mealy a) where- return = pure- {-# INLINE return #-}- m >>= f = Mealy $ \a -> case runMealy m a of- (b, m') -> (fst (runMealy (f b) a), m' >>= f)- {-# INLINE (>>=) #-}- (>>) = (*>)- {-# INLINE (>>) #-}- instance Profunctor Mealy where rmap = fmap {-# INLINE rmap #-}@@ -212,17 +199,6 @@ cotabulate f0 = Mealy $ \a -> go [a] f0 where go as f = (f (NonEmpty.fromList (Prelude.reverse as)), Mealy $ \b -> go (b:as) f) -instance MonadFix (Mealy a) where- mfix = mfixRep--instance MonadZip (Mealy a) where- mzipWith = mzipWithRep- munzip m = (fmap fst m, fmap snd m)--instance MonadReader (NonEmpty a) (Mealy a) where- ask = askRep- local = localRep- instance Closed Mealy where closed m = cotabulate $ \fs x -> cosieve m (fmap ($x) fs) @@ -231,4 +207,6 @@ instance Monoid b => Monoid (Mealy a b) where mempty = Mealy mempty+#if !(MIN_VERSION_base(4,11,0)) mappend f g = Mealy $ \x -> runMealy f x `mappend` runMealy g x+#endif
src/Data/Machine/MealyT.hs view
@@ -18,21 +18,20 @@ , upgrade , scanMealyT , scanMealyTM- , embedMealyT ) where import Data.Machine import Control.Arrow import Control.Applicative-import Data.Pointed import Control.Monad.Trans+import Data.Pointed import Control.Monad.Identity import Data.Profunctor import Data.Semigroup import qualified Control.Category as C import Prelude --- | 'Mealy' machine, with monadic effects+-- | 'Mealy' machine, with applicative effects newtype MealyT m a b = MealyT { runMealyT :: a -> m (b, MealyT m a b) } instance Functor m => Functor (MealyT m a) where@@ -49,22 +48,6 @@ pure b = r where r = MealyT (const (pure (b, r))) -- Stolen from Pointed MealyT m <*> MealyT n = MealyT $ \a -> (\(mb, mm) (nb, nm) -> (mb nb, mm <*> nm)) <$> m a <*> n a -instance Monad m => Monad (MealyT m a) where-#if !MIN_VERSION_base(4,8,0)- -- pre-AMP- {-# INLINE return #-}- return b = r where r = MealyT (const (return (b, r))) -- Stolen from Pointed-#endif-- MealyT g >>= f = MealyT $ \a ->- do (b, MealyT _h) <- g a- runMealyT (f b) a---- | Profunctor Example:------ >>> embedMealyT (dimap (+21) (+1) (arr (+1))) [1,2,3 :: Int]--- [24,25,26]--- instance Functor m => Profunctor (MealyT m) where rmap = fmap {-# INLINE rmap #-}@@ -98,13 +81,11 @@ arrM :: Functor m => (a -> m b) -> MealyT m a b arrM f = r where r = MealyT $ \a -> fmap (,r) (f a) -upgrade :: Monad m => Mealy a b -> MealyT m a b-upgrade (Mealy f) = MealyT $ \a ->- do let (r, g) = f a- return (r, upgrade g)+upgrade :: Applicative m => Mealy a b -> MealyT m a b+upgrade (Mealy f) = MealyT $ \a -> let (r, g) = f a in pure (r, upgrade g) -scanMealyT :: Monad m => (a -> b -> a) -> a -> MealyT m b a-scanMealyT f a = MealyT (\b -> return (a, scanMealyT f (f a b)))+scanMealyT :: Applicative m => (a -> b -> a) -> a -> MealyT m b a+scanMealyT f a = MealyT (\b -> pure (a, scanMealyT f (f a b))) scanMealyTM :: Functor m => (a -> b -> m a) -> a -> MealyT m b a scanMealyTM f a = MealyT $ \b -> (\x -> (a, scanMealyTM f x)) <$> f a b@@ -118,30 +99,13 @@ yield b go m --- | embedMealyT Example:------ >>> embedMealyT (arr (+1)) [1,2,3]--- [2,3,4]----embedMealyT :: Monad m => MealyT m a b -> [a] -> m [b]-embedMealyT _ [] = return []-embedMealyT sf (a:as) = do- (b, sf') <- runMealyT sf a- bs <- embedMealyT sf' as- return (b:bs)- instance AutomatonM MealyT where autoT = autoMealyTImpl -instance (Semigroup b, Monad m) => Semigroup (MealyT m a b) where- f <> g = MealyT $ \x -> do- (fx, f') <- runMealyT f x- (gx, g') <- runMealyT g x- return (fx <> gx, f' <> g')+instance (Semigroup b, Applicative m) => Semigroup (MealyT m a b) where+ f <> g = MealyT $ \x ->+ (\(fx, f') (gx, g') -> (fx <> gx, f' <> g')) <$> runMealyT f x <*> runMealyT g x -instance (Monoid b, Monad m) => Monoid (MealyT m a b) where- mempty = MealyT $ \_ -> return mempty- mappend f g = MealyT $ \x -> do- (fx, f') <- runMealyT f x- (gx, g') <- runMealyT g x- return (fx `mappend` gx, f' `mappend` g')+instance (Semigroup b, Monoid b, Applicative m) => Monoid (MealyT m a b) where+ mempty = MealyT $ \_ -> pure mempty+ mappend = (<>)
src/Data/Machine/Moore.hs view
@@ -34,7 +34,7 @@ import Data.Machine.Plan import Data.Machine.Type import Data.Machine.Process-import Data.Monoid+import Data.Semigroup import Data.Pointed import Data.Profunctor.Closed import Data.Profunctor@@ -48,7 +48,7 @@ -- | Accumulate the input as a sequence. logMoore :: Monoid m => Moore m m logMoore = h mempty where- h m = Moore m (\a -> h (m <> a))+ h m = Moore m (\a -> h (m `mappend` a)) {-# INLINE logMoore #-} -- | Construct a Moore machine from a state valuation and transition function@@ -155,3 +155,12 @@ instance Closed Moore where closed m = cotabulate $ \fs x -> cosieve m (fmap ($x) fs)++instance Semigroup b => Semigroup (Moore a b) where+ Moore x f <> Moore y g = Moore (x <> y) (f <> g)++instance Monoid b => Monoid (Moore a b) where+ mempty = Moore mempty mempty+#if !(MIN_VERSION_base(4,11,0))+ Moore x f `mappend` Moore y g = Moore (x `mappend` y) (f `mappend` g)+#endif
src/Data/Machine/Plan.hs view
@@ -118,7 +118,9 @@ {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-}+#if !(MIN_VERSION_base(4,13,0)) fail = Fail.fail+#endif instance Fail.MonadFail (PlanT k o m) where fail _ = PlanT (\_ _ _ kf -> kf)
src/Data/Machine/Process.hs view
@@ -35,6 +35,7 @@ , taking , droppingWhile , takingWhile+ , takingJusts , buffered , flattened , fold@@ -228,6 +229,29 @@ Refl stopped {-# INLINABLE takingWhile #-}++-- | A 'Process' that passes through elements unwrapped from 'Just' until a+-- 'Nothing' is found, then stops.+--+-- This can be constructed from a plan with+-- @+-- takingJusts :: Process (Maybe a) a+-- takingJusts = repeatedly $ await >>= maybe stop yield+-- @+--+-- Examples:+--+-- >>> run $ takingJusts <~ source [Just 1, Just 2, Nothing, Just 3, Just 4]+-- [1,2]+--+takingJusts :: Process (Maybe a) a+takingJusts = loop+ where+ loop = encased+ $ Await (maybe stopped (\x -> encased (Yield x loop)))+ Refl+ stopped+{-# INLINABLE takingJusts #-} -- | A 'Process' that drops elements while a predicate holds --