Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Let-in binding syntax #11514

Closed
lucian1900 opened this issue Jan 13, 2014 · 5 comments
Closed

Let-in binding syntax #11514

lucian1900 opened this issue Jan 13, 2014 · 5 comments

Comments

@lucian1900
Copy link

I thought it would be interesting to be also able to bind a symbol only for the scope of the following expression, much like "let ... in" syntax in Haskell/ML.

So this

let a = 1 in a + 1

would be equivalent to this

{
    let a = 1;
    a + 1
}

Such syntax would also more closely align with match, where the symbols are scoped only in that arm of the match.

I've felt the need for this trying to write Some(&1) and having to fall back binding it separately, but I understand that will be fixed.

@huonw
Copy link
Member

huonw commented Jan 13, 2014

This (or something equivalent) can be written with a macro:

#[feature(macro_rules)];

macro_rules! bind {
    ($( $p:pat $(: $t:ty)* = $val:expr );* in $rhs:expr) => {
        {
            $( let $p $(: $t)* = $val; )*
            $rhs
        }
    }
}

fn main() {
    let v = bind!(a: int = 1; b = 2 in a + b);
    println!("{}", v);
}

Does that appear to cover what you are thinking of?

@lucian1900
Copy link
Author

Yep, that's pretty much it. It would look a bit ugly when used with a block, but not too bad I guess.

Is it too much to add this to syntax?

@huonw
Copy link
Member

huonw commented Jan 13, 2014

The macro could be tuned to allow bind!(a = 1 in foo(a); bar(a); baz(a)); without needing { } (probably as simple as $( $rhs: expr );* in the definition and then $($rhs);* at the point of use.

And yes, to me, this seems like a poster boy for macros/syntax extensions, rather than hard-coding extended syntax into the language.

@lucian1900
Copy link
Author

It's quite a common feature of let, in ML/Haskell and Lisps, which is why I was thinking it would be nice if it were actual syntax. I was certainly surprised it didn't exist.

Of course, I can work with a macro as well.

@huonw
Copy link
Member

huonw commented Jan 15, 2014

I'm going to close this in favour of macros.

Anyone who feels particularly strongly (preferably with a good reason why a macro is insufficient) can comment/reopen.

@huonw huonw closed this as completed Jan 15, 2014
flip1995 pushed a commit to flip1995/rust that referenced this issue Oct 21, 2023
…les, r=flip1995

triagebot no-merges: exclude "Rustup"s, add labels

rust-lang/triagebot#1720

changelog: none
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants