Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

C# can turn lambdas into expression trees at runtime allowing libraries like EF to transform code like `db.Products.Where(p => p.Price < 100).Select(p => p.Name);` right to SQL by iterating the structure of that code. JavaScript ORMs would be revolutionized if they had this ability.


Good answer. To elaborate on it and provide examples.

In languages that don't have expression inspection capabilities you have to replace the `(p) => p.Price < 100` part with something that is possible for the language to inspect.

Normally it's strings or something using a builder pattern.

For example, in TypeORM:

    queryBuilder.where("product.price < :price", { price: 100 })
And in Mongoose:

    Product.find({ price: { $lt: 100 } });
The LINQ-ish version would be:

    Product.find((p) => p.price < 100);
--

Similarly, for Ruby on Rails:

    Product.where("price < ?", 100)
Ruby's Sequel overloads operators to have a more natural syntax:

    DB[:products].where { price < 100 }
But the "lambda" syntax would be:

    Product.where { |p| p.price < 100 }


Sadly expression trees got out of love in modern .NET and it remains to be seen how much they will ever improve them.

https://github.com/dotnet/csharplang/discussions/158


The last comment thread by agocke is interesting. I've thought before that it's unfortunate that LINQ and expression trees were implemented before the move to Roslyn, because if they'd been implemented afterwards they could maybe have just directly used the same object model that the compiler itself uses, which could make it more sustainable to keep them in sync with language changes.


Java has two somewhat related projects in this space, and it does add a substantial cost to language changes (assuming you commit to keep expression trees up to date). https://openjdk.org/projects/babylon/ is the most interesting to me, as a linq+++ potentially.


Yes, being on both ecosystems most of the time, means I get to have lots of nice toys both ways, with them counter influencing each other all these years.


An interesting thing about expression trees is that with JIT they can be compiled at runtime, but with AOT they are interpreted at runtime.


> JavaScript ORMs would be revolutionized if they had this ability.

Is this possible in JavaScript?


Not easily. There's no built-in way to access the abstract syntax tree (or equivalent) of a function at run time. The best thing you can do is to obtain the source code of a function using `.toString()` and then use a separate JS parser to process it, but that's not a very realistic option.


There is a limited form of such "expression rewriting" using tagged template strings introduced in ES2015. But it wouldn't be particularly useful for the ORM case.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: