Question

I currently have a special type that can be either an int or a float. I want to create a function that will allow me to add two of them together. (coercing the int to a float if necessary) I want the function to have a return type of my special type.

Here is what I have so far:

type number = A of int | B of float;;

let plus x1:number x2:number = (number x1) + (number x2);;

Doesn't compile. But it looks similar to what I would write if I were using the ML programming language.

What should my plus function look like in F#?

Was it helpful?

Solution

type number = A of int | B of float;;

let plus x1:number x2:number = (number x1) + (number x2);;

The problem you have here is twofold:

  1. You can't use discriminated union cases which have a single value (in this instance, A and B) as though you had the value instead. Think of each case as a class which has one value in it (this is how it is represented in the bytecode anyway). You would need to take the value out of the class before attempting to use it.

  2. F# doesn't allow implicit casting. This means that once you get the values out of your cases, you will need to convert them to a common type. In this case you will need to either cast the A value to a float or the B value to an int.

As @JohnPalmer notes in his answer, the most clear way of addressing these two issues is to use pattern matching.

OTHER TIPS

So the best way is to do something like

let plus x1 x2 = 
    match x1,x2 with
    |A(a),A(a2) -> float(a+a2)
    |A(a),B(b) -> float(a) + b
    |B(b),B(b2) -> b+b2
    |B(b),A(a) -> float(a) + b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top