Nick
Nick

Reputation: 9061

How to convert a tuple of numbers to float in F#?

Suppose I have a tuple of numbers:

let mynum = (3, 5, 8.9, 45, 127.3)

It's mixed int with float. In order to do calculations like average, I have to convert them to float. How to do the conversion?

Upvotes: 0

Views: 455

Answers (2)

Vandroiy
Vandroiy

Reputation: 6223

How did the input turn out in this format? Tuples aren't supposed to be used in this way; they are intended for combinations of a few objects, which are strongly and independently typed.

The type of a tuple changes with its length, so there is no straightforward way to perform sequence operations on them. They are not compatible with seq<'T> anyway, since they the types of their components are unrelated. There is no average function for tuples, and if there were, it would have to be overloaded for all possible arities (number of components).

You might want to import the data into another collection, such as a list, a set, an array, or another type of sequence, and have the importer handle conversions where necessary. For example, if the input were a list of strings (as taken from a text file or such), System.Double.Parse or, as pointed out by ildjarn in the comments, the float operator, can be used to turn them into floats:

let input = ["3"; "5"; "8.9"; "45"; "127.3"]
List.map float input

This returns [3.0; 5.0; 8.9; 45.0; 127.3], which is of type float list: an immutable, singly-linked list of double-precision floats.

Upvotes: 3

Gus
Gus

Reputation: 26204

I don't know how did you end up with that tuple, I would advise to review your design. I personally consider tuples of more than 4 elements a smell, may be a record with named elements would be a best fit.

Anyway you can convert it easily to a list of float and then calculate the average:

let mynum = (3, 5, 8.9, 45, 127.3)
let inline cnv (x1, x2, x3, x4, x5) = [float x1; float x2; float x3; float x4; float x5]
let lst = cnv mynum // float list = [3.0; 5.0; 8.9; 45.0; 127.3]
List.average lst    // float = 37.84

Upvotes: 4

Related Questions