Pattern matching: ocaml list -> Rust vec

  1. I am converting some OCaml code to Rust.

  2. I am representing OCaml list as a Rust Vec (with end = front of list).

  3. I see OCaml patterns like:

f(nil) -> ...
f(a :: nil) -> ...
f(a :: b) -> ...

Is there a nice way to match this in Rust ? Rust match works well for destructuring enums, but I want to use a Vec instead of mimicking OCaml lists via

pub enum FakeList<T> {
  Nil,
  Cons(T, Rc<FakeList<T>>)
}

EDIT: don't want -> want; i.e. I want to use Vec, I don't want to mimic FakeList

1 Like

You can use slice patterns to pattern-match on slices, but you can't use patterns to destructure a Vec by ownership.

match slice {
    [] => todo!(),
    [a] => todo!(),
    [a, b @ ..] => todo!(),
}
2 Likes

Ooh, I wrote an article which shows how to do exactly this!

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.