Rust pattern matching on vector

Tutorial shows some very basic pattern matching examples, such as matching integers to simulate C-style switch statements This tutorial also introduces how to basically deconstruct tuple types and deconstruct structures

It seems that pattern matching should be possible on a vector, but I can't find the correct syntax. I haven't found any examples

For example, in Haskell, you can easily refactor the list:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr func initValue []     = initValue
foldr func initValue (x:xs) = func initValue $foldr initValue func xs

Therefore, looking at a rough translation, it will be very happy to do:

fn foldr<A,B>(func: fn(A,B) -> B,initValue: B,vals: [A]) -> B {
  alt vals {
    [] { ret initValue; }
    _  {
      let h = vec::head(vals),t = vec::tail(vals);
      ret foldr(func,func(initValue,h),t);
    }
  }
}

Note: I know you can use the if statement here. I just use it as an example of vector pattern matching

Currently returned:

patterns.rs:10:4: 10:5 error: constant contains unimplemented expression type
patterns.rs:10     [] { ret initValue; }
                ^
error: aborting due to prevIoUs errors

In Deconstruction structure (by {..} Definition) and tuple (..) There is an example in the tutorial of definition), so it seems that support for vectors should be built in, taking into account that they also contain a special syntax (with [..] Definition)

If I use vectors in the wrong way, please correct me at any time

Solution

I wish I could provide more general advice on how to best use vector pattern matching, but here is how to use them to test empty vectors (at least I think this is what Haskell code is doing...):

use std;
import std::io::println;

fn main() {
    let empty: [int] = [];
    println(vec_alt(empty));
    println(vec_alt([1,2,3]));
}

fn vec_alt<A>(vals: [A]) -> str {
    alt vals {
        x if x == [] { "empty" }
        _ { "otherwise" }
    }
}

Note that the attempt to simply pass [] as an argument failed because the compiler cannot infer the type of vector Without declaring it first, it seems possible to pass [()] (a vector with no content), but the ALT statement seems unable to test to see if the header expression matches [()] (it simply falls in the default)

In a word, the vector seems a little rough If there are some specific usage methods, you can consider that rust does not seem to support, and developers are quite open to suggestions and Criticism: https://mail.mozilla.org/listinfo/rust-dev

Please also refer to the reference manual for more formal definitions, and there are more examples to help clarify things: http://doc.rust-lang.org/doc/rust.html#alternative -expressions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>