0

I want to try and write a match with variables as the condition ie

fn sub(x: uint ,y: uint) -> Vec<char> {
    let mut out: Vec<char> = Vec::new();
    out.push('-');
    let mut xw: bool = true;
    let mut yw: bool = true;
    let mut count: uint = 0;
    while xw || yw {
        match count {
            x => {out.push('2'); xw = false;}
            y => {out.push('1'); yw = false;}
            _ => {out.push('_');}
        }
    count+=1;
   }
etc

I get "error: unreachable pattern "...

Is there a way to do this nicely or am I back to if statements?

thanks in advance

jonnydedwards
  • 180
  • 10

1 Answers1

0

You are kind of stuck with ifs (although you can use them as guards in the match). The most readable option is probably a regular if chain.

This is how you would need to write the pattern match to make it work:

fn sub(x: uint, y: uint) -> Vec<char> {
    let mut out: Vec<char> = Vec::new();
    out.push('-');
    let mut xw: bool = true;
    let mut yw: bool = true;
    let mut count: uint = 0;
    while xw || yw {
        match count {
            a if a == x => { out.push('2'); xw = false; },
            b if b == y => { out.push('1'); yw = false; },
            _ => out.push('_')
        }
    count+=1;
   }
   // etc
   out
}

the problem with your code is that your x is not the same x that you're passing to your function. Instead the x in the match is saying "take whatever value count has and bind it to a name x".

This means that the first condition will always match (in functional programming parlance, it's "irrefutable"), so the compiler is alerting you that next branch of the match is unreachable.

As said, you can avoid this with a "guard", i.e. the if a == x in this code:

match count {
     a if a == x => ...
Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
  • If one really wants the guards, writing this as `match () { _ => if count == x ...` seems clearer to me, but just a normal `if`/`else` chain seems good too. – huon Sep 01 '14 at 22:48
  • @dbaupp yes, sorry... I should have been clearer when I said "you're stuck with ifs" that I was just giving an alternative to the normal if chain – Paolo Falabella Sep 02 '14 at 07:19