Skip to content

RFC: Destructuring vectors syntax #1844

Closed
@ashgti

Description

@ashgti

Currently its possible to destructure tuples, records, and enums in let's and alt patterns. It could be useful to also destructure vectors as well, plus it would feel more consistent.

The obvious goal would be to do something like this:

fn foldr<A, B>(func: fn(A, B) -> B,
               initValue: B,
               vals: [A]) -> B {
  alt vals { 
    [] { ret initValue; }
    [head, tail...]  { ret foldr(func, func(initValue, head), tail); }
  }
}

I am not sure of the syntax exactly but it would be useful to be able to destructure vectors at least in some way.

Another example of why this might be useful:

fn ever_other_element<A>(vals: [A]) -> [A] {
  alt vals {
    [head, _, rest...] { ret [head] + ever_other_element(rest); }
    [head, _] {  ret [head]; }
    _ { ret []; }
  }
}

Could be expressed as:

fn ever_other_element<A>(vals: [A]) -> [A] {
  if vec::len(vals) > 2 {
    let head = vals[0],
        rest = vec::tail(vec::tail(vals));
    ret [head] + ever_other_element(rest);
  }
  else if vect::len(vals) == 2 {
    let head = vals[0];
    ret [head];
  }
  else {
    ret [];
  }
}

In my samples I am assuming that in this expression: [head, tail...]; head matches 1 element and tail matches 0+ elements.

But, the difference is just that using pattern matching makes this a lot more readable. If this should apply to lists instead of vectors, let me know, but list's are in the core:: they are in std:: so, my assumption is that it makes more sense for vec to work this way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-frontendArea: Compiler frontend (errors, parsing and HIR)C-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions