2
votes

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);;
2
(Let us know if this is homework so we don't give away too much stuff you're supposed to figure out.) - Jeffrey Scofield
Thanks Jeffrey. This is not directly out of my homework, although an answer to this question will help me towards solving a question. I would really appreciate an answer on how +. operator works, and how InFloat (float i1 +. f2) is a valid expression. (ref pad's answer) - Gitmo
@Gitmo: You edited example is wrong; it supposes to be let var = InFloat(float 2 +. 3.2). Regarding (+.) operators on float, Jeffrey's comment on my answer is a great explanation. - pad
By the way, semi-colons aren't necessary except in the ocaml REPL (to tell it when to stop!). - Asherah

2 Answers

5
votes

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)
3
votes

+. will add floats only, and + will add ints only. That's all there is to it! If you've got floats or ints 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.