Please explain the syntax of "| x as a => a"

The following code:

let toBusy = v =>
  switch v {
  | Init => Loading              
  | Loading as a => a             
  | Reloading(_) as a => a
  | Complete(a) => Reloading(a)
}

Can somebody help me to explain what does the “Loading as a => a”, and why I can’t write ite as “Loading => Loading” ?

Let’s break it down into the left side and the right side of the arrow.

  • Loading as a is a pattern, Loading, which is aliased to a variable name, a.
  • a on the right side is the same variable from the left, which is bound to the value Loading.

You can definitely write it like that. There should be no problem. Sometimes people write it with an alias to save some typing.

2 Likes

One note to add to @yawaramin’s answer, the as a can be also useful for performance.

When you write this: | Reloading(a) => Reloading(a) Then you’re deconstructing the variant and then constructing it again.

But when you write it like this: | Reloading(_) as a => a Then you just reuse the existing value, so you save a small amount of performance.

But for variant constructors without arguments, such as Loading, then this probably doesn’t actually save anything (since Loading just compiles to an integer). I assume whoever wrote that code did it mainly for consistency.

You can also combine as a with nested | patterns, so this would be an even shorter way to write that function:

let toBusy = v =>
  switch v {
  | Init => Loading
  | (Loading | Reloading(_)) as a => a
  | Complete(a) => Reloading(a)
  }
5 Likes