3 ms·
Awesome, a C++ implementation of the Future monad. Personally I would prefer .flatMap to .then, as in Scala. That would also allow for a companion function .map
by pkinsky 13y ago
Awesome, a C++ implementation of the Future monad. Personally I would prefer .flatMap to .then, as in Scala. That would also allow for a companion function .map that transforms the result of a Future using a function that does not return a promise.
ie: (in Scala, my C++-fu is weak)
getTweetsFor("domenic") // returns a future
.map(parseTweetsForUrls)
.map(_.head)
.flatMap(expandUrlUsingTwitterApi)
.flatMap(httpGet)
- kentonv 13y agoHeh, yeah, I only realized yesterday, I think, that promises are monads. then() will actually accept functions returning regular values, too. A big difference between then() and map() is that then() accepts an optional second parameter for exception handling. In any case, I used "then" because that's what Javascript promises use.
- frowaway001 13y agoJavaScript promises are wrong and broken. See the huge spec of the Promises/A+ vs. the few lines of specification for a correct one.
- kentonv 13y agoAre they broken in a way that I have copied? I don't actually know too much about the details, I just copied the `then()` call.
- infinite8s 13y agoI haven't looked at your implementation, so I'm basing this on the statement "then() will actually accept functions returning regular values, too" in your grandparent comment. Because of this you don't have a true Monad (as in your Promise implementation doesn't satisfy the third monad law). One easy way to think of Monads is that they are like black holes - you are free to put something into it but can't ever pull it back out. Instead, all you are allowed to do is chain them together (with bind). So to transform the value inside a monad, you must write a function that takes that value and returns the transformed value wrapped in the same type of monad (Promise in this case). The monadic machinery in 'bind' will take care of pushing the result from one Promise into the transform function.
- dwrensha 13y agoI don't think there's a problem here. We get two functions with a monad m: bind :: m a -> (a -> m b) -> m b return :: a -> m a These allow us to define then :: m a -> (a -> b) -> m b then x f = bind x (return . f) i.e. it's trivial to lift a regular function into the monad.
- kentonv 13y agoWhat dwrensha said, although I'd describe it like this: Allowing then() to take a function which returns a bare value rather than a promise is just syntax sugar. You can always wrap a bare value in a promise by creating an immediate (already-fulfilled) promise. Giving then() such a function -- that wraps its result in a promise -- is equivalent in behavior to giving then() a function that just returns a bare value, except that the latter is somewhat more efficient in implementation.