Question

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.

Was it helpful?

Solution

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|]

OTHER TIPS

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 want to use tail recursive function to do the job. You might want to try sth similar:

let l = [1;2;3;4;5]

let product lst = 
    let rec pTR acc = function
        | [] -> acc
        | h::t -> pTR (h * acc) t
    pTR 1 lst

product l
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top