TC39 Pipeline Operator – Hack vs. F#
benlesh.com
benlesh.com
My suspicion is that once you move away from toy examples, most pipeline operator use cases are already covered by chaining class methods on classes. I suppose you could argue that the pipeline operator allows you to operate across multiple different data types, but I further suspect that handling many different data types with a single function is an annoying thing to get right and this won’t come up in practice all too often.
To be fair, the case of pulling in only the methods you need on rxjs seems somewhat useful… but do we really need a whole new operator just for that? And isn’t that the point of ::?
F# itself much prefers the pipeline, because of how its type inference algorithm works. F#'s type inference finds it much harder to work out the types when you use a dot operator, because so many possible types T could have `(x : T).Foo(bar)`, all those types are unrelated to each other, and notions of "has a member `Foo`" are quite hard to get right in the type system. By contrast, if you call `x |> List.map bar`, the types are almost totally fixed in an easy-to-understand way.
"Handling many different data types with a single function is an annoying thing to get right" - no, this is very common, and generics even make it easy.
I really fail to see how those kind of changes bring anything of value to the language, apart from creating complexity where there is much already: some codebases will try and use this before it's ironed out with different / changing / competing transpiler implementation while it is only stage 2. What happened with decorators (see babel-legacy-decorators) should be a warning against enthusiasm for these kind of things and remind me of the pitfalls of macros in the Lisp world...
I am not saying that you should stick with an idiom till the end of time but changes should try and lower that complexity while (in the case of EcmaScript) being backward compatible so as to not break existing stuff.
Btw I love RxJS and its variants, Ben Lesh's talks (as well as those by Matthew Podwysocki, Andre Staltz etc...) from around 2015 and then on were one of the reasons I got into JS as a professional.
But it's not the case for the majority of libraries, including many of the builtin types.
A pipeline operator is generic and can be used everywhere, without requiring the API to be built around chaining. This can often lead to much nicer, more readable code.
I think this is something you only start to really appreciate once you've used it a bit, like in Elixir or F#.
Obviously this is much more natural in a functional language, where everything is immutable anyway.
Methods are nice but suffer from the fact that adding a custom method to a new object is more involved and dangerous than just creating a new function. However, "f(g(h(x)))" is not very readable (at least for English speakers) since while we read left to right, the invocation order is right to left. "x | h | g | f" is arguably more readable since the evaluation order follows reading order (plus you don't have to deal with so many parenthesis).
I want to reemphasize though that introducing a variable is often better practice and that the pipe operator only makes sense when there is no suitable variable name.
There's also a "hierarchy" thing at play. With "f(g(h(x)))", x is "inside" h which is "inside" g which is "inside" f. With "x | h | g | f" all are on the same level. For me at least, it's easier to imagine your data "flow" through functions when they are on the same level. It sound a bit weird when I put it that way, but I don't think I'm alone in feeling that. Fluent interfaces are considered easy to read, and help flatten the code. Same thing with promise chaining compared to the callback > of doom.
Smart Blobs don't have to mutate themselves anymore than procedures have to have side effects.
Why would I be more likely to mutate state in sending a message to an object than I would be applying a procedure to a struct? (or a function to a record, depending on your terminology)
Immutable objects are a very old and mainstream idea, I believe they're even talked about in Effective C++.
Having said that, I actually don't know the history of the dot operator in any depth (https://cs.stackexchange.com/questions/89031/what-is-the-ori... suggests it arose in Simula).
I think most people don't think about objects in terms of sending a message to them, but in terms of calling a method on them. OOP in JS, currently, revolves a lot around mutable objects. JS itself revolves a lot around mutability. Some people are trying to change that, at least by getting proper support for the alternative. The pipeline operator is part of that.
There is also the fact that JavaScript supports different types of programming, functional being one of them. Having a pipe operator helps you to make very clean and readable functional code.
Edit: the article also mentionned that methods can't be tree shaken. That's another improvement.
But what if we don't want to use classes? What if we want to be cool and compose functions out of functions, Ramda-style, or Elm-style?
Piping is a common operation, though, and having dedicated syntax makes the code more readable. For those code bases that use curried, unary functions, the F# proposal is perfect (this is the original motivation behind the operator).
The hack-style pipe syntax that has been chosen is much worse in that regard, which is disappointing for the very folks that requested its addition.
I sort of agree though about the F# proposal version. It doesn't make sense to introduce if it is basically equivalent to having a pipe/pipeAsync function. I suspect this is a big reason why the Hack version was favored.
But defining these is typically left to library authors in many languages. Writing your own Fluent/chaining interface isn't usually worth the effort. Where in these languages because any function is "chainable" and gets it for free a lot of programming ends up being chained pipelines. Anything where there is a logical workflow (a lot of programming) ends up being nice to read when expressed with pipes (i.e. do this, then this, then that, and finally return this). The pipe operator goes hand in hand with currying as well since you can complete some of the arguments before wiring the partial completed function into a generic workflow; a pattern that typically isn't be done with Fluent/Chaining methods on classes.
Some people also find it easier to program in an FP style (separating data and functions) in their app code. It seems to be a matter of neurodiversity.
I'm jesting of course, I find JavaScript already too complicated, it's like some people want to make it look like Scala... just no.
A TC39 member on this topic of restraint and priorities: https://erights.medium.com/the-tragedy-of-the-common-lisp-wh...
I get that you don't want it *to become* complicated, but as it currently is, JavaScript is still a rather simple language.
val plus: (Int, Int) => Int = _ + _ foo(42, ?)
but not what you'd write within this pipe syntax as foo(42, ^) + 1
The tradeoff is that it doesn't need some extra delimiter since the function call is what delimits it. Perhaps that's a better tradeoff, I'm not sure; but for sure we shouldn't have both. let v = first();
v = second(v, 10);
v = third(x, y, v);
return v;
Why do we need a new operator for this? return first() | second(_, 10) | third(x, y, _)
I somewhat agree.And the placeholder can't be _ as that's a valid identifier. The first issue on the tracker is the bike shedding thread about what the placeholder symbol should be, and it's neither _ nor ^, but instead probably something like ^label.
Suppose you had "const _ = 42; /* more code / return x | f | g(11, _);". This would be semantically equivalent to "const _ = 42; / more code */ return ((_) => g(11, _))(f(x))". Since it is a new function, shadowing is not forbidden.
Source? This hasn't been my experience. Going on 10 years of heavy Node.js ecosystem involvement, immutable data enthusiasts are exceedingly rare.
Plus, this is const vs let, which is a reach to call "immutable data". We're not talking about object properties.
Not an authoritative source, but since you cite your own experience, mine has been the opposite. Especially so when TypeScript is also in the mix.
> Plus, this is const vs let, which is a reach to call "immutable data". We're not talking about object properties.
As I mentioned in a sibling comment, const is often used to signal the intent to treat an assignment as immutable. This isn’t universal, but I understand it to be idiomatic usage.
Immutable.js is relatively popular and immutable records and tuples are a stage 2 TC39 proposal. From what I've seen, immutability is mostly popular on the frontend, probably because functional programming had a huge impact there. It's also popular in other languages (FP or FP inspired generally, so OCaml, Haskell, Scala, Elm, Elixir, Rust) that are relatively close to the web ecosystem.
> Plus, this is const vs let, which is a reach to call "immutable data". We're not talking about object properties.
I'm not sure what you mean here.
- The pipeline operator can be used to assign to a const, to prevent further assignments. While const isn’t necessarily immutable, it is often idiomatically used to signal that the assigned value is intended to be final. The same can’t be achieved with your example without wrapping it in an IIFE, which is (IMO) much harder to follow than the pipeline operator.
- More subjectively, it (in the F# variant) encourages better interfaces. For most use cases where piping would be appropriate, it’s generally a good idea to make the data you’re processing the last parameter. This also, as the article notes, works well with partial application. Which in turn also encourages good practices like composition.
Those are my opinions, however.
It’s worth noting though that the TypeScript team does participate in the standards process. And Microsoft has two members on the committee.
This is somewhat less true in some frontend projects, where the underlying libraries/frameworks come with infectious built-in interface complexity (side-eyes React/JSX even though I quite like JSX otherwise).
Part of it may also be due to the limitations of TypeScript. Structural typing is not always the best choice. ADT support is also not the best.
let transformedData = transformFoo(data);
transformedData = transformBar(transformedData);
transformedData = transformBaz(transformedData);
vs.
const transformedData = data
|> transformFoo
|> transformBar
|> transformBaz
If you want have const's the first becomes even more unwieldy, and in general I'd recommend using const by default.Just like lambda syntax makes it much easier and readable to write small functions, the pipe operator make it much easier and readable to write chains.
succinct =/= more readable.
Readability here is really in the eye of the beholder...
It's certainly quicker to type, but that's not a good argument enough to make such a drastic change in javascript.
I am so glad this argument has not been winning out in the JavaScript language design community. There are so many wonderful constructs that have been added in the last 20 years that are just sorter ways to write things that could mostly already be done in the language. Many of these features focused on allowing developers to write what they intended to do without having to explicitly construction the intermediate steps to express the mechanics of how that should be carried out using basic language features.
After all why do we need arrow functions when we could just sprinkle our code with `var self = this;` declarations for anonymous functions to bind to, the way it was done in the late 90's and early 00's.
I'd much rather JavaScript adopt succinct ways to write common code patterns and let the developers and the community decide if those constructs are the correct ones to use on a case by case basis.
Beware of survival bias, though. There have been many proposals that aren't part of JS today.
arg function_name
Then instead of arg |> func1 |> func2 |> func3
you could simply write arg func1 func2 func3
It might get a bit ugly when used with arrow functions instead of named functions, and there might need to be a special case when arg is a function, but if those problems could be handled not too unreasonably this seems a fine approach for a programming language. 1.. |> take 10 |> map {|e| e*2} |> (x)
> After experiments, |> have caused more confusion and controversy far more than I expected. I still value the chaining operator, but drawbacks are bigger than the benefit. So I just give up the idea now. Maybe we would revisit the idea in the future (with different operator appearance).Understatement of the year, that's the worst token I've seen in all my years of working with javascript and I hope it doesn't go through.
if pipe() works for RxJs, and hackpipe is not better, then why don't you simply stick with pipe()?
Just because one operator is there, doesn't mean you have to use it.
JS classes are notoriously under powered, so much that both react and vue prefer functions over class components
Besides, it is possible that RxJs (and other libraries) may modify how they work to better utilise hack pipe
y %>% f(x, ., z) === f(x, y, z)
R lets you do macro-ish things at at runtime [1], and `.` is a valid variable name [2]. so %>% can just evaluate the AST of its right argument in an environment with `. = a`.(it's probably a bit more involved because %>% also supports
a %>% f(b) === f(a, b)
in which case %>% has to do some AST surgery to splice another argument in front of `b`.)---
[1] https://en.wikipedia.org/wiki/Fexpr
[2] think `_` in python etc. R uses dots instead of underscores
(as-> [:foo :bar] v
(map name v)
(first v)
(.substring v 1)) input |> func(?, 2)
input |> func(1, ?)
While hack's placeholders work exclusively in pipelines, the partial application proposal can be used with any function "123"
.split("")
.map(parseInt(?)) // make sure radix param is not set
[1] https://github.com/tc39/proposal-partial-applicationActualy this whole debate should be called scala vs F# because they are more corresponding, being both functional language on a OOP runtime.
For most of these proposals it is just syntactic sugar around invoking the function with a placeholder. The pipe in F# is slightly different in that most of the time it has no intermediate lambdas and is compiled in a more performant form. The downside is that unless you allocate that lambda yourself it has to be the last arg. On the plus side like most things in F# it is concise but shows all behavior explicitly - its usually a warning sign if you have to do that and helps reason about performance. Sometimes its a sign that the original function isn't written right or some other inline wrapper could be used for other usages of the function. You can inline a template to rearrange the arg's (inline) to avoid the lambda allocation as well.
This allows some level of re-use and performance benefits avoiding virtual table dispatch and a lambda allocation for many common methods (e.g. map, fold, iter, etc)
I believe the point made in the discussion is that the F# proposal leads to intermediate lambda if the function does not have the right arity. JS also don't do HM so that point is moot.
The people supporting the Hack proposal made the point that their expressions do not desugar to lambda and has no runtime cost, no idea how it works though.
I went through the github issue the other day, syntax aside, the two proposal boil down to functions vs expressions (no extra functions)