Lesson 12 of 15

Fold

Fold

List.fold reduces a list to a single value by accumulating results:

List.fold (fun acc x -> acc + x) 0 [1; 2; 3; 4; 5]
// 15

The signature: fold (acc -> elem -> acc) initialValue list.

  • The function takes the current accumulator and the current element
  • Returns the new accumulator
  • Starts with initialValue

Build a string from a list:

let joined = List.fold (fun acc x -> acc + x + " ") "" ["hello"; "world"]
// "hello world "

Your Task

Write a function product that takes a list of integers and returns their product using List.fold. The identity element for multiplication is 1.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.