promises-aplus / constructor-spec

Discussion and drafts of a possible spec for creating and resolving promises
10 stars 4 forks source link

point function #24

Closed Raynos closed 11 years ago

Raynos commented 11 years ago

@pufuwozu brought up a good point with his article

http://brianmckenna.org/blog/category_theory_promisesaplus

The notion of having a point function that takes a value and returns a promise would allow for writing powerful higher order functions.

Basically prior art, a-la category theory shows that having a function that looks like point is a good thing, we should consider this.

puffnfresh commented 11 years ago

@ForbesLindesay promises are monadic in lots of implementations for lots of languages. Monadic implementations must satisfy those laws or things are broken. Saying that promises are not monadic only applies to this specification - not to promises themselves.

I'm arguing that the promises specification is very close to being a monad and thus would have to obey those rules. Your argument against making it a monad is what? That it's useful to not be a monad?

It's much more useful to be monad - breaking the law for an arbitrary reason is not useful.

robotlolita commented 11 years ago

As it stands, the current semantics are easy to reason about and useful in real world programs.

Having implemented a Promises/A+ compliant library, and used it in real-world scenarios, I think I can provide my own experience on this: not true. You can't reason about what:

map(makeDirectory, lines(readFile('foo.txt')))

Will do without knowing how each of those functions handle the values passed to them wrt promises. It looks obvious what the code should accomplish, but it's not obvious what it, in fact, accomplishes. The problem gets worse if readFile or lines don't return a proper Promises/A+, or if you add even more functions to the mix.

puffnfresh commented 11 years ago

@ForbesLindesay in sane promise libraries it is mathematical. That's what I want.

Why don't you want that?

ForbesLindesay commented 11 years ago

They are mathematical, in the sense that everything is, but so are ours. You're saying Promises/A+ are wrong because they're not mathematical, monads are correct because they are mathematical. That argument simply doesn't hold water unless you have a definition of mathematical that's very different to the standard, accepted definition.

ForbesLindesay commented 11 years ago

Nobody has mathematically proved monads are the best way of doing things. Or, by extension, that promises are worse than monads as a way of doing things. So far you haven't provided a single example in which monads would be superior to promises.

puffnfresh commented 11 years ago

@ForbesLindesay being a monad means I can abstract over them. Like I said before, I do this all the time at work. It's extremely useful. I also have functions that work on promises and work on other things.

It's great.

Why should we not allow that?

robotlolita commented 11 years ago

@ForbesLindesay the only argument I see @pufuwozu is that Promises in this specification are close to being a Monad. Being a Monad is useful because you get lots of abstraction for free (the same way being a Functor is useful).

Edit: For example. You can write one library that deals just with Arrays, one that deals just with Vectors, one that deals just with Lists, one that deals just with Sets. And reimplement the same operations for all of them over and over again. Or you can write operations that are based on the fact that all of these share some similarities, so your operations should work neatly with all of them (and all other types to be). I fail to see how this isn't a compelling reason.

puffnfresh commented 11 years ago

They're close to being a monad. Being a monad would allow me to abstract over them and write lots of useful functions that also work for other structures.

Why do we not want to allow that?

ForbesLindesay commented 11 years ago

No, you have functions that work on promises, and work identity objects. And since a promise is a superset of an identity object, just use a promise to represent your identity object.

You get just as much useful abstraction from being a promise as you get from being a monad.

@killdream we've demonstrated time and time again that they are not close enough to being a monad to make the transition easy (possible?) without breaking existing code.

copumpkin commented 11 years ago

Take replicateM, sequence (fine, that works with Applicative, but the point still stands), or filterM. I can envision use cases for those on promises, and they all involve "nested promises".

Why not keep the funky existing behavior on then and make new methods that satisfy the laws? Existing code won't break, and people who want to use generic monad operations get to use them anyway.

ForbesLindesay commented 11 years ago

If you wish to continue to be taken seriously I'd suggest you stop writing "allow me to abstract over them" and start writing "allow me to abstract over them differently". You can abstract over promises. You can represent an option as a promise, you can represent a future as a promise, you can represent an identity as a promise.

copumpkin commented 11 years ago

He's talking about abstracting over monads, not promises. The operations I listed in my previous comment work over values of any monad, and make perfect sense to use on promises too.

Peaker commented 11 years ago

@ForbesLindesay No, the abstract functions @pufuwozu is talking about aren't just for promises and identity objects. They are also for lists, option types, parsers, exceptions, probability distributions, etc.

If you do what @pufuwozu is requesting, then he could use a nice API in the same way with promises as he does with his probability distribution code, or his parsers. If you reject it, you gain nothing -- but you lose this, meaning that you're going to have to duplicate all of your code for each of the above cases.

puffnfresh commented 11 years ago

@ForbesLindesay no, a promise is not a superset of an identity object.

Can I abstract over state as a promise? Can I abstract over reader as a promise? Can I abstract over writer as a promise? Can I abstract over IO as a promise?

Promises lack the laws necessary to allow the above. The laws are important - we can't use promise as a better monad. It's less general.

ForbesLindesay commented 11 years ago

@copumpkin

I don't know the functionality of the methods you list, and they have far from self-explanatory names.

The reason for not just creating a new method, is that avoiding the creation of promises for promises is widely seen as a useful goal, so we may not want to allow any method for doing so. You still need to demonstrate that doing so is necessary.

I know he was speaking about monads. The point is he was comparing monads to promises. I can abstract over promises, so his assertion should just be that he can abstract differently over monads.

puffnfresh commented 11 years ago

@ForbesLindesay monads are more general than promises. Does that answer your question?

puffnfresh commented 11 years ago

@ForbesLindesay self-explanatory names aren't going to be easy when we're dealing with abstract algebra, right? :smile:

copumpkin commented 11 years ago

@ForbesLindesay then take two minutes to look up what they do! The goal here is to improve the spec, and it's not like @pufuwozu is intentionally trolling you because he wants you to fail. If a dozen people seem to think there's something worth noting here, don't you think the obvious reaction of someone who wants to improve their spec should be to go learn about that thing, rather than to set up fortifications and stand their ground? @pufuwozu clearly cares enough to keep trying to drive the point home, but it isn't his responsibility to teach you. If your goal is genuinely to get the best spec, just go read about what we're talking about. You might find it's a load of bullshit, which is fine (I don't think it's bullshit, obviously), but give it an honest try and then come back and ask questions rather than making assertions or demanding that we prove to you that our points are worth your consideration before you take any sort of initiative to take them seriously.

The goal here isn't to win the argument.

Edit: I dare you to implement the list monad, the continuation monad, a probability density monad, the search monad, or parser combinators as promises.

ForbesLindesay commented 11 years ago

Here's my ID implementation that's a promise:

function ID(value) {
  return new Promise(function (resolve) { resolve(value); });
}

and here's an option type:

function Option(hasValue, value) {
  return new Promise(function (resolve, reject) { if (hasValue) { resolve(value) } else { reject() });
}

I can now write functions which abstract over Promises, and they will work fine abstracting over IDs and Options too.

ForbesLindesay commented 11 years ago

I continue to wait for an example that demonstrates the advantage.

ghost commented 11 years ago

@ForbesLindesay One reason that you aren't getting examples is exactly as @copumpkin explained; these examples are well-rehearsed elsewhere (yes, including other Promise implementations) and we aren't going to do your homework for you. If you want to claim authority over this JavaScript spec, fine, but if you want to be taken seriously, it behooves you to gain a little more education rather than stomping your feet like a petulant child and insisting that it's your way or the highway.

Hint: the fact that there's existing code with bad abstractions over which you can write N more bad abstractions one by one isn't a counterexample.

ForbesLindesay commented 11 years ago

No, my goal isn't to win an argument, it's to get a spec that's best for the future of software writing in JavaScript.

If I were attempting to persuade the makers of the HTML specification that we needed a new smell tag, that browsers would implement by generating gasses with the appropriate scent (when hardware support was available), it would be up to me to prove to them that it was worthwhile. Not up to them to learn about the uses of smells on the internet and in flash applications.

If I wanted to add a blink tag to GitHub flavoured markdown, it would be up to me to persuade GitHub that lots of people wanted to display blinking text in their issues and readmes. Not up to them to go looking for people who wanted that feature.

You want to add a feature, and thus complexity, to a well established spec, that's in use widely across the web, both client and server. As such, it's up to you to demonstrate that your feature adds enough value to be worth the added complexity. Not up to me to try and prove it adds value. I'm happy with what we already have. I'm not attempting to prove anything and I'd be really happy if you showed me something awesome I'm not yet aware of that we could do if only promises were monads. I'd then implement them in promise, rejoice at the new functionality I got then, after using it in a project, come back here and tell everyone how wonderful it was so that we could put it in the spec and implement it in other promise libraries.

joneshf commented 11 years ago

@ForbesLindesay I'm not sure if you got a decent example of a nested monad (and to be honest, I started skimming the last 20 or so messages), but there's always trees.

Peaker commented 11 years ago

@ForbesLindesay When you implement the Identity Monad and Option Monads with Promise result and Promise return, you actually implemented CPS'd Identity and Option. Identity/Option should lend themselves to case analysis, without needing to block on a promise.

Also, these are 2 monads that you can approximate with Promises. How do you implement the State/Reader/Writer monads? Or the List monad? Or the continuation monad?

copumpkin commented 11 years ago

Oh, I'd misunderstood the purpose of this exercise, then. I thought the goal was to get a better spec, not just to describe what was already in place. I also thought the overarching goal for developers/computer scientists in general was to learn new things, so the passive "prove to me that this is worth my time" (when there are literally hundreds of articles all over the internet about this) is a little surprising. It's not a smell tag and it's not a blink tag. It's basic mathematics that underpins/describes a lot of what happens in your day-to-day experience, whether you realize it or not.

I'm just disappointed by your lack of curiosity as an engineer more than anything. Don't tell me that the function names aren't descriptive; JFGI. In fact, that pretty much applies to this entire conversation, since our side of the conversation is pretty much standardized across the internet.

ForbesLindesay commented 11 years ago

@joneshf no, I never did. Trees seem like a nice obvious example, so lets run with that.

So, a tree of promises wouldn't actually require nesting promises at all:

function PromiseTreeNode(value, left, right) {
  return new Promise(function (resolve) {
    resolve( { left: left, right: right, value: value} );
  });
}
var tree = PromiseTreeNode('root', PromiseTreeNode('left'), PromiseTreeNode('right'));
Peaker commented 11 years ago

@copumpkin @pufuwozu Why not paste a few monadic combinators, with a couple of refactorings that depend on the monad laws, a couple of short programs that utilize the combinators, and then show how these programs could be used with promises or parsers/monad-of-the-day, but that won't be possible due to the refusal to have nested promises?

Sure, this is a boring homework assignment, but it seems to me that relative to the amount of time you've already invested in this, it should be a breeze :)

Peaker commented 11 years ago

Also, to @ForbesLindesay 's defense, the standard material on this stuff is not approachable if you don't have a background in any of Haskell, Agda, Coq, CT, etc. So transliterating a tiny subset of the required learning material to Javascript to illustrate would probably be helpful.

copumpkin commented 11 years ago

Yeah, I apologize for making overly broad critical statements about @ForbesLindesay there. That kind of attitude just rubs me the wrong way, to the point of getting nasty myself.

The fact remains that I don't have time to keep participating in this discussion, and don't think it really should be my duty to teach about this (although I do clearly enjoy teaching it on IRC, as I'm sure you've observed). Perhaps @pufuwozu will take the time, but that's his prerogative and would be very nice of him :) I'm also not sure that a bug tracker is really the best place to teach things like this.

dustinjuliano commented 11 years ago

@ForbesLindesay The Monad laws provide combinatorial expressiveness and a common binding that are "well-behaved" with an extremely large class of operations. This just makes sense from a language level; promises entail nonlinear changes of state in a way that can be delivered linearly in syntax. And monads have been used to deliver that kind of referential encapsulation in many languages. The most important reason to give @pufuwozu a listen is that promises could be improved without taking anything away from them conceptually. The onus shouldn't be on him when in fact there are dozens, if not hundreds, of written materials on the use and benefits of these abstractions in functional languages. One need not be a Haskell dev to realize that greater generality and a proven interface/pattern for combinatorial expression will make promises even better.

ForbesLindesay commented 11 years ago

@Peaker thanks, that's exactly what I'm asking for

@copumpkin It's not a lack of curiosity, it's the fact that there's much more to learn than I'll ever manage to learn in one lifetime. I'm in my final year of university so I have finals to prepare for. I care deeply about the next version of JavaScript, so I'd like to learn all about the different proposals for that (I created http://esdiscuss.org to help make that close to possible). I'm building a continuous integration system of JavaScript on the client side. I'm not asking you to prove I should continue learning stuff, I'm asking you to prove I should learn this, instead of something else.

joneshf commented 11 years ago

@ForbesLindesay sorry, I didn't actually mean a tree of promises, I just meant that trees are monads and trees can be nested, so that was supposed to be an example of why you would want to recursive monads.

ForbesLindesay commented 11 years ago

OK, so why does that translate to needing nested promises? Other than a flatten function, what else would you do with a promise that would require it to be nestable?

Twisol commented 11 years ago

Lets say I have a function query that takes a string of user input, sends it to the server, and returns a promise for the server's response. Now, I want to get the user's input, so I put up a popup window and create a promise userInput that represents the user's input.

userInput.then(query) :: Promise (Promise Response)

This type is quite exquisite. It explicitly shows that there are two different threads of execution involved here - three if you include the present thread of execution - and we have access to either one. In fact, we have access to the response thread from within the userInput thread, which is something we lack if Promises are pre-flattened.

There's one big reason why I think this is superior: it forces you to acknowledge and explicitly deal with the nesting if you want to access the response promise. This makes it clear that the response thread is entirely "later" than the userInput thread, so you don't have to keep track of a bunch of timeline interrelations yourself. Refactoring becomes easier, because you can immediately identify which parts of the code affect which thread of execution.

As for an actual bug in one, or outright feature in the other, that's a lot more subtle. A major benefit of these laws, as has been mentioned, is that they aid the programmer in equational reasoning (which directly affects reading and refactoring). There's certainly no reason why you can't have a helper method that follows a .then() immediately by a .flatten(). In fact, this helper method is still a different method from then, and serves to call out the "later-ness" just as explicitly.

ForbesLindesay commented 11 years ago

OK, I can see how it makes that more explicit. My impression of it though is that in JavaScript it just creates more re-factoring hazards and bugs because it forces me to always know whether something is a promise or a value. For most of the code I write, that would make things much less DRY.

Results of Some Research

I've done some research, just to keep everyone happy. I've spent the last hour watching http://www.youtube.com/watch?v=dkZFtimgAcM and also took the time to take a couple of notes here.

puffnfresh commented 11 years ago

@ForbesLindesay oh no, don't watch Crockford's talk. He gets a lot of things wrong.

puffnfresh commented 11 years ago

@ForbesLindesay your notes are fair. It is hard to imagine a case where a nested promise will break. I'll eventually come up with a small example that breaks horribly.

Sadly, I'm going to have to spend some time on it, just to show you something I know will break.

Twisol commented 11 years ago

Following on @pufuwozu's point, I recommend this one by Brian Beckman.

it forces me to always know whether something is a promise or a value

For what it's worth, I usually track the types in my Javascript code anyway. I put a docu-comment containing a type signature before functions that need it, or I tag a line that needs more clarification. And I've taken to the convention of suffixing promise variables with a $, like so:

user$ = server.getUser("Twisol");
user$.then(function(user) {
  // ...
});

For most of the code I write, that would make things much less DRY.

I'm not sure I follow that one. If you define a helper method that just calls p.then(f, g).flatten(), you have exactly the same code you had before (but with a different name instead of then). If I'm missing something here, can you clarify?

bergus commented 11 years ago

This thread seems to be still on the wrong track. Just to remember, the original assignment was to get a point function on Promises :-) So I'm gonna comment on some older post…

@juandopazo:

The problem [to fulfil left idendity] is with the overloaded then

I don't see that. To me, it's a problem of an overloaded constructor. In fact, we will need two of them: One that assimilates thenables etc, and one that follows point semantics.

Indeed, Promise.of(a).then(f) is equivalent to f(a) (assuming f is returning a promise - if not, it would at least behave the same while having different return values) and so satisfies the law.

One would expect that promise.then(identity).then(identity) would return a promise for the same value as the first promise.

No. Or only if you expect then to act like a Functors' fmap - which it does not always due to overloading. If you had explicitly used the map function as given above by @pufuwozu and later by @juandopazo, it would work:

promise.map(identity) ≡ promise

But if you are expecting the monadic then, it will fulfill the right identity law:

promise.then(Promise.of) ≡ promise
ForbesLindesay commented 11 years ago

@Twisol

If it doesn't flatten automatically that requires writing additional code. This would either need to be added everywhere, or I'd have to remember to add it whenever re-factoring caused it to be needed. Besides, then is not going to change that dramatically. It's not too late to change it to only unwrap one layer of promises. i.e. if your callback returns a promise for a promise, it only unwraps the first promise, not the second one. It's far too late for a .then that doesn't unwrap at all, not that anyone who's using promises actually wants that.

@bergus

I agree this went off topic. The issue is that although I'm not dead set against having a .of that supports returning a promise for a promise, I don't really see the point of it. I just don't see the use case. I've tried hundreds of phrasings of that question, but nobody's actually answered the question of "why are promises for promises necessary?"

puffnfresh commented 11 years ago

@ForbesLindesay "why are promises for promises necessary?" <- to not break the monad laws. You have an answer. What you want is an example, of which I have one in my head. I'll write it down sometime soon.

briancavalier commented 11 years ago

nobody's actually answered the question of "why are promises for promises necessary?"

From my perspective, I feel like answers that have been given, have tended to be "because otherwise we break Monad laws". Unfortunately, that is only a helpful answer to someone who already understands what Monad laws are and why they are important. To someone who doesn't have that experience/perspective, it doesn't really help. What would likely help is some further explanation, examples, or at the very least some links for further reading.

@pufuwozu your answer was serendipitously timed. It appeared as I was typing the above paragraph.

I understand everyone is busy, but if you could indeed take the time to write down that example, I think it would be hugely beneficial to moving forward.

techtangents commented 11 years ago

nobody's actually answered the question of "why are promises for promises necessary?"

This has been answered many times over. Let me summarise:

  1. Identity law
  2. Parametricity
  3. Practical example: https://github.com/promises-aplus/resolvers-spec/issues/24#issuecomment-16310925

Parametricity is a very important concept that I'd like to highlight.

Parametricity means that when you create a data type that's parameterised over another type, it works the same regardless of the type parameter. e.g. if I have a list of strings, it behaves exactly like a list of integers, for all list operations. This means also that your data type implementation deals only with the structure and function of that data type itself. That structure and function then applies identically across all instances.

The logical expression is of this form: For all values of a type X there is a type Y(X). e.g. for all types X, there is a type Array of X.

(In JavaScript, the type X is really the 'universal' type as references are untyped)

This principle is deemed so important that many languages enforce it. e.g. in Java, if I am implementing a new structure FunkyList, then in my class definition, I cannot call any methods of values of type A, because I don't know anything about their type is (unless I do reflection, but that defeats the point).

So, the benefits of parametricity are thus:

  1. As a user of a data type Y(X), I can be assured that Y behaves identically for all type parameters X.
  2. As the creator of data type Y, parametericity means that I don't have to test Y for any specific values of X - if I can test that it works for a single type parameter, it will work for all.

It follows, then, that I should be able to create a Promise of Promises, because I can create a Promise of anything! There is nothing special about a Promise that prevents it from being a type parameter of Promise.

Also, if I were to create a library of useful functions on top of Promises, I wouldn't know what type of Promise was being passed in. However, in order to reason about what my functions do, I need to be able to reason about what the base Promise functions do. If the base functions behave one way for all types of values, my job is easier.

it forces me to always know whether something is a promise or a value Well, a promise IS a value. More generally, this is a complaint about "I don't know what type this value is", which is a fundamental problem with dynamic typing and not specific to this discussion.

Let me take a different approach. A Promise is a computation which may produce a value in the future. A function is a similar concept - it just produces a value when it is invoked. So, a Promise is very similar to a function (with its arguments applied), and these ideas generalise.

More specifically, a Promise is a type of value - the asynchronous equivalent of Id. A Promise may produce a value in the future; an Id is just a data cell that can produce a value right now. A function that returns a Promise can be considered an asynchronous function - the asynchronous equivalent of a function.

So, we're using these concepts just to model a different execution mechanism and different data channel for returning results. So, they generalise.

Ok, so a Promise of a Promise reads thus: I wish to have an asynchronous computation which produces another asynchronous computation.

Applying the the general concept here is thus: I wish to have a computation which produces another computation. This sounds familiar - when applied to functions, we call this Higher Order Functions. Currying is a typical example of this. It is well-established that Higher Order Functions and Currying are useful.

So... a Promise of a Promise can be thought of as a curried Promise!

So, what of this generality?

Looking at Promise vs Id. What concept abstracts the notion of "a value produced by a specific means or in a specific structure"? Well, we call them Functor, Applicative and Monad.

Looking at "function" vs "asynchronous function (function that produces a Promise)". Well, these concepts generalise to Arrow and Category. (Given that Promise is a monad, a function that produces a monadic value is an abstraction known as a Kleisli. All Kleislis are Arrows and all Arrows are Categories).

In our case, the whole point of the Promise data type is to encapsulate what it means for a value to be produced in the future. We are encapsulating this behavior into a data type. "Produced in the future" is just one mechanism that a value may be produced - we can abstract on this mechanism, and that is what Monad is useful for.

I can produce a value one way, or another, or a third way - it doesn't matter. I can define functions that operate identically regardless of how the value is produced, just by encapsulating "how that value is produced" in a Monad instance.

So, why is this useful? As has been explained, a large number of types are Monads and Monad gives rise to a lot of operations. i.e. DRY.

Ok, let's look at "point". Aside from being required for Monad and Applicative, it is practically useful for a few reasons.

And, well, some practical examples? I do a HTTP request to get a URL for another HTTP request. I may want to do the first request now, and the other later. This is a Promise (Promise HttpResponse). I evaluate the first one, which gets me the Promise I need to use later on to get my final data.

Sure, you could just store the URL. But, what if it isn't always a URL? What if the server sometimes gave a URL of an image, sometimes base64-encoded data of an image? Then I have a Promise (Promise Image).

Say I wish to poll a URL. You could do this with recursive setTimeout. SetTimeout is a way of constructing an asynchronous computation. So, a setTimeout loop polling a URL is an infinite nesting of Promise (Promise (...)). This can also be represented as a stream or signal - this is basically what Functional Reactive Programming is.

Then, lets go to testing. Generally, in testing, you wish to not perform side effects because:

  • they're slow
  • they impact the real world
  • they may require a browser
  • you want to run them on a CI server in a console on Node

So, what can we do? There are a few techniques:

  1. Instead of constructing a Promise that returns a value from a HTTP request, let's just create a Promise that returns a pre-set value. By parametricity, these should behave identically. So, I can test my code by using "point" aka "of", instead of a side-effecting one.
  2. This still leaves us with an asynchronous computation, which can be messy to deal with in tests. So, if we abstract over the mechanism of computation, we can test with values of a more convenient computation (e.g. Id) and still gain the same confidence in our correctness.

So, to summarise:

  1. We want to implement Monad, because it is incredibly useful.
  2. We want to obey parametricity, because it makes it easier to reason about for the implementer and caller, and avoids run-type type inspection. Also, because it is required for the laws of Monad, Applicative and Functor. Parametricity is of particular importance in a dynamically-typed language, as you never know what type you're going to get passed in.
  3. We want to do these things to make asynchronous computations behave like synchronous computations and many other computations in general.
  4. Use cases of nested Promises have been demonstrated. You have a nested Promise whenever you have an asynchronous computation that produces some value that needs to be input to another asynchronous computation.
  5. Abstracting over a mechanism of computation is useful in order to reason about your code abstractly and has practical benefits in testing.
  6. You're creating a standard for promises, so it may be useful to consider the common aspects of promise implementations in other languages. Implementing Monad is certainly common and has been demonstrated in JS promise libraries.
  7. Honestly, the liftA2 function @pufuwozu showed should be more than enough on its own to demonstrate the benefits of his proposal.

I really think the benefits of @pufuwozu's proposals are irrefutable and any remaining reluctance just comes out of fear and a need for some learning. Rest assured, though, there are a lot of resources out there to help, and people who will volunteer their time to mentor anyone with an open mind and a willingness to learn.

techtangents commented 11 years ago

I think we need to close this thread. The benefits have been explained many times, and I believe no convincing counter-argument has been proposed.

Beyond this, it's up to the project contributors to either accept or reject the proposals.

I sincerely hope that you see the benefits of what has been proposed. Know that the wider programming community is watching this thread, and it has become a bit embarrasing for us as the JS community that we are actively refuting some very well-established computer science, mainly out of attitude, fear and unwillingness to learn.

Moreover, it is an opportunity for us as the JS community to step up and say: yes, we are real programmers, we're not babies, we can take on board useful computer science concepts and wield them like professionals.

ForbesLindesay commented 11 years ago

Give me a minute to finish reading your post, then we can discuss closing/not closing :smile:

ForbesLindesay commented 11 years ago

Right, I've read that, and taken my time to digest it. This explanation was good, it was clear, and I think I'm now in favor of us moving in this direction, or at least not ruling it out yet.

liftA2 wasn't good enough, because I still don't know what it does, it's really not obvious. Code that's not obvious rarely wins arguments.

I think it would be well worth you re-posting that comment somewhere as a Gist so we can link to it from other discussions around this issue as "motivation for promises for promises". I think it would also benefit greatly from a few proper section headings.

Moving Forwards

I want to see consensus, here's my proposal for how I think this can be achieved:

.then

It is probably not too late to change the behavior of recursively flattening promises at the end of a .then callback into just flattening one layer of promises. I will open an issue to this effect, and attempt to explain the reasons why I have shifted my view on the issue. This would make .then equivalent to fantasy land's chain.

It should be noted that other than that change, you won't succeed in affecting any other changes to the semantics of then. As such, people should refrain from any discussions relating to strict typing, separating error handling, functions that return pure values (i.e. map) etc. etc.

.map

Map can be implemented on top of then and of if we get it to flatten a single layer rather than multiple layers. As such, we should stop talking about it and no further mention of it should occur in the promises-A+ world until after all other points have been met. At such a point, the request would need to be for a separate specification for map. I suspect that you won't ever get this specification integrated into proimses-aplus, but that's OK because you can still implement map in terms of .then and .constructor.of.

.constructor.of

This won't be added directly to the objects themselves, that would be very weird, some objects may support it as a convenience function.

You may succeed in getting this added to the constructor. This will almost certainly be in a separate spec, not the resolvers spec, and not the promises spec. This is low priority, providing that no spec explicitly states: "There must not be a way of creating a promise for a promise". As such, you should defer all discussion on this matter until after the discussions of .then are concluded.

This issue

Since we are now looking for a different named method to the one you started out asking for and a lot of space has been taken up debating the rights and wrongs of promises for promises, I propose we close this issue. I think this issue should be renamed to Importance of Promises for Promises. I think a summary should then be added that should look like:

# EDIT: Summary of Discussion

Promises for promises were discussed at great length.  The discussion was concluded with the arguments in favor of allowing promises for promises summarized in [this gist](link to gist containing @techtangents latest post with headings etc) and the arguments against are summarized in [this gist](I'll create a gist, or someone else can).

I think once the discussions surrounding then are concluded, I think a new issue should be opened on this repository requesting the creation of a repository in which to discuss the possible specification of the .constructor.of method.

If this gains @Raynos's approval, he can make the necessary adjustments to this issue, alternatively so can someone who is an admin/collaborator on this repository.

puffnfresh commented 11 years ago

Here's an example of where a broken of will break a program.

I write a small module in terms of an abstract monad. In production I have everything asynchronous. In testing I have everything blocking for determinism (woo, easy deterministic tests!).

In my code, I use the great lift4 function. The lift4 function takes a 4-arity function and then 4 monadic values as arguments - it then returns a monadic result.

lift4(f, a, b, c, d)

Let's make this more concrete. f will become a function that creates a user on a server (i.e. it returns a monadic value). Its arguments are name, password, age, address.

var userMM = lift4(createUser, nameM, passwordM, ageM, addressM);

(Where the M suffix means a monadic value and MM means a monadic value of a monadic value, i.e. the values are in a promise or some other monad, depending on context)

Under the identity monad we get an Identity(Identity(User)). Under broken promises we get Promise(User). That's strange but let's keep going.

Now, let's say the returned userMM has an id property from our database. I have an existing function called getId:

// Takes a monadic user, gives back the monadic user ID.
function getId(userM) {
    return userM.map(function(user) { return user.id; });
}

Now, I can just do this:

var keyM = userMM.chain(getId);

It'd work for actual monads but not promises. The ReadWriteState monad would call chain, get the monadic user and then map the monadic user into a monadic id. Promises would call chain, get the actual user value and then getId would call map on the user! The wrong thing!

@ForbesLindesay are you happy with that for an example? It's both concrete and realistic.

puffnfresh commented 11 years ago

Well, glad you were convinced one minute before my example :smile:

puffnfresh commented 11 years ago

@ForbesLindesay the Fantasy Land specification allows of to be on the value or the values constructor. Either one. Code abstracting over it must fall back to either.

ForbesLindesay commented 11 years ago

OK, to be clear, I'm happy that this needs further consideration, and more eyes on it from the promises side of the fence, rather than just me + a few people in neither camp + everyone from fantasy land (I still think that's a terrible name for a spec you want people to actually use).

Just a point of clarification: Why can't you fix the above by just making Identity also do the same recursive flattening?