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

Allow evaluation and pattern matching within guards (what Haskell calls "pattern guards") #680

Closed
steveklabnik opened this issue Jan 21, 2015 · 2 comments
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.

Comments

@steveklabnik
Copy link
Member

Issue by kmcallister
Tuesday Mar 11, 2014 at 22:08 GMT

For earlier discussion, see rust-lang/rust#12830

This issue was labelled with: B-RFC, I-enhancement in the Rust repository


What Rust calls "pattern guards" are just called "guards" in Haskell. Pattern guards in Haskell allow additional evaluation and a refutable pattern match. If that pattern match fails, it's as if a regular guard returned false. Here's an example, adapted from the HTML5 tokenizer I'm working on.

fn process_char(&mut self, chars: CharSource) {
    match self.state {
        TagOpen => match chars.next() {
            '/' => { self.state = EndTagOpen; }
            c if (Some(a) <= c.to_ascii_opt()) => { do_something(a.to_lower()); }
            c if other_condition => { ... }
            _ => parse_error()

(I'm not advocating for this particular concrete syntax, just trying to get the idea across.)

One can always refactor to avoid the fancy guard, but in general it can produce ugly, hard-to-follow trees of nested matches. In this case I would love to have a single match per tokenizer state which closely follows the specification.

Pattern guards have proven tremendously useful in GHC and were one of the few GHC extensions accepted into Haskell 2010. I think Rust could benefit just as much.

@glaebhoerl
Copy link
Contributor

See this reddit discussion which suggests that the right syntax for this might be to simply extend our if guards to allow if let, just like top-level ifs.

@petrochenkov
Copy link
Contributor

Closing in favor of #2294

@Centril Centril added the T-lang Relevant to the language team, which will review and decide on the RFC. label Jan 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.
Projects
None yet
Development

No branches or pull requests

4 participants