[beginner] what's a good pattern around pattern matching on a string?


#1

Is this pattern “Reasonable”?

let basicOp = (operation, a, b) => {
  switch (operation) {
  | '+' => a + b
  | '-' => a - b
  | '*' => a * b
  | '/' => a / b
  | _ => raise(Not_found) /* OK? */
  }
};

With syntax highlighting:

Or would something like this be better? I sort of changed the assignment here.

type operator = Plus | Minus | Multiply | Divide;

let basicOp3 = (operation, a, b) => {
  switch (operation) {
  | Plus => a + b
  | Minus => a - b
  | Multiply => a * b
  | Divide => a / b
  }
};

Js.log(basicOp3(Plus, 4, 7) == 11);
Js.log(basicOp3(Minus, 15, 18) == -3);
Js.log(basicOp3(Multiply, 5, 5) == 25);
Js.log(basicOp3(Divide, 49, 7) == 7);

Thanks!


#2

Depends on what you want. You might want to return None instead of raising an exception:

let basicOp = (operation, a, b) => {
  switch (operation) {
  | '+' => Some(a + b)
  | '-' => Some(a - b)
  | '*' => Some(a * b)
  | '/' => Some(a / b)
  | _ => None
  }
};

Or, if you just want to pass an operation as a parameter, you can go:

let runOp = (op, a, b) => op(a, b);
let x = runOp((*), 2, 3); /* 6 */

So in the latter example you don’t really need runOp at all, you can just go (*)(2,3). But you could do something fancier like:

Array.map([| 3, 4, 5 |], (*) 2)); /* [6, 8, 10] */

This is because operators are just functions.


#3

Thanks @hoichi! That already helps :slight_smile:

Because it’s an exercise they imply that we’ll only get those operators. So letting the function pass back Some/None is clean I’d say.

And: your solution with passing in the operator is really nice, I did not yet know that of Reason.