8

I want to remove nans from a list, so I've implemented the function shown below.

val it : float list =
  [50.0; -20833.33333; 4.50701062e-14; -4.267032701e-15; 3.942195769e-16;
   -3.555114863e-17; 3.130384319e-18; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 
   nan; nan; nan; nan; nan; nan; nan; nan; nan]

let rec remove_nan l =
    match l with
    | [] -> []
    | x::rest -> if x=nan then remove_nan rest
                 else x::(remove_nan rest)

remove_nan points

However, it does not remove the nan's from the list. Why aren't they being removed?

0

1 Answer 1

21

NaN has weird equation properties. Specifically, nan = nan is false! Use this in your code:

if System.Double.IsNaN x then remove_nan rest

Or define remove_nan as follows, which is shorter and doesn't grow the stack:

let remove_nan = List.filter (System.Double.IsNaN >> not)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.