how do i use list.fold_left in ocaml, give examples and in ruby

(* Using List.fold_left in OCaml *)
let numbers = [1; 2; 3; 4; 5]
let sum = List.fold_left (fun acc x -> acc + x) 0 numbers
124 chars
4 lines

In the above code snippet, we are using List.fold_left to calculate the sum of elements in the numbers list.

main.rb
# Using inject in Ruby
numbers = [1, 2, 3, 4, 5]
sum = numbers.inject(0) { |acc, x| acc + x }
94 chars
4 lines

In the above Ruby code snippet, we are using inject method to achieve the same result as in the OCaml example.

main.rb
0 chars
1 lines

related categories

gistlibby LogSnag