Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# How to Count Number of elements in a list that match some criteria?

Tags:

f#

I am prototyping how I am going to handle Double.NaN values in an F# array, and the first step, trying to simply count how many there are, has me stumped. The value "howMany" comes back as zero in my code, but I know there are 2, because I set 2 value to be Double.NaN. Can anyone point out what I am missing? Thanks!

let rnd = new System.Random()
let fakeAlphas = Array.init 10  (fun _ -> rnd.NextDouble());;

fakeAlphas.[0] <- Double.NaN;
fakeAlphas.[1] <- Double.NaN;

let countNA arr = arr |> Array.filter (fun x -> x = Double.NaN) |> Array.length;;

let howMany = countNA fakeAlphas;; 
like image 977
gh. Avatar asked Nov 27 '22 08:11

gh.


2 Answers

To answer the general question in the title:

let HowManySatisfy pred = Seq.filter pred >> Seq.length 

for example

let nums = [1;2;3;4;5]
let countEvens = nums |> HowManySatisfy (fun n -> n%2=0) 
printfn "%d" countEvens
like image 164
Brian Avatar answered Dec 14 '22 23:12

Brian


Double.NaN = n is false for all n. See the MSDN page for Double.NaN.

Instead use Double.IsNaN. See the MSDN page for more information.

like image 36
Nathan Shively-Sanders Avatar answered Dec 14 '22 23:12

Nathan Shively-Sanders