In the below code there are two functions that are doing the same thing. With a single argument “match function” there is some syntactic sugar with = function
. You can use this with a tuple to shorten a function and it made me wonder if there were any performance penalties with this route.
I skimmed the article in Real World OCaml and it looks like tuples are compiled down into C arrays which would mean that they are heap allocated right? Unless you already have a tuple, wouldn’t you want to always opt for something like type_effectiveness
over type_effectiveness_tuples
?
type ptype = TNormal | TFire | TWater
type effectiveness = ENormal | ENotVery | ESuper
let effectiveness_multiplier : effectiveness -> float = function
| ENormal -> 1.0
| ENotVery -> 0.5
| ESuper -> 2.0
let type_effectiveness (user_type : ptype) (target_type : ptype) =
match user_type, target_type with
| (TFire, TFire) | (TWater, TWater) | (TFire, TWater) -> ENotVery
| (TWater, TFire) -> ESuper
| _ -> ENormal
let type_effectiveness_tuples : ptype * ptype -> effectiveness = function
| (TFire, TFire) | (TWater, TWater) | (TFire, TWater) -> ENotVery
| (TWater, TFire) -> ESuper
| _ -> ENormal
Also in type_effectiveness
is there a difference between:
match user_type, target_type with
| (TFire, TFire) | (TWater, TWater) | (TFire, TWater) -> ENotVery
| (TWater, TFire) -> ESuper
| _ -> ENormal
match user_type, target_type with
| TFire, TFire | TWater, TWater | TFire, TWater -> ENotVery
| TWater, TFire -> ESuper
| _ -> ENormal
I find 1 much easier to read.