0
votes

When I try to iterate through a 2darray of floats and try to compare an element with a float it won't let me. I get the error: "error FS0001: The type 'float' does not match the type 'obj'"

Have tried casting "elm" in the loop but it does not work.

let arr = array2D   [[1.0;  2.0; 3.0]
                     [4.0;  5.0; 6.0]
                     [7.0;  8.0; 9.0]]

for elm in retval do
    if elm = 0.0 then 
        printfn "yes"
1
What is retval? - Phillip Carter

1 Answers

0
votes

The issue is that .Net multidimensional arrays don't implement IEnumerable<T>, only the non-generic IEnumerable, so your loop variable is typed as obj. You have a few options.

Cast the loop variable

if elm :?> float = 0.0 then

Cast the array elements

for elm in Seq.cast<float> arr do

Additionally, I would caution you to avoid doing equality comparisons using float or double, because that won't always work due to how floating point representations are handled. For example, in the multidimensional array you've presented, as double values the 1.0 value is actually 1.0000000000000557. Floating point numbers are for things that have to be just accurate enough but not completely precise.