-
Notifications
You must be signed in to change notification settings - Fork 64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Idea for Monad instance of Concurrently compatible with the Applicative Instance #69
Comments
Why would someone want a Monad instance for |
@jml Well, for the getUrl example, we could have it fetch a list of urls from somewhere else. If the place its getting it from is slow, it would be able to start fetching the webpage of first url before it finishes getting the entire list. There are many other ways where having a |
The Monad instance is in fact compatible with the Applicative instance. In as >>= asb, it will run concurrently if asb is lazy (such as used by `ap`) and sequential when strict Close simonmar#69
The Monad instance is compatible with the Applicative instance. In as >>= asb, the actions will run concurrently if asb is lazy (in `ap` for instance), or sequentially if asb is strict. Close simonmar#69.
The obvious way to make Concurrently into a Monad doesn't work, since then Monad would be sequential, but Applicative would be concurrent (whereas Monad is usually supposed to be a generalization of Applicative). There is a way to make a Monad instance though that is as concurrent as possible (in particular,
ap
would be perfectly concurrent).The trick is the same one used for
fixIO
. Givenx :: Concurrently a
andf :: a -> Concurrently b
, we useunsafeInterleaveIO
to start a thread to putx
into a MVar (or TMVar or Async), and then useunsafeInterleaveIO
to read the value from the variable lazily. We can then startf
's action. Iff
needsx
's value to do anything, it will be sequential. On the other hand, iff
does not usex
's value at all (such as inap
), it will be perfectly concurrent. It can also be anywhere in between.I can do the code if you think this is a good concept. I just thought I'd check with you first to make sure its a good idea though.
The text was updated successfully, but these errors were encountered: