Reputation: 2424
I have a variant type like this:
type score =
InInteger of int
| InFloat of float ;;
Now, given two scores (InInteger(5)
and InFloat(5.5)
), I want to add, subtract them etc..
How can this be done?
PS - I'm a newbie to OCaml.
Edit::
More specifically:
How does this work?
let n = InInt(2);;
let m = InFloat(3.2);;
let var = InFloat(float n +. m);;
Upvotes: 2
Views: 355
Reputation: 41290
First, discriminated unions require their identifiers starting with upper cases:
type score =
InInteger of int
| InFloat of float
Second, you can define an add
function on this datatype by pattern matching all possible cases and returning appropriate values:
let add s1 s2 =
match s1, s2 with
| InInteger i1, InInteger i2 -> InInteger (i1 + i2)
| InInteger i1, InFloat f2 -> InFloat (float i1 +. f2)
| InFloat f1, InInteger i2 -> InFloat (f1 +. float i2)
| InFloat f1, InFloat f2 -> InFloat (f1 +. f2)
Upvotes: 5
Reputation: 19367
+.
will add float
s only, and +
will add int
s only. That's all there is to it! If you've got float
s or int
s wrapped inside your union type, you'll have to use match
per pad's answer to get them out, then convert the plain numbers within.
Upvotes: 3