Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Created October 25, 2012 01:48
Show Gist options
  • Select an option

  • Save brendanzab/3950026 to your computer and use it in GitHub Desktop.

Select an option

Save brendanzab/3950026 to your computer and use it in GitHub Desktop.
A proposal for how to enable the use constants with pattern matching

At the moment one of the limitations of pattern matching is the inability to use variables in the scope of the match.

pcwalton suggests using const:

const origin: Point = Point { x: 0, y: 0 };

let foo = Point { x: 12, y: 42 }

match p {
    const origin          => io::println(~"the point lies at the origin"),
    Point { origin.x, y } => io::println(fmt!("the point lies on the x axis, at y=%?", y)),
    Point { x, origin.y } => io::println(fmt!("the point lies on the y axis, at x=%?", x)),
    const foo             => io::println(~"the point is at the point \"foo\""),
    Point { x, y }        => io::println(fmt!("The point is at (%?, %?)", x, y))
}

nmatsakis suggests using the == operator:

const origin: Point = Point { x: 0, y: 0 };

let foo = Point { x: 12, y: 42 }

match p {
    == origin             => io::println(~"the point lies at the origin"),
    Point { origin.x, y } => io::println(fmt!("the point lies on the x axis, at y=%?", y)),
    Point { x, origin.y } => io::println(fmt!("the point lies on the y axis, at x=%?", x)),
    == foo                => io::println(~"the point is at the point \"foo\""),
    Point { x, y }        => io::println(fmt!("The point is at (%?, %?)", x, y))
}
@bstrie
Copy link
Copy Markdown

bstrie commented Oct 25, 2012

How about something that looks like capture clauses:

match p |origin, foo| {
    origin                => io::println(~"the point lies at the origin"),
    Point { origin.x, y } => io::println(fmt!("the point lies on the x axis, at y=%?", y)),
    Point { x, origin.y } => io::println(fmt!("the point lies on the y axis, at x=%?", x)),
    foo                   => io::println(~"the point is at the point \"foo\""),
    Point { x, y }        => io::println(fmt!("The point is at (%?, %?)", x, y))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment