From 34a038b95a55d4eeede068c19c02eacdd60cfcda Mon Sep 17 00:00:00 2001 From: Irakli Safareli Date: Thu, 5 Apr 2018 22:19:03 -0400 Subject: [PATCH] add Lazy instance for Aff (#142) * add Lazy instance for Aff * change Lazy tests so result is returned from fix * move test_lazy after kill and avar tests --- src/Control/Monad/Aff.purs | 4 ++++ test/Test/Main.purs | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/Control/Monad/Aff.purs b/src/Control/Monad/Aff.purs index 125a679..f6a8d06 100644 --- a/src/Control/Monad/Aff.purs +++ b/src/Control/Monad/Aff.purs @@ -36,6 +36,7 @@ import Prelude import Control.Alt (class Alt) import Control.Alternative (class Alternative) import Control.Apply (lift2) +import Control.Lazy (class Lazy) import Control.Monad.Eff (Eff, kind Effect) import Control.Monad.Eff.Class (class MonadEff, liftEff) import Control.Monad.Eff.Exception (Error, EXCEPTION, error) @@ -110,6 +111,9 @@ instance monadErrorAff ∷ MonadError Error (Aff eff) where instance monadEffAff ∷ MonadEff eff (Aff eff) where liftEff = _liftEff +instance lazyAff ∷ Lazy (Aff eff a) where + defer f = pure unit >>= f + -- | Applicative for running parallel effects. Any `Aff` can be coerced to a -- | `ParAff` and back using the `Parallel` class. foreign import data ParAff ∷ # Effect → Type → Type diff --git a/test/Test/Main.purs b/test/Test/Main.purs index 15d011c..81583cd 100644 --- a/test/Test/Main.purs +++ b/test/Test/Main.purs @@ -3,6 +3,7 @@ module Test.Main where import Prelude import Control.Alt ((<|>)) +import Control.Lazy (fix) import Control.Monad.Aff (Aff, Canceler(..), runAff_, launchAff, makeAff, try, bracket, generalBracket, delay, forkAff, suspendAff, joinFiber, killFiber, never, supervise, Error, error, message) import Control.Monad.Aff.AVar (AVAR, makeEmptyVar, takeVar, putVar) import Control.Monad.Aff.Compat as AC @@ -632,6 +633,26 @@ test_scheduler_size = assert "scheduler" do _ ← traverse joinFiber =<< traverse forkAff (Array.replicate 100000 (modifyRef ref (add 1))) eq 100000 <$> readRef ref +test_lazy ∷ ∀ eff. TestAff eff Unit +test_lazy = assert "Lazy Aff" do + varA ← makeEmptyVar + varB ← makeEmptyVar + fiberA <- forkAff $ fix \loop -> do + a <- takeVar varA + putVar (a + 1) varB + loop + fiberB <- forkAff $ fix \loop -> do + b <- takeVar varB + if (b > 100) + then do + killFiber (error "finished") fiberA + pure "done" + else do + putVar (b + 1) varA + loop + putVar 0 varA + eq "done" <$> joinFiber fiberB + main ∷ TestEff () Unit main = do test_pure @@ -670,6 +691,7 @@ main = do test_kill_parallel_alt test_kill_parallel_alt_finalizer test_avar_order + test_lazy test_efffn test_fiber_map test_fiber_apply