An explanation of `as`


I’m trying to understand as more deeply. Basically, what is it? What are its semantics? I know that it is a binding, but how and why is it different from other kinds of bindings.


as is pretty much what it appears to be, a way to bind a pattern to a name for a certain scope. I think it’s useful to understand why one would use it. When pattern-matching, there are certain times when you want to bind to certain parts of a pattern, but also to the pattern as a whole. For example, look at this:

As Jeffrey Scofield says in the answer, being able to bind to b :: _ as t (Reason syntax [b, ..._] as t) is slightly more convenient and efficient than if you didn’t have the as pattern available and you were forced to bind to only parts of the list and then reconstruct the list on the right-hand side of the pattern match.

In OCaml/Reason, there is a lot of expressive power in pattern matches that has evolved over time. Another one I really like is ‘or’ patterns, e.g.:

let cardType = fun
  | Some(Jack | Queen | King) => "face"
  | Some(_other) => "number"
  | None => "none";

This shows how patterns are actually composeable, just like lots of other concepts in OCaml.


How does this apply to using as in an object, for example as _this to eliminate unused value errors. Is this a special form?


This is a bit of the consequence of the way ReasonML inverts the default for object literals. By default in OCaml syntax, if you do something like:

let bob = object
  method id = 1
  method name = "Bob"

The this value is not bound. To bind it inside the object body, you actually have to use the explicit let bob = object (this) ... end.

Reason is the other way round, you have to explicitly ‘unbind’ it otherwise this is available. In this case as works the same way, to alias some variable with a new name.