E4165

E4165#

Compiler diagnostic name: missing_op_as_view.

Missing op_as_view method for array pattern matching.

Open array patterns such as [head, ..tail] need a value that can provide a view for the .. part of the pattern. op_as_view is the compiler's internal name for the _[_:_] view operator; in source code this operation is provided by annotating a compatible method with #alias("_[_:_]").

Erroneous example#

The following example tries to use an open array pattern on an Int, which does not provide op_as_view:

///|

///|
fn first_and_rest(value : Int) -> Int {
  match value {
    [head, .. _tail] => head
    _ => 0
  }
}

///|
test {
  ignore(first_and_rest)
}

MoonBit will report an error.

Suggestion#

Use an array-like value that provides the view operation. When defining that operation, annotate the method with #alias("_[_:_]"), for example:

#alias("_[_:_]")
fn Type::view(self : Type, start? : Int = 0, end? : Int) -> View {
  ...
}

The fixed example uses Array[Int], which already provides this operation:

///|

///|
fn first_or_zero(values : Array[Int]) -> Int {
  match values {
    [head, .. _tail] => head
    [] => 0
  }
}

///|
test {
  inspect(first_or_zero([1, 2, 3]), content="1")
  inspect(first_or_zero([]), content="0")
}