Module ‘chan-split’ released
17/07/2011Whaa?
chan-split is a haskell library that is a wrapper around Control.Concurrent.Chans that separates a Chan into a readable side and a writable side.
We also provide two other modules: Data.Cofunctor (because there didn’t seem to be one anywhere), and Control.Concurrent.Chan.Class. The latter creates two classes: ReadableChan and WritableChan, making the fundamental chan functions polymorphic, and defining an instance for standard Chan as well as MVar (an MVar is a singleton bounded channel, wanna fight about it?).
Why?
Having separate read/write sides makes it easier to reason about your code, supports doing some cool things (defining Functor and Cofunctor instances), and makes more sense (e.g. the function of dupChan in the base library is much easier to understand as an operation that happens on an OutChan).
Also I use it in (the coming new, less stupid version of) my module simple-actors.
Where?
You can get it with a:
cabal install chan-split
And check out the docs on hackage. Or check out the source on github and send me pull requests.
Usage
Let’s write the numbers 1 – 10 to the InChan and read them as a stream in the OutChan:
1 module Main
2 where
3
4 import Control.Concurrent.Chan.Split
5 import Control.Concurrent(forkIO)
6
7 main = do
8 -- Instead of a single Chan, we initialize a pair of (InChan,OutChan)
9 (inC,outC) <- newSplitChan
10 -- fork a writer on the InChan
11 forkIO $ writeStuffTo inC [1..10]
12 -- read from the OutChan in the main thread:
13 getStuffOutOf outC >>=
14 mapM_ print . take 10
And we’ll make writeStuffTo and getStuffOutOf, simply be the standard functions. Note that writeListToChan is actually polymorphic.
16 writeStuffTo :: InChan Int -> [Int] -> IO ()
17 writeStuffTo = writeList2Chan
18
19 getStuffOutOf :: OutChan Int -> IO [Int]
20 getStuffOutOf = getChanContents
Now I’ll demonstrate the use of our Functor and Cofunctor instances by re-defining those two functions above, after importing our Cofunctor class
17 import Data.Cofunctor
18
19 ...
20
21 -- we could convert the [Int] to [String] here but will instead demonstrate the
22 -- Cofmap instance:
23 writeStuffTo :: InChan String -> [Int] -> IO ()
24 writeStuffTo = writeList2Chan . cofmap show
25
26 -- likewise this demonstrates the Functor instance of OutChan:
27 getStuffOutOf :: OutChan String -> IO [Int]
28 getStuffOutOf = getChanContents . fmap read
All right, leave your love or hate and stay tuned for the new (less stupider) simple-actors lib.