Destructuring array or list


#1

Is there an idiomatically correct way to destructure an array or list?


#2

Yup, there are a couple of array pattern matching examples in the Reason docs. Also, in Exploring ReasonML.

If you need more, you can probably find some examples for OCaml and convert them using the Reason REPL.


#3

Exploring Reason is a good example of my issue. If I try to destructure all values into variables, I get the non-exhaustive error. But unadulterated pattern matching doesn’t allow a similar multi-bind. Is there a way to do that?


#4

It depends. If you are willing to supply default values for non-existent array/list members, then you can still do multi-binds with normal pattern matching. E.g.,

let (x, y, z) = switch (arr) {
  | [|x, y, z|] => (x, y, z)
  | _ => (0, 0, 0)
};

But if not, the compiler can’t guarantee that the values will be present and so it warns about non-exhaustive match.


#5

Thank you muchly. That’s how I was doing it, but it seemed a bit cludgey… kludgey… klugey?.. As such, I wanted to make sure I wasn’t missing a one-liner or some other language feature intended for this.


#6

If you find yourself doing this too often, maybe you’re overloading arrays as tuples like TypeScript does? If that’s the case, consider producing tuples as early as possible in your application. Arrays, Lists and Tuples are totally different data structures in Reason.


#7

That’s a good point. BuckleScript actually guarantees that its representation of tuples is in fact JavaScript arrays, so if you’re binding to some JavaScript thing that’s giving you an array that’s really a tuple, you can type it as a ReasonML tuple.


#8

I doubt that I would be doing this very often. I’m interested in it because as I’m learning Reason, I want to make sure that I don’t do a quick pass over a structure or a concept, but stop and focus on one particular piece until I fully understand its conceptual foundation as well as its implementation. Granted, since I’m interested in Reason specifically to get away from JavaScript, I’m not as interested in the implementation as I otherwise would be.