Draco-lang / Language-suggestions

Collecting ideas for a new .NET language that could replace C#
75 stars 5 forks source link

Let ... in construct #51

Open LPeter1997 opened 2 years ago

LPeter1997 commented 2 years ago

Motivation

When discussing the syntax for the matching construct in #44, the position of the keyword came up. Should it be when (expr) { ... } or expr when { ... }? The former would be consistent with the rest of the constructs. It came up that the latter is useful when matching on long expressions, as when (this is a very long expression) { ... } is not too fluent.

This discussion gave me an idea for proposing the let ... in construct for the language, as I believe it would resolve the problem for long expressions - and keeping the keyword consistently -, make the language a bit more fluent with expressions and help in other constructs with long expressions, not just the matching construct.

The feature

The general syntax would be (keywords could change):

let name = boundExpr in evalExpr

which would be equivalent to:

{
    val name = boundExpr;
    evalExpr
}

So in essence, this would bind a value to a name, local to the expression after the in keyword.

Examples of use

Match constructs

The problem initiating this proposal about long expressions in the match construct.

func foo(x: T): U =
    let matched = here comes the extremely long expression in
    when (matched) {
        ...
    };

Shortening other constructs

You couldn't factor out the discriminant without a block otherwise (ignore that I'm working with ints).

func solve_quadratic(a: int, b: int, c: int): (int, int) =
    let disc = b * b - 4 * a * c in
    if (disc >= 0) 
        (
            (-b + sqrt(disc)) / (2 * a),
            (-b + sqrt(disc)) / (2 * a)
        )
    else (0, 0);

The former construct can be rewritten with pattern matching, but this demonstrates, that a let ... in could be reused at more places than just that "special" case for when.

To be decided

Since we already have var and val, we could decide to extend the syntax for val to support this. I wouldn't consider var for this, as mutating the bound value here feels very wrong.

We can also just decide to go with let.

Binto86 commented 2 years ago

I don't really feel like the in after the expresion makes much sence, wouldn't it make more sence to have expresions as special variables declared with the keyword let? Or maybe some keyword that shows it is an expresion like exp but the name of the keyword doesn't really matter

LPeter1997 commented 2 years ago

Syntax is subjective, but this is the syntax most languages go with when having a construct like this (like ML languages).