...Wat?
This is an article about how the most well known villain in the JS universe isn't really evil, just misunderstood.
G...
For further actions, you may consider blocking this person and/or reporting abuse
But why would you EVER want to do this if there is already a continuation monad implementation in the language itself that:
Yes, I'm talking about Promises. Yes, Promises are effectively continuation monads (not to the strictest definition of a monad but neither is the implementation in this post). The .then function is the monadic bind (e.g. '>>=') and Promise.resolve is 'pure' (which you don't need as often because .then will automatically perform a pure of a value that isn't a monad)
Here is a code example showing how they're methodologically equivalent (and qualitatively better) than what is described in the post. I'm doing this in the hopes that I never have to see anybody doing this in actual code I have to work with. Stop trying to be smart. Don't reinvent the wheel. Please...
The ways in which promises do not form a monad (and in fact not even pure values) are actually pretty well understood. In particular,
then
is not a lawfulbind
, andjoin
is impossible to express (because simply referring to a value causes effects to start happening).Moreover you cannot generally express interaction with traversable containers, functor composition, monad transformers, or other general purpose abstractions with respect to promises, because again, they don't actually form a monad.
Regarding "neither is the implementation in this post": I'm not sure you've actually grasped the content of the post if this is the conclusion you've arrived at. The operations given in this post precisely form a monad (including obeying all the relevant laws).
In the construction above,
verifyUser
is a pure, continuation returning function. In your snippet,async function verifyUser(user, password) { ... }
is not even really a function in the functional programming sense of the word.As a very simple example, the promise produced by mapping a Promise-based implementation of
deleteUser
over an array of usernames and taking the first element doesn't represent deleting the first user; instead every user in the database would be deleted. Conversely, doing the same thing with adeleteUser
based on a lawful asynchronicity monad, as given in the post, would be no different than taking the first element and then applyingdeleteUser
to it. Both would produce a continuation representing deleting the first user (nothing would actually start happening "behind the scenes").I'm not going to argue about strict definitions with you because you don't know what you're talking about and are opinionated about your misconceptions. I simply don't have the time.
They are the same - please inform yourself more thoroughly.
Not being able to implement
join
has nothing to do with it being a monad. It's because they're automatically flattened. You don't have to implementm (m a) -> m a
ifm (m a)
is equivalent tom a
. But again - it has nothing to do with it being a monad.My point is that they can be used the same way as your continuation monad implementation and as such should be favoured over it because they're standard language constructs. Period.
Also, of course
async function verifyUser(user, password) { ... }
is a pure function. It's referentially transparent in the sense that given the same parameters the Promise returned will always be the same. How that promise is consumed doesn't matter. Again - inform yourself.Lazy evaluation also doesn't have anything to do with purity or it being a monad. (regarding your
deleteUser
example. You're mixing up concepts that you don't seem to understand)Thanks, the definition you posted above is helpful. Try evaluating
const map = f => bind(x => pure(f(x))); map(pure)(pure(5))
to understand why this is not actually a lawful implementation ofbind
.Without having a
join
operation (which can be recovered asbind(id)
from a lawfulbind
), it's actually meaningless to talk about a "monad". Monads are fundamentally defined by an associativejoin
and an idempotentpure
, together forming a monoid.This isn't about lazy evaluation vs strict evaluation, but rather about pure vs impure evaluation. The term
verifyUser(user, password)
does not purely evaluate to a representation of an effect; instead it immediately starts performing effects in the course of its evaluation. The result of evaluating it is not dependent only on its inputs, but also on the state of the world.This means
verifyUser
isn't actually a function in the functional programming sense of the word, preventing us from reasoning equationally in programs that involve it. For example the following program:is not the same program as:
when using promises. It is when using a lawful asynchronicity monad (e.g. the continuation monad above). Whether this is bad or good depends on whether you prefer an imperative or functional style of reasoning.
Your definition of monads is wrong. It has nothing to do with
join
, their time of evaluation or 'imperative vs functional reasoning' lol.Here are the monadic laws proven with the Promise definitions from above - in js.
You're also wrong about the fact that the promises don't evaluate to the representation of an effect first. Of course they do. The point in time the underlying implementation decides to consume that value has no significance whatsoever. As I said - you're mixing up concepts, don't understand monads and likely don't understand Promises either.
This is the first time I've heard that monads have nothing to do with the join operation. You should share this revolutionary insight with the mathematics community.
Regarding the "proof" of the monadic laws above, unfortunately the laws don't hold for the definitions given (the proof-by-single-example notwithstanding). In fact, the definitions are not even well-typed.
Conveniently, to disprove something requires only a single counterexample:
I'd like to have discussed how the word "monad" refers to a particular kind of endofunctor with
join
andpure
natural transformations, but I really have to take a break from this conversation. I don't mind discussing things with people I disagree with, but the complete lack of manners displayed in your comments goes poorly with your total ignorance of the subject.Very interesting. A few things I like...
I like how
verifyUser
has now become Lazy.I love the
M[">>="]
function. First time I have seen an object used like this.Without Promises, you have eliminated a round trip to the event loop (for sync functions).
I had a hard time finding the
@masaeedu/mdo
package. I did find@masaeedu/do
though. Typo? Could you throw me a link?Cheers!
Hi @joelnet . Yeah, sorry. That's a typo on my part. The repo is here: github.com/masaeedu/do. There's no README yet, sadly, but here is a slightly more fleshed our runkit with usage examples for various monads: runkit.com/masaeedu/do-notation
Awesome thanks. There's some magic in that lib that I'm gonna have to play with to fully understand. I didn't know it was possible to do something like this:
Those proxies are some interesting things.
I recently did something related with the W Combinator. I also need to improve the docs :( But I like how your implementation allows you to assign values.
What's currying doing for this code, exactly?
Hi Pablo. What currying is doing for this code is turning an impure function of type (ignoring errors for simplicity):
, which is not a monadic value, into a pure function of the type:
for which the return type
({ userInfo: UserInfo, roles: Roles } -!-> Undefined) -!-> Undefined
(and more generally, the type(a -!-> r) -!-> r
) forms a monad.We're changing our perspective so that all of our impure functions of multiple arguments can instead be interpreted as pure functions that accept one less argument and return an impure, callback-accepting computation with possibility of failure.
Thanks for writing this up! I was first introduced to currying in Scala but I was a junior at the time and didn't get it at all. This shows it in a neat example.
I also like your step-by-step refactoring process. Cool to see how other people approach it.
Awesome! I first saw applicatives in Scala. Bring self taught from the imperative braces world not enough of that has rubbed off to transfer onto other languages. I would really like to see more articles about
do
that are written in as approachable way as this one."Perhaps in a future post we can re-derive this abstraction with the monad and monad-transformer concepts foremost in our minds, and with special attention to the types and laws." - Perhaps after that you could write it in Malbolge.
I see a Monadic Javascript Framework in the future....
tips fedora
But what about 🅱erformance?
History is littered with situations where someone comes up with higher abstractions and people say ”but what about performance”. Due to fear, uncertainty and doubt people avoid it for a time. Then whatever people thought might be show becomes mainstream if it brings higher developer productivity.
Sure some people need to drop into C or even assembler and maybe some of those people are even doing this from JavaScript. They probably measure for themselves before taking anyone else’s advice on performance. They won't ask about performance they tell you what they have measured about performance.
Most folks running JavaScript typically are not dropping to C. Most folks using garbage collected languages are awaiting IO and so high level programming abstractions run satisfactorily. In this article the code is calling a database over a network. The runtime will be doing garbage collection. The runtime will do a lot of optimizations. Swapping around functions probably will use more objects and more final machine code but measuring that difference on real applications outside of synthetic micro benchmarks is often really very hard.
People should try things out new approaches and measure the performance in their context. As a rule of thumb unless you know your working on performance critical sections of code it is most often worth trying to optimize for less bugs than more speed.