Quantcast
Channel: Possible ways to determine reach of implicit lambda expressions - Programming Language Design and Implementation Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by tarzh for Possible ways to determine reach of implicit lambda expressions

$
0
0

Here's one: integrate the parser and type-checker so that only token trees (lexed tokens and parentheses groups) are initially parsed, then the compiler further parses outer expressions and type-checks them before parsing inner expressions.

When an expression gets parsed to a function call, the compiler will type-check the function and, whichever arguments are supposed to be closures, will be parsed as implicit closure expressions unless they are explicit (either start with x -> or identifiers which resolve to lambda expressions). When an expression gets parsed to the assignment, if the assigned-to identifier is a variable, the assigned value will be parsed as an implicit closure unless it's explicit.

Pros: this gives you maximum flexibility: you can create expressions like this, which aren't otherwise possible:

functionWhichTakesClosure(functionWhichTakesRegularArgument(_))// Desugars tofunctionWhichTakesClosure(x -> functionWhichTakesRegularArgument(x))functionWhichTakesRegularArgument(functionWhichTakesClosure(_))// Desugars tofunctionWhichTakesRegularArgument(functionWhichTakesClosure(x -> x))

However, I'd say this is a bad idea. Because it creates a situation where the compiler is smarter than the developer, so that it generates code when it should throw a type error. What if someone changes functionWhichTakesRegularArgument so that it actually does take a closure (you know that in practice, functions won't have these obvious names)? What if functionWhichTakesClosure no longer takes a closure, the error message "_ expression but none of the outer calls take a closure" isn't very helpful (or if one of the outer calls do take a closure, that will be even less helpful). Moreover, there are still ambiguities: what if functionWhichTakesRegularArgument takes a generic parameter, will it be inferred to a closure? You can resolve them (like say, generic types which can't be inferred will never be parsed as implicit closure, or just simplify so that even generics which do resolve to closure can't be parsed implicitly), but that only creates more complexity and confusion.

In this case, Scala's and Kotlin's simple solution (just desugar the inner-most parenthesis or braces into an implicit closure) is the best. Because it doesn't require type knowledge to understand; when the developer does mess up and pass an inner closure, they are breaking a simple rule, which is a lot easier to spot than breaking a more complicated one.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>