3 ms·
I don't understand the second example: fn some_on_even(val: int) -> Option<int> { match val { // Matches an even number. even if even % 2
by 1_player 12y ago
I don't understand the second example:
fn some_on_even(val: int) -> Option<int> {
match val {
// Matches an even number.
even if even % 2 == 0 => Some(even),
// Matches anything else.
_ => None
}
}
Where is even coming from? Is that a typo, or that construct is actually defining a variable even from val if val % 2 == 0 ?
That seems absurdly confusing to me.
- dbaupp 12y agoIt's binding a variable `even`, and then using a pattern guard to conditionally take that arm depending on the value of `even`; it's (basically) the same as match val { even => { if even % 2 == 0 { Some(even) } else { None } } _ => None } which is an absurd construct (and the example pretty absurd too). It should be written as just if val % 2 == 0 { Some(val) } else { None } or, if you really like the formatting a match provides, just avoid creating a new name binding match () { _ if val % 2 == 0 => Some(val), _ => None } `match` and pattern guards make far more sense when not just binding directly to a single variable like that, e.g. let val: Option<int> = ...; match val { // even Some(x) if x % 2 == 0 => Some(x), // odd Some(x) => Some(x + 1), None => None } (Of course this may still be clearer using `.map` instead `match` but it's a better example than the original one.)
- yawaramin 12y agoTo answer your question, it's the latter. That's what pattern matching is, basically.
- ww520 12y agoMatch has the syntax of: match value { pattern(variable-binding) [if guard-condition] => matched result ... } In this case, the first 'even' is variable declaration binding it to val. The next 'if even % 2 == 0' is the guard expression, qualifying the range of values of the 'even' variable. The 'if' is a keyword, indicating a guard expression. The next '=> Some(even)' returns an Option type wrapping the matching 'even' values. The wildcard _ matches whatever left, which is the non-even values of val.