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.
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|]
You can use Array.scan
:
let products = arr |> Array.scan (*) 1;;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With