Reputation: 133567
From what I understood I can use pattern-matching in a match ... with
expression with tuples of values, so something like
match b with
("<", val) -> if v < val then true else false
| ("<=", val) -> if v <= val then true else false
should be correct but it gives me a syntax error as if the parenthesis couldn't be used:
File "ocaml.ml", line 41, characters 14-17: Error: Syntax error: ')' expected
File "ocaml.ml", line 41, characters 8-9: Error: This '(' might be unmatched
referring on first match clause..
Apart from that, can I avoid matching strings and applying comparisons using a sort of eval of the string? Or using directly the comparison operator as the first element of the tuple?
Upvotes: 2
Views: 2684
Reputation: 36496
It's not the core of your problem, but a more flexible (and potentially performant as the lookup map grows) approach to this problem may be to use a map of strings to functions, and then use the lookup functions in the map to handle the dispatch.
module StrMap = Map.Make (String)
# let eval_binary_op op a b =
StrMap.(
let m =
empty
|> add "<" (<)
|> add "<=" (<=)
in
match find_opt op m with
| None -> failwith "op not found"
| Some f -> f a b
);;
val eval_binary_op : string -> 'a -> 'a -> bool = <fun>
# eval_binary_op "<" 4 5;;
- : bool = true
# eval_binary_op "<" 7 5;;
- : bool = false
# eval_binary_op ">" 7 5;;
Exception: Failure "op not found".
Upvotes: 0
Reputation: 370112
val
is a reserved keyword in OCaml, so you can't use it as a variable name. If you use something else instead of val
, it will work.
As a side note: if condition then true else false
is equivalent to condition
.
Upvotes: 9