Is it idiomatic to switch on an array?

This looks weird to me but seems to work well in my tests.

let parse_address = (line): option<(string, string)> => {
  switch Js.String2.split(line, "@") {
  | [] | [""] | [_, ""] | ["", _] => None
  | [box, domain] => Some(box, domain)
  | _ => None
  }
}

The code it generates looks really smart, but my main concern is if you can accidentally trick it into going out of bounds in the array somehow and throwing an exception.

1 Like

I match on arrays as well. I think you can simplify your first clause, since you only care about non-empty tuples.

  switch Js.String2.split(line, "@") {
  | [_, ""] | ["", _] => None                // no reason to match [] or [""]
  | [box, domain] => Some(box, domain)
  | _ => None
  }
3 Likes

otherwise this avoids code review abuse and ridicule?

I like it. If you need more logic (eg only accept letters and numbers) then a regex would be better suited than a split. But the split and switch is nice and readable.

IMO it is idiomatic to switch on anything that is more complex than a boolean.

4 Likes