Practicing match and enum functions

I have a code here that compares two numbers in an array. it works but I am wondering how I can rewrite this code using the match function, or structs or enums.



fn main() {
    let a = [0,0,0,0,0];
    let b = [3,6,10,-6,32];
     //index,alice and bob change values. use mut
    let mut index: usize  = 0 ;
    let mut alice: i8 = 0;
    let mut bob: i8 = 0;
     //checking length of Array
    if a.len()!= b.len(){
        panic!("A and B must have the samen length!" );

  }
    
while index < a.len() {
        // println!("value  a is :{}",a[index] );
        // println!("the value b is {}",b[index] );
        if a[index] >  b[index]{
             alice = alice + 1;
        }
         else if a[index] < b[index] {
            bob =  bob + 1;
        }
        index = index + 1;
    }
    println!("Alice has: {} points", alice);
    println!("Bob has {} points", bob );

And aso while is not usually recommended, it's probably bad habits, but I couldn't get it to work with the for or loop.

Please edit your post to use a code block rather than a quote block. See more here.

```
// your code here
```

Thank you! :slight_smile:

You can match of the result of a[index].cmp(b[index]) if you want.

You can also skip the index alltogether, by looping over a zip of a and b.

Here's an example in the playground:

If you want to get more functional / funky you could skip the for-loop and use a fold over the ziped iterator instead, but if that would be an improvement or not is entirely a matter of taste.

@kaj Thank you very much. That was fast response.
I've seen this in cmp in the guessing game example and I thought it meant compile. Also can I also write _=>() instead of "Ordering::Equal => ()? This is awesome, I also get to try using crates as well.
for (ai, bi) in a.iter().zip(&b) does this mean you are iterating through a and b at the same time. zip combines the two?. and since you have ai can one for example write println!({},a2) without using square brackets?

I am not familiar with the fold.

cmp is short for "compare". See docs for cmp and Ordering.

Yes, you can always use _ => ... as the last branch in a match statement, to match any remaining case.

Yes, the zip function combines two iterators (or an iterator and an iterable) to a single iterator over pairs of values from the original iterators. The docs explains it better than me.

The variables ai and bi in my example is nothing magic, just the iterator variables in the for loop. So no, you cant magically use a1 or a2 as shorthand for a[1] or a[2].

1 Like

That's entirely optional, as I said. But quite cool, and I think the standard library docs describe it rather well.

If you were to use fold in this case, You'd have the scores as the accumulator, with (0, 0) as the start value. The x would be the (ai, bi) tuple.

1 Like