[Haskell-cafe] readEitherChan

S. Alexander Jacobson alex at i2x.com
Tue Jun 15 18:29:59 EDT 2004

I'd like a function that blocks until data is
available on one of two channels and then returns
that data wrapped in an Either.  Here is my naive

  readEitherChan::Chan a -> Chan b -> Either a b
  readEitherChan a b =
	var <- newEmptyMVar
	forkIO (readChan a >>= putMVar var . Left)
	forkIO (readChan b >>= putMVar var . Right)
	val <- readMVar
	return val

  eitherChan a b left right = readEitherChan a b >>= either left right

But creating an MVar and starting two threads
feels like a lot of overhead for a simple

Is there a better way or is forkIO so efficient
that I shouldn't care?

S. Alexander Jacobson                  mailto:me at alexjacobson.com
tel:917-770-6565                       http://alexjacobson.com

More information about the Haskell-Cafe mailing list