News for hackers. Stuff that matters.
Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @08:44AM (#38823986)
I think this article actually does a really good job of explaining why TCO hasn't really been an important part of the JS ecosystem.

There's a lot of situations where recursive algorithms are really neat and clear. I don't know if this is the best example, but it shows the benefit of being able to split logic into a base case and a recurrence case.

But, in my experience, an algorithm that elegantly fits a recursive relationship is rarely one that naturally fits the tail-call paradigm. Often part of the benefit of recursion is that you can store state in the stack - the very thing you need to avoid to use TCO.

This means you often need to put in effort to create a tail recursive algorithm. But that often ends up looking a lot like the imperative case anyway - an accumulator outside the loop that you either mutate manually, or update in a tail call. And in my experience, the mutating, imperative version is usually then the easier to read and write (assuming you can keep mutations to a given scope, and not have that state leak all over the place). (In fairness, this might be more familiarity, though.)

In the light of this, what is the advantage of TCO? In functional languages without mutation, it's pretty important to allow for functions to act on arbitrarily-sized inputs without constantly growing the stack. But if we have mutation, it's really just a different way of writing the same code. And if that different way is generally less clear and almost always less performant, it probably isn't a very useful choice.

Which is why I think TCO hasn't really caught on in the other JS engines. It's a cool idea, and there's definitely a handful of cases where it's the useful way to go, but usually you'll be better served by writing things in the more traditional JS way.

Re:Bun, JavaScript, and TCO by pjmlp on Sunday December 31, 2023 @08:49AM (#38824008)
Regardless, it has been approved as part of JavaScript specification and Chrome folks refuse for political reasons to implement it, which given the market domination everyone has helped them achieve is a bummer.
Re:Bun, JavaScript, and TCO by tomashubelbauer on Sunday December 31, 2023 @09:44AM (#38824364)
I find it surprising that the JS specification also includes optimizations an engine should implement. I'm not sure how difficult TCO is to implement, but I just checked if QuickJS supports it or not and it seems to be one of the few ES2020 omissions the author chose to make: https://bellard.org/quickjs/quickjs.pdf (3.1.1). This tells me it might be non-trivial to implement which if true makes the decision to make it a part of the specification all the more surprising, because that means the specification restricts the types of trade-offs implementers can make when attempting to achieve full compatibility. In other words, until today I was under the impression you could make a fully ES compatible engine, but choose to make it slow for implementation ease. Looks like the spec defines the floor for how (non)-performant the engine implementation can be in some cases. Is this common in other languages' specs?

Edit: Oh, seeing the sibling comment, are TCO and "tail calls" different things? If so, I remain unclear on the status of TCO support in QuickJS.

Re:Bun, JavaScript, and TCO by mananaysiempre on Sunday December 31, 2023 @10:29AM (#38824679)
There’s a bit of a naming confusion around tail calls, but in any case “proper tail calls”, let’s call them that, are not precisely an optimization: they are a guarantee that any number of recursive calls of a certain kind will result in constant and not linear memory consumption. This permits some kinds of programming that can otherwise be quite awkward. If your program takes advantage of them (as e.g. often happens in Scheme), having tail calls is not an optimization issue, it’s an implementation correctness issue.

Now tail calls are quite annoying to implement in C on top of a compiler that doesn’t (and in fact I don’t think any mainstream platform has a C ABI that would allow a C compiler to natively support them between functions of arbitrary types). That has always been a (solvable) issue for Scheme-to-C translators, and it was probably a consideration for QuickJS. Chrome’s V8, though, is so far away from interpreting things in C or even translating them to C that I expect that any difficulties the developers have are of a completely different nature.

(As an example, LuaJIT does support tail calls but kind of sucks at inferring hot loops written using them, so has really impressively draconian limits on how many you can have before the JIT aborts. They otherwise work, though, as is required for a valid Lua implementation.)

Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @10:46AM (#38824809)
TCO isn't really an optimisation per se, at least in the sense that optimisations typically aren't observable as part of the semantics of a language. TCO does affect the semantics; it says that a recursive function that recurses only using tail calls will never overflow the call stack. That's why it's something that might get specified in the specification rather than just left as an implementation detail: it's the sort of implementation detail that developers might actually rely on.

While in practice it probably improves the performance to have tail calls, theoretically, the spec isn't making a point about performance here, only semantics. It would, for example, be allowed to have a spec-compliant JS implementation that handled tail calls very slowly, as long as they are correctly don't increase the stack.

As to why various implementations don't do TCO, my impression is that it's a combination of complexity and usability issues that have kept it from being implemented. And if some of the major browsers won't implement it, then I can see why other, smaller implementations don't see it as a priority.

Re:Bun, JavaScript, and TCO by EE84M3i on Sunday December 31, 2023 @03:27PM (#38827240)
There's another consideration, you can introspect the stack using Error.stack (also Function.caller and friends?). It requires a spec change to say "it's okay to not not includes these stack frames in specific cases". This information would also presumably not show up in the devtools / debugger or sentry, etc.

I personally more agree with not implementing it implicitly (although I think there was some discussion about having a special syntax) just because of the potential for confusion during debugging. E.g. if all tail calls are elided, then you could have stack frames that don't "make sense" (how did function A call function C? well, through function B but that frame is gone, and this could be really difficult in deep stacks). Alternatively, you could use a heuristic but that just raises even more questions.

Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @03:56PM (#38827449)
This solvable enough by activating a shadow stack. You can also just note on the trace pretty cheaply that X function was called by a tail call function. This eliminates any ambiguity about what happened.

It’s not a different issue from async functions not having a stack trace and JS devs survived for decades without async traces just fine.

Re:Bun, JavaScript, and TCO by basil-rash on Sunday December 31, 2023 @10:21AM (#38824614)
Scheme (what JavaScript was based on) also requires tail call optimizations as part of its spec.
Re:Bun, JavaScript, and TCO by bsdpufferfish on Sunday December 31, 2023 @08:52PM (#38829119)
> I find it surprising that the JS specification also includes optimizations an engine should implement.

Algorithmic complexity is an essential part of defining an interface.

Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @09:41AM (#38824352)
Firefox have also chosen not to implement it, right? Indeed, my impression was that Firefox were far more against the whole thing than Chrome, who did implement TCO but then removed it for various reasons.

My impression is that this is less an issue with any particular implementor, and more with the feature not being fully thought through at the beginning. A lot of the browsers (including the Edge team at the time) ended up running into issues, on top of the UX/explanatory problems. That's why there was the alternative proposal for explicit tail calls, but those didn't go anywhere.

Re:Bun, JavaScript, and TCO by pjmlp on Sunday December 31, 2023 @12:32PM (#38825748)
Firefox no longer matters, hence why I left it out.
Re:Bun, JavaScript, and TCO by ncruces on Sunday December 31, 2023 @02:57PM (#38827010)
1. Complain about market dominance.

2. Any 2% of the market doesn't matter.

3. …

Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @03:48PM (#38827406)
They said it was too hard, but now they’re adding it because of wasm, so their objection doesn’t matter.
Re:Bun, JavaScript, and TCO by kannanvijayan on Sunday December 31, 2023 @08:15PM (#38828934)
I left the spidermonkey team a while back but was there when this issue came up and I was strongly against implementing support for it. For me it wasn’t about it being “too hard” (implementation difficulty wouldn’t have been that bad actually).

It was more that it forced the implementation to elide stack frames whenever calls occurred in tail position.

That’s a semantic change to program behaviour. And one that messed with the expectations of developers.

I would have been fine with some explicit syntax for invoking that behaviour, but it seems the standards process that got it approved never really consulted developers or implementors.

Do you know why the standard committee rejected adding explicit syntax for tail returns and instead went the route of declaring that all calls in tail position must lead to stack elision? I never really bothered to find out.

Also is spidermonkey now adding TCO to JS because of wasm, or are they adding TCO to wasm?

Re:Bun, JavaScript, and TCO by pjmlp on Monday January 01, 2024 @02:31AM (#38830250)
Most likely because FP languages that have as part of the language specification don't have special syntax for it, it just works, and the debuggers are able to provide a good debugging experience.

The only FP languages that require explicit syntax, target the JVM, which lacks the support.

Re:Bun, JavaScript, and TCO by kannanvijayan on Monday January 01, 2024 @03:46AM (#38830487)
It wouldn't just work for javascript and the way it's used, though. It modifies semantics in a way that would affect the behaviour of existing programs in production environments. It would break things that currently work, and it would break tooling that currently works.

Common tooling for production error tracking (e.g. Sentry) would be greatly affected by such a behavioural change.

Functional languages "just work" with those semantics because those expectations were set up ahead of time, and tooling and developer expectations were molded around them. But JS isn't one of those languages. The tooling and developer expectations, and gargantuan amounts of existing code, has been written with the expectation that calls create stack frames.

> The only FP languages that require explicit syntax, target the JVM, which lacks the support.

Support could be added to the JVM just the same as the JSVM though - via a spec change. And just as with the JSVMs, it would be a semantic change that would alter the behaviour of existing programs in ways that would break existing tooling and make developers lives worse. It's why both of them resist it.

Re:Bun, JavaScript, and TCO by hajile on Monday January 01, 2024 @09:54AM (#38832167)
It might give different tooling output, but the tooling wouldn’t break. Likewise, the only side effect of the code itself is that some of it would get faster because functions wouldn’t need to return.

The percentage of sites affected by automated stack tools is far less than the number of other sites that would benefit from tail calls.

More importantly, this breakage already happened 8 YEARS ago in Safari and 20% of all web users already break those expectations, so companies should have already adjusted. At this point, it only serves to split the web.

Re:Bun, JavaScript, and TCO by pjmlp on Monday January 01, 2024 @02:25AM (#38830233)
Yes, those 2% only came to be because of folks pushing Chrome and Electron all over the place.

Now it is too late to save Firefox.

Re:Bun, JavaScript, and TCO by ncruces on Monday January 01, 2024 @10:15AM (#38832308)
Right.

And apparently, the best way to reverse that situation is to ignore Mozilla (or any other player with single digit market share) at the W3C?

And do what instead? Side with Apple/Microsoft as long it hurts Google?

Re:Bun, JavaScript, and TCO by trashburger on Sunday December 31, 2023 @02:12PM (#38826614)
SpiderMonkey is still used in over 2% of the browser market share, and is used in non-Firefox applications too. I'd say it matters.
Re:Bun, JavaScript, and TCO by pjmlp on Monday January 01, 2024 @02:27AM (#38830240)
Sadly it doesn't, in many places being so low means the project acceptance matrix for target browsers no longer needs to contemplate Firefox.
Re:Bun, JavaScript, and TCO by zelphirkalt on Monday January 01, 2024 @08:01AM (#38831525)
Usually though when people make shit websites or products, needlessly not adhering to browser standards that would easily work in basically all modern browsers, because they cannot be bothered or don't have a clue what they are doing.
Re:Bun, JavaScript, and TCO by spankalee on Sunday December 31, 2023 @02:33PM (#38826813)
What "political" reasons?

My understanding of the situation is that it's entirely technical issues that came up after implementing.

Re:Bun, JavaScript, and TCO by magicalist on Sunday December 31, 2023 @03:17PM (#38827161)
Yes, what's really important here is that TCO was added to the spec before the modern TC39 process was adopted. Had implementation and usage experience been required before it shipped in the spec, this conversation would have been concluded 9 years ago.
Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @03:47PM (#38827399)
There were no technical arguments from Google. They implemented tail calls and performance was fine. Furthermore, wasm required them to add the functionality back to the jit.

MS complained that windows APIs made it slow, but first, they should fix their OS. Second, chrome didn’t have those same issues on windows. Third, they now use chrome, so it’s no longer an objection.

Firefox complained that it was work, but they’re also doing it for wasm.

This only leaves the stack trace argument, but the biggest cases for tail calls are where you’d already be forced to a loop and nobody complains that loops don’t have stack traces.

Further, you already have the same issues with async stack traces and activating shadow stacks in debug mode works just as well as those async traces.

It’s all about chrome devs digging in their heels because they took a side dumb argument and won’t just swallow their pride and implement what developers want and the spec demands.

Re:Bun, JavaScript, and TCO by Rapzid on Sunday December 31, 2023 @03:57PM (#38827456)
> Firefox complained that it was work

LOL, as they do.

Re:Bun, JavaScript, and TCO by chrismorgan on Sunday December 31, 2023 @09:25PM (#38829268)
Anything to do with tail calls in WASM is likely to be completely irrelevant to proper tail calls in ECMAScript: they’ll be separate pieces of code with different reasons and balances.

Moreover, tail call elimination is explicit in WASM. The initially-defined call and call_indirect instructions aren’t allowed to do tail call elimination, and the tail-call proposal added return_call or return_call_indirect which require it. The situation is thus more like the (now inactive) TC39 Syntactic Tail Calls proposal. No need to worry about the debugging or performance implications.

> Firefox complained that it was work, but they’re also doing it for wasm.

They said it was impossible to implement across realms with their membrane-based security model. That is: “we could do it in most cases, but you’ve said we have to do it in all cases and we can’t do that without replacing a fundamental and pervasive part of our engine, which we certainly don’t want to do for something we and others aren’t convinced is even a good idea”. But in WASM, any tail calls are to the same WASM program, where this isn’t a problem.

Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @09:38PM (#38829341)
WASM runs in v8 on Chrome. If you have to implement the bytecode for one, it should work for both. Chrome used to have semantic tail calls for JS implemented too.

FF runs WASM on Spidermonkey. If the security model is broken by JS, there's not a great reason to believe it won't also be broken for the same JIT when running WASM.

Re:Bun, JavaScript, and TCO by runarberg on Sunday December 31, 2023 @02:46PM (#38826919)
I think the most cited reason they give is diminished developer experience. That is when developers write a recursive function without intending it to be tail call optimized, they loose their call stack. In theory this makes debugging harder. However I don’t—and others interested in JavaScript design—don’t buy this reasoning. There is little—if any—data showing this happens to developers in real life.

I also believe that Google’s representatives at TC-39 (and Mozilla’s to a lesser extent) knows this. Meaning they have other reasons for not implementing TCO. My personal theory is that they are very much against expending the functional paradigm in JavaScript. TC-39 has been very hostile towards any proposals which would expand the functional paradigm in JavaScript. The decision to advance the hack style pipeline operator (which uses a placeholder) over the F# (functional/tacit) operator is a prime example of this.

This, I believe, is purely political.

Re:Bun, JavaScript, and TCO by odyssey7 on Sunday December 31, 2023 @03:49PM (#38827408)
Sadly I sense something amuck against the functional paradigm as well.

Paul Graham wrote back in 2001 that Lisp was a secret weapon for building a startup due to the developer productivity gains. https://paulgraham.com/avg.html

As a corollary, the more lisp-like JavaScript is, the more it reduces barriers to entry for launching a tech company, promoting more software engineers into potential new competitors.

Could it be that Java and Python are taught in universities because some members of the industry prefer making it more cumbersome for new grads to launch a company? Having significant barriers to entry is business strategy 101.

Re:Bun, JavaScript, and TCO by jart on Sunday December 31, 2023 @04:34PM (#38827699)
Are you saying that knowing LISP makes you like an instant Paul Graham? If only.
Re:Bun, JavaScript, and TCO by klyrs on Sunday December 31, 2023 @07:14PM (#38828616)
Ew, I hope not. I know lisp, I do not want to be Paul Graham.
Re:Bun, JavaScript, and TCO by odyssey7 on Sunday December 31, 2023 @04:42PM (#38827756)
Nice try
Re:Bun, JavaScript, and TCO by sroussey on Sunday December 31, 2023 @06:34PM (#38828429)
Having worked on debuggers in JS land I can tell you that it would generate lots of bug reports.

Does the developer expect a call stack?

Does the developer NOT expect a call stack? Maybe they want to see if the optimization was activated.

Bug reports either way.

That said, all sorts of weird changes happen when a debugger is enabled.

The jit will eliminate various pieces of code and remove variables from scopes, but you better put them back if the debugger stops! This one I remember in Firebug. Oops!

¯\_(ツ)_/¯

Re:Bun, JavaScript, and TCO by hajile on Monday January 01, 2024 @12:09PM (#38833322)
Safari has enabled proper tail calls for 8-9 years now and they haven’t caused issues despite Safari having 20% of the worldwide browser market.
Re:Bun, JavaScript, and TCO by runarberg on Monday January 01, 2024 @07:30PM (#38836675)
I guess Safari doesn’t have this large a share of developers, who are the main concern here. But I guess we will truly see if this is an issue as Bun increases in popularity.
Re:Bun, JavaScript, and TCO by hajile on Tuesday January 02, 2024 @10:39AM (#38842691)
The major Google "objection" was automated trace loggers. When something goes wrong, they grab the stack trace and ship it off to the developers.

In this particular case, devs definitely see the Safari traces when bugs pop up.

Re:Bun, JavaScript, and TCO by sroussey on Wednesday January 03, 2024 @10:24PM (#38862598)
I feel like it could be represented in the trace or the debugger or both and eliminate everyone issues.

Devs definitely don’t like surprises, but also absolutely hate their tools not telling the truth.

Re:Bun, JavaScript, and TCO by odyssey7 on Sunday December 31, 2023 @11:00AM (#38824935)
I don’t think the example is particularly good. TCO is essential in functional programming, where recursion shines, but the example given is an impure function which mutates its input parameter by calling Array.prototype.push. Basically, this isn’t a demonstration of the paradigm for which TCO is required.

We’ll never know how big of a role TCO could have played in JavaScript over the past several years, because it hasn’t been available outside of some narrow contexts.

Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @11:31AM (#38825193)
I agree that TCO is essential in functional languages where loops and mutability are disallowed or at least heavily discouraged, but Javascript is not one of those languages. In Javascript, both mutation and and loops are very simple, and as I think the article demonstrates, often the clearest ways to express an idea.

Where recursion is clearer (for example, when dealing with recursively nested data structures), the clearest expression of a function usually isn't tail recursive - that often requires rewriting the function to put more state into the function arguments.

This means that tail recursion rarely matches with patterns used regularly in Javascript. That's not to say it's useless - if you want to keep to a particular functional style, or if you're compiling to Javascript from a language that emphasises recursion, then it's a useful tool to have. But in the former case, you're generally going to struggle with browser engines not being optimised for this style, and in the latest case, you're probably better off targeting WASM directly.

Re:Bun, JavaScript, and TCO by odyssey7 on Sunday December 31, 2023 @12:29PM (#38825712)
I agree with everything you wrote.

There’s an element in this that gets at why V8’s omission of TCO feels to me like suppression of functional programming. JavaScript is an incredible widely used multi-paradigm language, to the point that I would recommend for universities to replace Python and Java with JavaScript in their curriculums. It’s just so practical for building software systems, has amazing tooling, connects you to a rich community, and allows you to cover so much academic ground. JavaScript has been a rocket fuel for promoting a vibrant, diverse software engineering ecosystem.

Although you can choose to write a loop and do things imperatively in JavaScript, you don’t have to. The ECMAScript spec is inclusive toward the functional programming paradigm by requiring that engines provide for proper tail calls. Functional programmers should be allowed to have their cake and eat it too! But TCO isn’t implemented in V8, and the workaround is to just switch from functional to imperative programming.

Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @01:04PM (#38826066)
I don't think it's the lack of TCO that's the thing holding JS back from getting the next great functional language. There's no structural pattern matching, there's no immutable data structures, there's nothing in the way of convenient syntax sugar like currying.

You can mimic all of that, but it's painful, it's not something that Javascript is that great at. Which is fair enough, it doesn't need to be perfect at everything, that's why there's different languages. If you want functional programming in the browser, try using Elm or ReasonML. Both of those are fairly easy to use, I think there are even online playgrounds for both to get started.

Re:Bun, JavaScript, and TCO by odyssey7 on Sunday December 31, 2023 @03:13PM (#38827127)
I think it’s not as widely recognized as it could be just how forward-looking ECMAScript was in introducing language updates in the mid 2010s. For instance, arrow functions make it natural to work with partial application, a currying-adjacent technique.

  const times = a => b => a * b
  const double = times(2)
  const twiceFour = double(4)
As a language feature, a function to curry a given function is different from proper tail calls in that it can be implemented as a JavaScript function rather than needing to be built into the JavaScript engine. Similarly, Haskell’s own curry function is imported from its standard prelude. Leaving this detail up to language users allows a diversity of approaches and vibrancy in the community. Lodash has had an implementation for a while: https://github.com/lodash/lodash/blob/0843bd46ef805dd03c0c8d.... (Edit, found better example.)

Structural pattern matching can be very elegant and it would be nice if ECMAScript offered it. Object destructuring has been added to the language, and that feature could be seen as a stepping stone for adding structural pattern matching in a later version. Proper tail calls however are more fundamental to the paradigm of functional programming, since they are necessary for iterative algorithms to work as well functionally as they do imperatively.

Re:Bun, JavaScript, and TCO by MrJohz on Sunday December 31, 2023 @07:56PM (#38828841)
In Haskell, all functions are syntactically and semantically curried. That is, a function that takes two arguments is essentially identical to a function that takes one argument, and returns a new function that returns a second argument. (In fairness, part of this is the laziness of Haskell, and a language like OCaml which also uses currying behaves slightly differently, but still similarly enough.) The `curry` function is not a library implementation of currying, it's a way of unpacking tuples into arguments.

In Javascript, a function that accepts two arguments is meaningfully different from a function that accepts one argument and returns a new function that accepts a second argument. Both semantically, but more importantly syntactically. It's possible to overcome this at the library level as you say, but it usually has performance and usability issues - error messages start looking very funky! It also often doesn't play well with other Javascript features, such as the famous `map(parseInt)` issue.

That's not to say that currying isn't possible in Javascript, just that it's a feature that doesn't play well with the rest of Javascript. If you really want currying when you're coding, you're probably better off choosing another language - currying will work so much better, and you will have so many more advantages.

What I've said is specific to currying, but in my experience, this is generally true. You can use certain functional idioms in Javascript (particularly higher order functions), but it isn't really a functional programming language. Adding features to make Javascript more functional makes the language a lot more complex, but it won't magically turn Javascript into a good functional language. Therefore, it doesn't make sense to include things in Javascript just because they're useful in a functional context, it's first important to validate that these features are useful in a standard Javascript context.

Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @09:29PM (#38829296)
JS works alright with currying, but I think manual currying is the best way to do it with the language (and it's not that inconvenient).
Re:Bun, JavaScript, and TCO by Rapzid on Sunday December 31, 2023 @04:06PM (#38827523)
Shout out to F# in the browser via Fable too.
Re:Bun, JavaScript, and TCO by miloandmilk on Sunday December 31, 2023 @05:10PM (#38827951)
I was looking for an alternative to rescript and literally just started looking at Fable this week - and absolutely love it in conjunction with Elmish.
Re:Bun, JavaScript, and TCO by hajile on Sunday December 31, 2023 @04:38PM (#38827722)
TC39 hates FP.

They have a stage 2 record/tuple proposal. Records are far more optimizable than JS classes since they enforce concrete types and can’t add/remove fields.

Instead, they spent massive amounts of time on private fields which most devs didn’t want (most pushback any JS feature has ever received by a large margin) AND one that completely breaks proxies which are used by all kinds of libraries.

Even Java is getting pattern matching before JS.

They’ve decided pipe operators are either going to be an abomination or they will be cancelled entirely. So of this completely disregards the opinions and use cases of the FO devs that will be using them.

This applies to all the FP proposals on their list. They get delayed, canceled, and neutered while niche or even bad features get implemented instead.

Re:Bun, JavaScript, and TCO by wk_end on Sunday December 31, 2023 @07:51PM (#38828812)
It’s a shame, because records and tuples are enormously helpful when trying to optimize React, given how it uses reference equality on objects to bust memoization.
Re:Bun, JavaScript, and TCO by o11c on Sunday December 31, 2023 @03:34PM (#38827311)
The real problem, of course, is that in the cases where compiler-based TCO is possible, the user can trivially refactor the function to use a loop.
Re:Bun, JavaScript, and TCO by tonyg on Sunday December 31, 2023 @06:46PM (#38828500)
This is not true.

The compiler can trivially turn this into a jump, but the developer doesn't have enough context to construct any kind of loop:

    function ap(f, v) { return f(v); }
Re:Bun, JavaScript, and TCO by tikhonj on Sunday December 31, 2023 @04:07PM (#38827529)
Tail calls also matter for code in continuation-passing style (CPS).

This matters for some styles of programming (callbacks/promises/monads/etc), but it's also very useful for code emitted by compilers and DSLs. It's much easier to encode complex control flow with CPS than just with the basic constructs JavaScript supports.

Even for hand-written code it can be pretty important. It's easy to imagine rewriting simple tail-recursive functions in an imperative style, but it quickly gets much harder, especially if your problem naturally decomposes into mutually recursive functions: that is, instead of a function calling itself, you have multiple functions calling each other, often with a bunch of additional computation between each call. I've run into this when writing parsers as well as custom algorithms for constraint-satisfaction kinds of problems. (Which are pretty common!)

Re:Bun, JavaScript, and TCO by tonyg on Sunday December 31, 2023 @07:11PM (#38828599)
> an algorithm that elegantly fits a recursive relationship is rarely one that naturally fits the tail-call paradigm.

That's because tail calls are structured gotos (with arguments). They're not really about recursion or even iteration.

> what is the advantage of [proper tail calls]?

There's a loss of expressiveness [1] without them, similar to the loss of expressiveness when there's no garbage collector.

> if [using proper tail calls] is almost always less performant, it probably isn't a very useful choice.

Don't assume PTC is less performant. There's no intrinsic reason for it to be. After all, the machine should be doing (slightly) less work: a goto instead of a call. Retrofitting it to an existing system can of course lead to a poor implementation, but it is not inherently a slow construct.

[1] Felleisen, Matthias. “On the Expressive Power of Programming Languages.” Science of Computer Programming, vol. 17, no. 1--3, 1991, pp. 35–75, https://doi.org/10.1016/0167-6423(91)90036-W .

Re:Bun, JavaScript, and TCO by MrJohz on Monday January 01, 2024 @03:59AM (#38830541)
To be clear, I'm not talking about PTC/TCO in general in this comment, I'm talking about it specifically in the context of Javascript, and in the context of the common patterns of Javascript usage.

That is, PTC doesn't just need to be powerful than other forms of call, it needs to be more useful day-to-day than other ways of writing the same logic. I think this article shows that, at least with the common recursive examples, that's rarely the case - it is pretty much always clearer and significantly quicker to use loops and Array methods than it is to rely on PTC and recursion.

You make a good point that there are uses for PTC outside of recursion, and that there are things you can do with it that can't be done with existing constructs. I'm sure that's true, but in my experience, the things people want to do with these tools tend not to fit well with the other features of Javascript, such as the high degree of mutation, and the dynamic nature of the language. At which point, it's probably more useful to create a compile-to-Javascript language instead that uses these sorts of features internally.

But with the rise of WASM (which has PTC as a proposal that I believe some groups have already implemented), it makes a lot more sense to use WASM as a target instead. There, you have a lot more control over exactly what gets executed and how, along with generally smaller and faster code. The exception right now is obviously DOM manipulation, but with the GC work being done right now, the path is opening up to getting easier access to the DOM directly in WASM.

Re:Bun, JavaScript, and TCO by zelphirkalt on Monday January 01, 2024 @07:57AM (#38831513)
The article does not show much except TCO existing with Bun and JavaScriptCore. It uses a not very suitable mutable data structure to mutate it in each iteration. I would say for that example it is almost better to use the for loop, since it looks very imperative anyway and using recursion to do mutating procedure calls does not give much benefit. It is a not so well chosen example.
Re:Bun, JavaScript, and TCO by MrJohz on Monday January 01, 2024 @08:03AM (#38831538)
That's mostly the point I'm trying to make! What would you see as a more convincing example of TCO in this context?
Re:Bun, JavaScript, and TCO by zelphirkalt on Tuesday January 02, 2024 @08:42AM (#38841498)
Perhaps an example using a persistent functional data structure would be good, but probably also more complex.

Instead you could do some simpler example like factorial or fibonacci, which would usually run into a stack overflow, but due to Bun being based on JavaScriptCore not running into one.

At first I wanted to suggest to implement Dijkstra's algorithm for finding shortest paths from a specific node to all other nodes, but then I found a mutation in my own implementation for updating the distances and routes to nodes tables, so I did not want to suggest something I hadn't fully done myself.

But maybe, if you had something like functional hashes or similarly usable for the problem, you could do it. So I will link it here: https://notabug.org/ZelphirKaltstahl/guile-algorithms/src/83...

Note, that I put a "warning" in there, at the place, where it still uses mutation. Potentially this could hinder parallelization. Not sure if applicable in this specific problem, but in general, if you want to parallelize an algorithm, it not having any mutation makes it much easier to parallelize it and use our modern machines, which have multiple cores.

So shame on me for not having a mutation-free version yet ;)

Re:Bun, JavaScript, and TCO by akoboldfrying on Sunday December 31, 2023 @11:08PM (#38829674)
>I think this article actually does a really good job of explaining why TCO hasn't really been an important part of the JS ecosystem.

Nicely put. TCO is a bit like a guitar solo: more fun to implement than it is useful/enjoyable to the intended recipients.