[Haskell-cafe] readEitherChan

Tomasz Zielonka t.zielonka at students.mimuw.edu.pl
Wed Jun 16 03:17:09 EDT 2004

On Tue, Jun 15, 2004 at 06:29:59PM -0400, S. Alexander Jacobson wrote:
> 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
> implementation:
>   readEitherChan::Chan a -> Chan b -> Either a b
>   readEitherChan a b =
> 	do
> 	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
> operation.

You can also loose some elements from both channels. I think it would be
safer to create once new Chan (Either a b), and then read from it.

    createEitherChan :: Chan a -> Chan b -> IO (Chan (Either a b))
    createEitherChan a b = do
	ab <- newChan
	forkIO (sequence_ (repeat (readChan a >>= writeChan ab . Left)))
	forkIO (sequence_ (repeat (readChan b >>= writeChan ab . Right)))
	return ab

Best regards,

.signature: Too many levels of symbolic links

More information about the Haskell-Cafe mailing list