Jump to content

Return multiple values: Difference between revisions

→‎{{header|OCaml}}: Space safety of tuples
No edit summary
(→‎{{header|OCaml}}: Space safety of tuples)
Line 225:
Printf.printf "33 + 12 = %d\n" sum;
Printf.printf "33 - 12 = %d\n" difference</lang>
 
=== Space safety of tuples ===
 
The OCaml programmer should be aware that when multiple values are returned with a tuple, the finalisation does not handle each values independently, but handles the tuple as a whole. So all the values are only finalised when all the values are not reachable anymore.
 
There is also an explanation of this behaviour in the module [http://www.janestreet.com/ocaml/janestreet-ocamldocs/core/Space_safe_tuple.html Space_safe_tuple] of the Jane Street's core library.
 
<lang ocaml>let pair a b =
let ra = Array.create 1 a
and rb = Array.create 1 b in
let f r = Printf.printf "> finalised: %d\n%!" r.(0) in
Gc.finalise f ra;
Gc.finalise f rb;
(ra, rb)
 
let () =
let a, b = pair 1 2 in
let c, d = pair 3 4 in
Gc.full_major (); (* garbage collection *)
Printf.printf "Used: %d\n%!" a.(0)</lang>
 
Here we see that <code>b</code> is not finalised even if it is not used after the garbage collection:
 
<pre>$ ocamlopt -w y -o pair.opt pair.ml
$ ./pair.opt
> finalised: 4
> finalised: 3
Used: 1</pre>
 
The workaround is to explicitly access to each value with functions like <code>fst</code> and <code>snd</code> that return only one element of the tuple:
 
<lang ocaml>let pair a b =
let ra = Array.create 1 a
and rb = Array.create 1 b in
let f r = Printf.printf "> finalised: %d\n%!" r.(0) in
Gc.finalise f ra;
Gc.finalise f rb;
(ra, rb)
 
let () =
let ab = pair 1 2 in
let a = fst ab
and b = snd ab in
let c, d = pair 3 4 in
Gc.full_major (); (* garbage collection *)
Printf.printf "Used: %d\n%!" a.(0)</lang>
 
Now we see that <code>b</code> is finalised:
 
<pre>$ ocamlopt -w y -o pair2.opt pair2.ml
$ ./pair2.opt
> finalised: 4
> finalised: 3
> finalised: 2
Used: 1</pre>
 
=={{header|PARI/GP}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.