Loop over multiple arrays simultaneously: Difference between revisions
Content deleted Content added
→{{header|Python}}: Add (i)zip_longest |
→{{header|OCaml}}: a more generic solution |
||
Line 339:
print_newline()
) a1 ;;</lang>
a more generic solution could be to use a function which iterates over a list of arrays:
<lang ocaml>let n_arrays_iter ~f al =
match al with
| [] -> ()
| x::xs ->
let len = Array.length x in
let b = List.fold_left (fun b a -> b && (Array.length a = len)) true xs in
if not b then raise(Invalid_argument "n_arrays_iter: arrays of different length");
for i = 0 to pred len do
let ai = List.map (fun a -> a.(i)) al in
let () = f ai in ()
done</lang>
this function raises Invalid_argument exception if arrays have different length, and has this signature:
<lang ocaml>val n_arrays_iter : f:('a list -> unit) -> 'a array list -> unit</lang>
how to use it with arrays a1, a2 and a3 defined before:
<lang ocaml>let () =
n_arrays_iter [a1; a2; a3] ~f:(fun l ->
List.iter print_char l;
print_newline());
;;</lang>
=={{header|Perl 6}}==
|