[Haskell-cafe] async simplify code

Sjoerd Visscher sjoerd at w3future.com
Sun Jul 6 09:54:24 UTC 2014


You can use the Concurrently newtype wrapper for this, then you can use the Applicative and Alternative type classes.

dostuff :: Int -> Concurrently (String, Int)
dostuff n = Concurrently $ do 
  ..

let aborcd  =  (\x y -> [x, y]) <$> dostuff 6 <*> dostuff 12 
           <|> (\x y -> [x, y]) <$> dostuff 8 <*> dostuff 10
fromMaybe [] <$> timeout (1000000 * 20) (runConcurrently aborcd)

or even

let aborcd = traverse dostuff [6, 12] <|> traverse dostuff [8, 10]

Sjoerd

On 06 Jul 2014, at 06:17, Michael Snoyman <michael at snoyman.com> wrote:

> 
> 
> 
> On Sat, Jul 5, 2014 at 3:58 AM, grant weyburne <gbwey9 at gmail.com> wrote:
> Hi Cafe,
> 
> Is there any way to simplify this async code to somehow merge the withAsync code
> into the STM code? Looking at the code for tstABorCD it is not easy to see that
> it is really just (A&&B)||(C&&D). Here is the code:
>  
> http://lpaste.net/106945
> 
> Thanks for any pointers,
> Grant
> 
> 
> 
> The code as-is doesn't actually look too bad to me. But it *might* be a bit easier to read if instead of withAsync, waitSTM, and registerDelay, you used race, concurrently, and timeout. That might look something like this (untested):
> 
> let toList (x, y) = [x, y]
>     ab = toList <$> concurrently (doStuff 6) (doStuff 12)
>     cd = toList <$> concurrently (doStuff 8) (doStuff 10)
> res <- timeout (1000000 * 20) $ race ab cd
> return $ maybe [] (either id id) res
> 
> Michael
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list