alshdavid / BorrowScript

TypeScript with a Borrow Checker. Multi-threaded, Tiny binaries. No GC. Easy to write.
1.45k stars 16 forks source link

Inline / pipeline functions whenever possible #32

Closed Isaac-Leonard closed 1 year ago

Isaac-Leonard commented 3 years ago

In Typescript we can currently do something like this:

arr
  .map(x(=) > x* 2 )
  .map(x() => x*x);

From what I understand most javascript interpreters will run the first map to completion before starting the second as javascript is too dynamic to allow for proper analysis of pure functions. Would it be possible to investigate limiting certain dinamicness of borrowScript to allow for merging each step of the above code in compilation so the array is not iterated twice?

SuperSonicHub1 commented 3 years ago

So you want the code to become something like this?

arr.map(x => x * 2 * x)

Honestly, if you want something like this, it would be much better to use generators instead:

function* map(iterable, callback) {
    for (const x of iterable) {
        yield callback(x)
    }
}

map(map(arr, x => x * 2), x => x * x)

Perhaps we should make ECMAScript generators have a greater focus in BorrowScript?

Isaac-Leonard commented 3 years ago

While my example is simplistic there's more complicated ones where being able to automatically pipeline pure functions would be useful. I don't really see the connection to generators here,. The transformation that I'm considering just removes the unnecessary double iteration of the array and would mainly be a compiler optimisation aided by enforcing some constraints on what code in the callbacks can do.

SuperSonicHub1 commented 3 years ago

From what I understand most javascript interpreters will run the first map to completion before starting the second

Generators solve this exact problem; both maps are running at pretty much the same time. The first value of the array goes through the first map, and then immediately through the second.

I guess I'm not really following then. Are there any existing languages that do the optimizations you're describing so that I can read about them?

Isaac-Leonard commented 3 years ago

Alan lang does it, pretty sure Julia does too along with other functional languages