Type inference with List.fold

65 Views Asked by At

I'm having some issues transforming a list of lists again. I have a list of list of ints it looks like this.

val p5PrimeFactorization : int list list =
  [[1]; [2]; [3]; [2; 2]; [5]; [3; 2]; [7]; [2; 2; 2]; [3; 3]; [5; 2]; [11];
   [3; 2; 2]; [13]; [7; 2]; [5; 3]; [2; 2; 2; 2]; [17]; [3; 3; 2]; [19];
   [5; 2; 2]] 

Now I want to transform each list into the product of all entries. Now this works

[for n in 2..20 -> primeFactors n 2 []]
|> List.map (List.sum)

But this doesn't..

[for n in 2..20 -> primeFactors n 2 []]
|> List.map (List.fold (fun acc elem -> acc * elem))

It seems the problem is that it infers the type of acc and elem to be of type int list which isn't right. I don't understand why List.sum which basically does the same thing except it returns the sum of all numbers, works, but my folder will not.

1

There are 1 best solutions below

0
On BEST ANSWER

In your second example, you haven't specified the initial value for the fold.

You probably meant something like

|> List.map (List.fold (fun acc elem -> acc * elem) 1)