Question: Can I return different types with a `switch`?


#1

Taking the example FizzBuzz implementation, I wanted to see if the pattern matching could be used to return more than just the inferred type of string. Aside from design decisions, is it possible to implement this? Keep in mind that the actual working example utilizes string_of_int(i) to satisfy the expected type.

let fizzbuzz = (i) =>
  switch (i mod 3, i mod 5) {
  | (0, 0) => "FizzBuzz"
  | (0, _) => "Fizz"
  | (_, 0) => "Buzz"
  | _ => i /* Can I intentionally return an int here */
  };

for (i in 1 to 100) {
  Js.log(fizzbuzz(i))
};

#2

One way to do this is to have fizzbuzz return a variant. Taking your example:

type output =
  | Str(string)
  | Int(int);

let fizzbuzz = i =>
  switch (i mod 3, i mod 5) {
  | (0, 0) => Str("FizzBuzz")
  | (0, _) => Str("Fizz")
  | (_, 0) => Str("Buzz")
  | _ => Int(i) 
  };

for (i in 1 to 100) {
  switch (fizzbuzz(i)) {
  | Str(x) => Js.log(x)
  | Int(x) => Js.log(x)
  };
};

#3

Thanks so much, this helped clear up a lot for me!