Skip to content
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

Open
ChristopherKing42 opened this issue Nov 27, 2017 · 2 comments

Comments

@ChristopherKing42
Copy link

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. Given x :: Concurrently a and f :: a -> Concurrently b, we use unsafeInterleaveIO to start a thread to put x into a MVar (or TMVar or Async), and then use unsafeInterleaveIO to read the value from the variable lazily. We can then start f's action. If f needs x's value to do anything, it will be sequential. On the other hand, if f does not use x's value at all (such as in ap), 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.

@jml
Copy link

jml commented Dec 6, 2017

Why would someone want a Monad instance for Concurrently? Can you give an example of how it might be used?

@ChristopherKing42
Copy link
Author

@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 Monad instance is just convenient, even if it isn't necessarily concurrent. We could also give Concurrently a MonadIO and MonadFix instance.

ChristopherKing42 added a commit to ChristopherKing42/async that referenced this issue Dec 12, 2017
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
ChristopherKing42 added a commit to ChristopherKing42/async that referenced this issue Dec 12, 2017
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants