How to resolve the algorithm Closures/Value capture step by step in the OCaml programming language
How to resolve the algorithm Closures/Value capture step by step in the OCaml programming language
Table of Contents
Problem Statement
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Closures/Value capture step by step in the OCaml programming language
Source code in the ocaml programming language
let () =
let cls = Array.init 10 (fun i -> (function () -> i * i)) in
Random.self_init ();
for i = 1 to 6 do
let x = Random.int 9 in
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
done
You may also check:How to resolve the algorithm Trabb Pardo–Knuth algorithm step by step in the Perl programming language
You may also check:How to resolve the algorithm Animate a pendulum step by step in the Clojure programming language
You may also check:How to resolve the algorithm OpenGL step by step in the Lua programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the R programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Odin programming language