Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing nans from a list in F#

Tags:

list

nan

f#

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?

like image 896
madeinQuant Avatar asked Feb 10 '17 11:02

madeinQuant


1 Answers

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)
like image 66
Vandroiy Avatar answered Oct 14 '22 15:10

Vandroiy