packages feed

par-dual (empty) → 0.1.0.0

raw patch · 6 files changed

+760/−0 lines, 6 filesdep +asyncdep +basedep +hedgehogsetup-changed

Dependencies added: async, base, hedgehog, par-dual, refined, template-haskell, validators

Files

+ LICENSE view
@@ -0,0 +1,201 @@+                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++   1. Definitions.++      "License" shall mean the terms and conditions for use, reproduction,+      and distribution as defined by Sections 1 through 9 of this document.++      "Licensor" shall mean the copyright owner or entity authorized by+      the copyright owner that is granting the License.++      "Legal Entity" shall mean the union of the acting entity and all+      other entities that control, are controlled by, or are under common+      control with that entity. For the purposes of this definition,+      "control" means (i) the power, direct or indirect, to cause the+      direction or management of such entity, whether by contract or+      otherwise, or (ii) ownership of fifty percent (50%) or more of the+      outstanding shares, or (iii) beneficial ownership of such entity.++      "You" (or "Your") shall mean an individual or Legal Entity+      exercising permissions granted by this License.++      "Source" form shall mean the preferred form for making modifications,+      including but not limited to software source code, documentation+      source, and configuration files.++      "Object" form shall mean any form resulting from mechanical+      transformation or translation of a Source form, including but+      not limited to compiled object code, generated documentation,+      and conversions to other media types.++      "Work" shall mean the work of authorship, whether in Source or+      Object form, made available under the License, as indicated by a+      copyright notice that is included in or attached to the work+      (an example is provided in the Appendix below).++      "Derivative Works" shall mean any work, whether in Source or Object+      form, that is based on (or derived from) the Work and for which the+      editorial revisions, annotations, elaborations, or other modifications+      represent, as a whole, an original work of authorship. For the purposes+      of this License, Derivative Works shall not include works that remain+      separable from, or merely link (or bind by name) to the interfaces of,+      the Work and Derivative Works thereof.++      "Contribution" shall mean any work of authorship, including+      the original version of the Work and any modifications or additions+      to that Work or Derivative Works thereof, that is intentionally+      submitted to Licensor for inclusion in the Work by the copyright owner+      or by an individual or Legal Entity authorized to submit on behalf of+      the copyright owner. For the purposes of this definition, "submitted"+      means any form of electronic, verbal, or written communication sent+      to the Licensor or its representatives, including but not limited to+      communication on electronic mailing lists, source code control systems,+      and issue tracking systems that are managed by, or on behalf of, the+      Licensor for the purpose of discussing and improving the Work, but+      excluding communication that is conspicuously marked or otherwise+      designated in writing by the copyright owner as "Not a Contribution."++      "Contributor" shall mean Licensor and any individual or Legal Entity+      on behalf of whom a Contribution has been received by Licensor and+      subsequently incorporated within the Work.++   2. Grant of Copyright License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      copyright license to reproduce, prepare Derivative Works of,+      publicly display, publicly perform, sublicense, and distribute the+      Work and such Derivative Works in Source or Object form.++   3. Grant of Patent License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      (except as stated in this section) patent license to make, have made,+      use, offer to sell, sell, import, and otherwise transfer the Work,+      where such license applies only to those patent claims licensable+      by such Contributor that are necessarily infringed by their+      Contribution(s) alone or by combination of their Contribution(s)+      with the Work to which such Contribution(s) was submitted. If You+      institute patent litigation against any entity (including a+      cross-claim or counterclaim in a lawsuit) alleging that the Work+      or a Contribution incorporated within the Work constitutes direct+      or contributory patent infringement, then any patent licenses+      granted to You under this License for that Work shall terminate+      as of the date such litigation is filed.++   4. Redistribution. You may reproduce and distribute copies of the+      Work or Derivative Works thereof in any medium, with or without+      modifications, and in Source or Object form, provided that You+      meet the following conditions:++      (a) You must give any other recipients of the Work or+          Derivative Works a copy of this License; and++      (b) You must cause any modified files to carry prominent notices+          stating that You changed the files; and++      (c) You must retain, in the Source form of any Derivative Works+          that You distribute, all copyright, patent, trademark, and+          attribution notices from the Source form of the Work,+          excluding those notices that do not pertain to any part of+          the Derivative Works; and++      (d) If the Work includes a "NOTICE" text file as part of its+          distribution, then any Derivative Works that You distribute must+          include a readable copy of the attribution notices contained+          within such NOTICE file, excluding those notices that do not+          pertain to any part of the Derivative Works, in at least one+          of the following places: within a NOTICE text file distributed+          as part of the Derivative Works; within the Source form or+          documentation, if provided along with the Derivative Works; or,+          within a display generated by the Derivative Works, if and+          wherever such third-party notices normally appear. The contents+          of the NOTICE file are for informational purposes only and+          do not modify the License. You may add Your own attribution+          notices within Derivative Works that You distribute, alongside+          or as an addendum to the NOTICE text from the Work, provided+          that such additional attribution notices cannot be construed+          as modifying the License.++      You may add Your own copyright statement to Your modifications and+      may provide additional or different license terms and conditions+      for use, reproduction, or distribution of Your modifications, or+      for any such Derivative Works as a whole, provided Your use,+      reproduction, and distribution of the Work otherwise complies with+      the conditions stated in this License.++   5. Submission of Contributions. Unless You explicitly state otherwise,+      any Contribution intentionally submitted for inclusion in the Work+      by You to the Licensor shall be under the terms and conditions of+      this License, without any additional terms or conditions.+      Notwithstanding the above, nothing herein shall supersede or modify+      the terms of any separate license agreement you may have executed+      with Licensor regarding such Contributions.++   6. Trademarks. This License does not grant permission to use the trade+      names, trademarks, service marks, or product names of the Licensor,+      except as required for reasonable and customary use in describing the+      origin of the Work and reproducing the content of the NOTICE file.++   7. Disclaimer of Warranty. Unless required by applicable law or+      agreed to in writing, Licensor provides the Work (and each+      Contributor provides its Contributions) on an "AS IS" BASIS,+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+      implied, including, without limitation, any warranties or conditions+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+      PARTICULAR PURPOSE. You are solely responsible for determining the+      appropriateness of using or redistributing the Work and assume any+      risks associated with Your exercise of permissions under this License.++   8. Limitation of Liability. In no event and under no legal theory,+      whether in tort (including negligence), contract, or otherwise,+      unless required by applicable law (such as deliberate and grossly+      negligent acts) or agreed to in writing, shall any Contributor be+      liable to You for damages, including any direct, indirect, special,+      incidental, or consequential damages of any character arising as a+      result of this License or out of the use or inability to use the+      Work (including but not limited to damages for loss of goodwill,+      work stoppage, computer failure or malfunction, or any and all+      other commercial damages or losses), even if such Contributor+      has been advised of the possibility of such damages.++   9. Accepting Warranty or Additional Liability. While redistributing+      the Work or Derivative Works thereof, You may choose to offer,+      and charge a fee for, acceptance of support, warranty, indemnity,+      or other liability obligations and/or rights consistent with this+      License. However, in accepting such obligations, You may act only+      on Your own behalf and on Your sole responsibility, not on behalf+      of any other Contributor, and only if You agree to indemnify,+      defend, and hold each Contributor harmless for any liability+      incurred by, or claims asserted against, such Contributor by reason+      of your accepting any such warranty or additional liability.++   END OF TERMS AND CONDITIONS++   APPENDIX: How to apply the Apache License to your work.++      To apply the Apache License to your work, attach the following+      boilerplate notice, with the fields enclosed by brackets "[]"+      replaced with your own identifying information. (Don't include+      the brackets!)  The text should be enclosed in the appropriate+      comment syntax for the file format. We also recommend that a+      file or class name and description of purpose be included on the+      same "printed page" as the copyright notice for easier+      identification within third-party archives.++   Copyright [yyyy] [name of copyright owner]++   Licensed under the Apache License, Version 2.0 (the "License");+   you may not use this file except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS,+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+   See the License for the specific language governing permissions and+   limitations under the License.
+ README.md view
@@ -0,0 +1,209 @@+# par-dual++[![CI Status](https://github.com/gvolpe/par-dual/workflows/Haskell%20CI/badge.svg)](https://github.com/gvolpe/par-dual/actions)++The [PureScript](https://www.purescript.org/) language defines a [Parallel](https://pursuit.purescript.org/packages/purescript-parallel/4.0.0/docs/Control.Parallel.Class#t:Parallel) typeclass in the `parallel` package. Quoting its documentation:++> The `Parallel` class abstracts over monads which support parallel composition via some related `Applicative`.++The same typeclass is defined in the [Scala](https://www.scala-lang.org/) language, as part of the [Cats](https://typelevel.org/cats/typeclasses/parallel.html) library.++This typeclass has been controversial, in a sense, for not having strong laws. However, it has been proven to be actually useful in real-world applications.++The idea of this package is to bring this power over to the Haskell language while exploring the design space to identify and define stronger laws (if possible).++Originally, this idea has been described in [this blogpost](https://gvolpe.github.io/blog/parallel-typeclass-for-haskell/).++## ParDual++Here's the definition of the same typeclass in Haskell:++```haskell+class (Monad m, Applicative f) => ParDual f m | m -> f, f -> m where+  parallel :: forall a . m a -> f a+  sequential :: forall a . f a -> m a+```++I decided to call it `ParDual` instead of `Parallel`, because this *duality* doesn't always define a `sequential` and `parallel` relationship. Such is the case between `[]` and `ZipList`, as we will soon discover.++It defines two functions, which are natural transformations between a `Monad m` and an `Applicative f`. It could also be seen as a typeclass version of an isomorphism such as `forall a . Iso (f a) (m a)`.++The most common and useful relationships are both `Either` / `Validation` and `IO` / `Concurrently`.++```haskell+instance Semigroup e => ParDual (Validation e) (Either e) where+  parallel   = fromEither+  sequential = toEither++instance ParDual Concurrently IO where+  parallel   = Concurrently+  sequential = runConcurrently+```++`Validation` comes from the [validators](https://hackage.haskell.org/package/validators) package, whereas `Concurrently` comes from the [async](https://hackage.haskell.org/package/async) package.++Additionally, we can define a lot of powerful functions solely in terms of `Applicative`, `Monad`, and `ParDual`. A few other functions might require extra requirements, such as `Traversable`.++### parMapN++The `parMapN` set of functions are analogue to combining `<$>` and `<*>`, for any dual `Applicative`.++```haskell+parMap2+  :: (Applicative f, Monad m, ParDual f m)+  => m a0+  -> m a1+  -> (a0 -> a1 -> a)+  -> m a+```++In this case, `parMap2` takes only two computations and a function, but you can find other versions up to `parMap6`. If there is demand, we can consider abstracting over its arity, in order to compose an arbitrary number of computations.++For example, if we define a `Person` datatype with two fields:++```haskell+type Name = Refined NonEmpty String+type Age = Refined (GreaterThan 17) Int++data Person = Person+  { personAge :: Age+  , personName :: Name+  } deriving Show+```++We can then validate different inputs, while accumulating errors on the left side, even when our type is `Either [String] Person`.++```haskell+mkPerson :: Int -> String -> Either [String] Person+mkPerson a n = parMap2 (ref a) (ref n) Person+```++Where `ref` is a generic function that converts `RefineException`s to `[String]`:++```haskell+ref :: Predicate p x => x -> Either [String] (Refined p x)+ref x = left (\e -> [show e]) (refine x)+```++In case of two invalid inputs, we will get as a result a list of validation errors:++```haskell+mkPerson 10 "" == Left ["error 1", "error 2"]+```++If `parMapN` didn't exist, we could do the same by manually converting between `Either` and `Validation` (which is exactly what `parMapN` does via the `ParDual` class).++```haskell+mkPerson :: Int -> String -> Either [String] Person+mkPerson a n = toEither $ Person <$> fromEither (ref a) <*> fromEither (ref n)+```++Though, we can see how cumbersome and boilerplatey it gets.++### parTraverse++Another great application of the `ParDual` class is the definition of a `traverse` function that takes a `Monad` and a `Traversable t`, but that operates over its dual `Applicative`, and at the end it converts back to this `Monad`.++```haskell+parTraverse+  :: (Traversable t, Applicative f, Monad m, ParDual f m)+  => (a -> m b)+  -> t a+  -> m (t b)+```++The type signature is exactly the same as `traverse`, except the constraints are different.++We can appreciate its usability by looking at some examples. Here's one with `Either`:++```haskell+f :: Int -> Either [String] Int+f n = Left [show n]++traverse f [1..5] == Left ["1"]+parTraverse f [1..5] == Left ["1","2","3","4","5"]+```++Below there is another one with `IO`:++```haskell+randomDelay :: IO ()+randomDelay = do+  r <- randomRIO (1, 10)+  threadDelay (r * 500000)++traverseIO :: IO ()+traverseIO = traverse_ (\n -> randomDelay >> print n) [1 .. 10]++parTraverseIO :: IO ()+parTraverseIO = parTraverse_ (\n -> randomDelay >> print n) [1 .. 10]+```++The `traverse` version prints out numbers from 1 to 10 in sequence, while waiting for every random delay. So the output is pretty much `1 2 3 4 5 6 7 8 9 10`.++The `parTraverse` version has a non-deterministic output, since it goes through `Concurrently` (`IO`'s dual). It is exactly what you would expect while using [mapConcurrently](https://hackage.haskell.org/package/async-2.2.2/docs/Control-Concurrent-Async.html#v:mapConcurrently). One possible output is `5 10 6 1 3 2 9 4 7 8`.++### ZipList++The dual `Applicative` instance of `[]` is the one defined by `ZipList`, which doesn't have anything to do with parallelism.++```haskell+instance ParDual ZipList [] where+  parallel   = ZipList+  sequential = getZipList+```++Let's have a look at the examples shown below.++```haskell+((+) <$> [1..5] <*> [6..10]) == [7,8,9,10,11,8,9,10,11,12,9,10,11,12,13,10,11,12,13,14,11,12,13,14,15]++parMap2 [1..5] [6..10] (+) == [7,9,11,13,15]+```++The standard version iterates over both lists "sequentially". That is, it iterates over the first one, and then over the second one, returning the cartesian product of both lists.++Conversely, `ZipList`s only return the sum of the current elements of both lists such as `1 + 6`, `2 + 7`, and so on. It iterates over both lists in "parallel", effectively traversing both at once.++### parBitraverse++Operates over any `Bitraversable` such as `Either` or `(,,)`.++```haskell+res1 = [("ba",'2','T'),("ba",'2','r'),("ba",'2','u'),("ba",'2','e'),("ba",'4','T'),("ba",'4','r'),("ba",'4','u'),("ba",'4','e')]++(bitraverse show show ("ba", 24, True)) == res1+```++The standard `bitraverse` for `(String, Int, Bool)` traverses over the second value and then over the third value, combining the results on each iteration.++```haskell+(parBitraverse show show ("ba", 24, True)) == [("ba",'2','T'),("ba",'4','r')]+```++The dual variant traverses all the values at the same time, terminating as soon as either value is empty.++## Test suite++The test suite property-checks the functions defined in `ParDual` applied to different types of values.++```+$ nix-shell --run 'cabal new-run par-dual-tests'+━━━ Main ━━━+  ✓ prop_parMap2_on_success passed 100 tests.+  ✓ prop_parMap2_accumulates_errors passed 100 tests.+  ✓ prop_parTraverse_accumulates_errors passed 100 tests.+  ✓ prop_parTraverse_io_is_concurrent passed 10 tests.+  ✓ prop_parMap2_on_lists passed 100 tests.+  ✓ prop_parBitraverse passed 100 tests.+  ✓ 6 succeeded.+```++## Publishing++Generating documentation and tarball file to upload.++```+$ cabal new-haddock --haddock-for-hackage --enable-doc+$ cabal upload -d dist-newstyle/par-dual-0.1.0.0-docs.tar.gz+$ cabal new-sdist
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ par-dual.cabal view
@@ -0,0 +1,38 @@+cabal-version:       2.4++name:                par-dual+version:             0.1.0.0+synopsis:            ParDual class for Parallel <-> Sequential+description:         Defines a ParDual class for a Parallel <-> Sequential relationship+homepage:            https://github.com/gvolpe/par-dual+bug-reports:         https://github.com/gvolpe/par-dual/issues+license:             Apache-2.0+license-file:        LICENSE+category:            Library+author:              Gabriel Volpe+copyright:           2020 - Gabriel Volpe+maintainer:          volpegabriel@gmail.com+build-type:          Simple+extra-source-files:  README.md++library+  exposed-modules:     Control.ParDual.Class+  build-depends:       base                   >= 4.13.0 && < 4.14+                     , async                  >= 2.2.2 && < 2.3+                     , validators             >= 0.0.1 && < 0.1+  hs-source-dirs:      src+  default-language:    Haskell2010+  ghc-options:         -Wall++test-Suite par-dual-tests+  type:                exitcode-stdio-1.0+  main-is:             Main.hs+  hs-source-dirs:      test+  build-depends:       base+                     , hedgehog+                     , par-dual+                     , refined+                     , template-haskell+                     , validators+  default-language:    Haskell2010+  ghc-options:         -Wall -threaded -with-rtsopts -N
+ src/Control/ParDual/Class.hs view
@@ -0,0 +1,178 @@+{-# LANGUAGE FunctionalDependencies, RankNTypes, TypeOperators #-}++{-|+Module      : Control.ParDual.Class+Description : Definition of the 'ParDual' class and its functions.+Copyright   : (c) Gabriel Volpe, 2020+License     : Apache-2.0+Maintainer  : volpegabriel@gmail.com+Stability   : experimental++You can find here functions such as 'parMap2', 'parTraverse', 'parBitraverse', etc.+-}+module Control.ParDual.Class where++import           Control.Applicative            ( ZipList(..) )+import           Control.Concurrent.Async       ( Concurrently(..) )+import           Data.Bitraversable             ( Bitraversable+                                                , bitraverse+                                                )+import           Data.Functor                   ( void )+import           Data.Validation                ( Validation+                                                , toEither+                                                , fromEither+                                                )++{- | The ParDual class abstracts over 'Monad's that have a dual+'Applicative' instance that acts in a different useful way.++E.g., the duality between 'Either' and 'Validation'. As well+as the duality between 'IO' and 'Concurrently'.++It can also be seen as an isomorphism defined at the class level.+-}+class (Monad m, Applicative f) => ParDual f m | m -> f, f -> m where+  {- | A natural transformation from 'm' to 'f'+  -}+  parallel :: forall a . m a -> f a++  {- | A natural transformation from 'f' to 'm'+  -}+  sequential :: forall a . f a -> m a++  {- |+  It is the analogue to using '<$>' and '<*>' for the dual+  'Applicative' of the current 'Monad', as defined by the+  relationship defined by the 'ParDual' instance.+  -}+  parMap2 :: m a0 -> m a1 -> (a0 -> a1 -> a) -> m a+  parMap2 ma0 ma1 f = sequential $ f+    <$> parallel ma0+    <*> parallel ma1++  {- |+  It is the analogue to using '<$>' and '<*>' for the dual+  'Applicative' of the current 'Monad', as defined by the+  relationship defined by the 'ParDual' instance.+  -}+  parMap3 :: m a0 -> m a1 -> m a2 -> (a0 -> a1 -> a2 -> a) -> m a+  parMap3 ma0 ma1 ma2 f = sequential $ f+    <$> parallel ma0+    <*> parallel ma1+    <*> parallel ma2++  {- |+  It is the analogue to using '<$>' and '<*>' for the dual+  'Applicative' of the current 'Monad', as defined by the+  relationship defined by the 'ParDual' instance.+  -}+  parMap4 :: m a0 -> m a1 -> m a2 -> m a3 -> (a0 -> a1 -> a2 -> a3 -> a) -> m a+  parMap4 ma0 ma1 ma2 ma3 f = sequential $ f+    <$> parallel ma0+    <*> parallel ma1+    <*> parallel ma2+    <*> parallel ma3++  {- |+  It is the analogue to using '<$>' and '<*>' for the dual+  'Applicative' of the current 'Monad', as defined by the+  relationship defined by the 'ParDual' instance.+  -}+  parMap5 :: m a0 -> m a1 -> m a2 -> m a3 -> m a4 -> (a0 -> a1 -> a2 -> a3 -> a4 -> a) -> m a+  parMap5 ma0 ma1 ma2 ma3 ma4 f = sequential $ f+    <$> parallel ma0+    <*> parallel ma1+    <*> parallel ma2+    <*> parallel ma3+    <*> parallel ma4++  {- |+  It is the analogue to using '<$>' and '<*>' for the dual+  'Applicative' of the current 'Monad', as defined by the+  relationship defined by the 'ParDual' instance.+  -}+  parMap6 :: m a0 -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> (a0 -> a1 -> a2 -> a3 -> a4 -> a5 -> a) -> m a+  parMap6 ma0 ma1 ma2 ma3 ma4 ma5 f = sequential $ f+    <$> parallel ma0+    <*> parallel ma1+    <*> parallel ma2+    <*> parallel ma3+    <*> parallel ma4+    <*> parallel ma5++  {- |+  Same as 'traverse', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parTraverse :: Traversable t => (a -> m b) -> t a -> m (t b)+  parTraverse f ta =+    let g a = parallel (f a)+        res = sequenceA $ fmap g ta+    in  sequential res++  {- |+  Same as 'Data.Foldable.traverse_', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parTraverse_ :: Traversable t => (a -> m b) -> t a -> m ()+  parTraverse_ f = void . parTraverse f++  {- |+  Same as 'sequence', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parSequence :: Traversable t => t (m a) -> m (t a)+  parSequence = parTraverse id++  {- |+  Same as 'sequence_', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parSequence_ :: Traversable t => t (m a) -> m ()+  parSequence_ = void . parSequence++  {- |+  Same as '*>', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parProductR :: m a -> m b -> m b+  parProductR ma mb = parMap2 ma mb (\_ b -> b)++  {- |+  Same as '<*', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parProductL :: m a -> m b -> m a+  parProductL ma mb = parMap2 ma mb const++  {- |+  Same as 'bitraverse', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parBitraverse :: Bitraversable t => (a -> m c) -> (b -> m d) -> t a b -> m (t c d)+  parBitraverse ma mb tab =+    let fa  = (\a -> parallel (ma a))+        fb  = (\b -> parallel (mb b))+        res = bitraverse fa fb tab+    in  sequential res++  {- |+  Same as 'Data.Traversable.bisequence', except it uses the dual 'Applicative' of+  the current 'Monad', as defined by the 'ParDual' relationship.+  -}+  parBisequence :: Bitraversable t => t (m a) (m b) -> m (t a b)+  parBisequence = parBitraverse id id++--------------------- Instances ----------------------------++instance Semigroup e => ParDual (Validation e) (Either e) where+  parallel   = fromEither+  sequential = toEither++instance ParDual Concurrently IO where+  parallel   = Concurrently+  sequential = runConcurrently++instance ParDual ZipList [] where+  parallel   = ZipList+  sequential = getZipList
+ test/Main.hs view
@@ -0,0 +1,132 @@+{-# LANGUAGE DataKinds, OverloadedStrings, TemplateHaskell #-}++module Main where++import           Control.Arrow                  ( left )+import           Control.Concurrent             ( threadDelay )+import           Control.ParDual.Class+import           Control.Monad                  ( unless )+import           Data.Bitraversable             ( bitraverse )+import           Data.Foldable                  ( traverse_ )+import           Data.IORef+import           Data.Validation                ( fromEither+                                                , toEither+                                                )+import           Hedgehog+import qualified Hedgehog.Gen                  as Gen+import qualified Hedgehog.Range                as Range+import           Refined+import           System.Exit                    ( exitFailure )++main :: IO ()+main = do+  results <- sequence [checkParallel dualTests]+  unless (and results) exitFailure++dualTests :: Group+dualTests = $$(discover)++prop_parMap2_on_success :: Property+prop_parMap2_on_success = property $ do+  a <- forAll $ Gen.int (Range.linear 18 100)+  n <- forAll $ Gen.list (Range.linear 1 50) Gen.alpha+  let result   = parMap2 (ref a) (ref n) Person+      expected = Person <$> ref a <*> ref n+  result === expected++prop_parMap2_accumulates_errors :: Property+prop_parMap2_accumulates_errors = property $ do+  a <- forAll $ Gen.int (Range.linear 0 17)+  n <- forAll $ Gen.list (Range.linear 0 0) Gen.alpha+  let+    res1 = parMap2 (ref a) (ref n) Person+    res2 = Person <$> ref a <*> ref n+    exp1 = Left+      [ "The predicate (GreaterThan 17) does not hold: \n  Value is not greater than 17"+      , "The predicate (SizeGreaterThan 0) does not hold: \n  Size of Foldable is not greater than 0\n  Size is: 0"+      ]+    exp2 = left (take 1) exp1+  res1 === exp1+  res2 === exp2++prop_parTraverse_accumulates_errors :: Property+prop_parTraverse_accumulates_errors = property $ do+  xs <- forAll $ Gen.list (Range.linear 1 10) (Gen.int (Range.linear 1 10))+  let f :: Int -> Either [String] Int+      f n = Left [show n]+      res1 = parTraverse f xs+      res2 = traverse f xs+      exp1 = Left (show <$> xs)+      exp2 = Left (take 1 $ show <$> xs)+  res1 === exp1+  res2 === exp2++-- This one is tricky to test but this seems good enough for now+prop_parTraverse_io_is_concurrent :: Property+prop_parTraverse_io_is_concurrent = withTests (10 :: TestLimit) $ property $ do+  xs <- forAll $ Gen.list (Range.linear 15 25) (Gen.int (Range.linear 1 10))+  let f r n = threadDelay (1 * 3000) >> atomicModifyIORef r (\x -> (n : x, n))+  ref1 <- evalIO $ newIORef [] :: PropertyT IO (IORef [Int])+  ref2 <- evalIO $ newIORef [] :: PropertyT IO (IORef [Int])+  evalIO $ parTraverse_ (f ref1) xs+  evalIO $ traverse_ (f ref2) xs+  res1 <- evalIO $ readIORef ref1+  res2 <- evalIO $ readIORef ref2+  -- Avoid cases where all elements are the same (could prob. be done in a better way)+  let exp1 = if and (fmap (== head xs) (tail xs)) then [] else reverse xs+  res1 /== exp1+  res2 === reverse xs++prop_parMap2_on_lists :: Property+prop_parMap2_on_lists = property $ do+  xs <- forAll $ Gen.constant [1 .. 5] :: PropertyT IO [Int]+  ys <- forAll $ Gen.constant [6 .. 10] :: PropertyT IO [Int]+  let res1 = parMap2 xs ys (+)+      res2 = (+) <$> xs <*> ys+      exp1 = [7, 9, 11, 13, 15]+      exp2 = [7 .. 11] ++ [8 .. 12] ++ [9 .. 13] ++ [10 .. 14] ++ [11 .. 15]+  res1 === exp1+  res2 === exp2++prop_parBitraverse :: Property+prop_parBitraverse = property $ do+  a <- forAll $ Gen.list (Range.linear 5 10) Gen.alpha+  b <- forAll $ Gen.int (Range.linear 5 10)+  c <- forAll Gen.bool+  let res1 = parBitraverse show show (a, b, c)+      res2 = bitraverse show show (a, b, c)+  length res1 === min (length $ show b) (length $ show c)+  length res2 === length (show b) * length (show c)++-------------- Datatypes -------------------------++type Name = Refined NonEmpty String+type Age = Refined (GreaterThan 17) Int++data Person = Person+  { personAge :: Age+  , personName :: Name+  } deriving (Eq, Show)++-------------- Sequential Validation -------------++mkPersonSeq :: Int -> String -> Either RefineException Person+mkPersonSeq a n = do+  age  <- refine a+  name <- refine n+  return $ Person age name++-------------- Parallel Validation (manually) -------------------++type Eff a = Either [String] a++ref :: Predicate p x => x -> Eff (Refined p x)+ref x = left (\e -> [show e]) (refine x)++mkPerson :: Int -> String -> Eff Person+mkPerson a n = toEither $ Person <$> fromEither (ref a) <*> fromEither (ref n)++-------------- Parallel Validation -------------++makePerson :: Int -> String -> Eff Person+makePerson a n = parMap2 (ref a) (ref n) Person