Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Cumulative Product of an array

Tags:

f#

Using F#, I would like to calculate the cumulative product of an Array without any loop. A first idea will be to use Array.fold and Array.map but I don't see how I can use them. What do you suggest? or peharps using a recursive function? Many thanks in advance for your help.

like image 296
Gilles Criton Avatar asked May 06 '14 09:05

Gilles Criton


3 Answers

If you need the product of all elements, you can use fold indeed:

> let a = [|1;2;3;4;5|];
> a |> Array.fold (*) 1;;

val it : int = 120

If you need the intermediate (cumulative) results, you can use scan. Scan takes each element in the array and applies a function (product in this case) to the element, and the previous cumulative result. Starting with a value of 1 for the accumulator, we get:

> a |> Array.scan (*) 1;;

val it : int [] = [|1; 1; 2; 6; 24; 120|]
like image 95
Mau Avatar answered Nov 15 '22 12:11

Mau


You can use Array.scan:

let products = arr |> Array.scan (*) 1;;
like image 42
Lee Avatar answered Nov 15 '22 11:11

Lee


Others already gave nice answers, just a general remark. Your statement "or perhaps a recursive function" is usually unnecessary. About 95% of the time, you can use a fold instead. Where recursive functions are the way to go, is if you need a non-standard iteration order.

Apart from that think in terms of not how to do the whole operation at once, i.e. how to process a list of numbers in your case, but just think how to do it for one item.

From that you get that you e.g. need to multiply the item with the accumulator. So in this case your no longer needs to be recursive, because with fold you abstracted over the iteration itself.

like image 35
Daniel Fabian Avatar answered Nov 15 '22 12:11

Daniel Fabian