RosettaCodeData/Task/Apply-a-callback-to-an-array/CLU/apply-a-callback-to-an-array.clu
2023-07-01 13:44:08 -04:00

34 lines
1.1 KiB
Text

% This procedure will call a given procedure with each element
% of the given array. Thanks to CLU's type parameterization,
% it will work for any type of element.
apply_to_all = proc [T: type] (a: array[T], f: proctype(int,T))
for i: int in array[T]$indexes(a) do
f(i, a[i])
end
end apply_to_all
% Callbacks for both string and int
show_int = proc (i, val: int)
po: stream := stream$primary_output()
stream$putl(po, "array[" || int$unparse(i) || "] = " || int$unparse(val));
end show_int
show_string = proc (i: int, val: string)
po: stream := stream$primary_output()
stream$putl(po, "array[" || int$unparse(i) || "] = " || val);
end show_string
% Here's how to use them
start_up = proc ()
po: stream := stream$primary_output()
ints: array[int] := array[int]$[2, 3, 5, 7, 11]
strings: array[string] := array[string]$
["enemy", "lasagna", "robust", "below", "wax"]
stream$putl(po, "Ints: ")
apply_to_all[int](ints, show_int)
stream$putl(po, "\nStrings: ")
apply_to_all[string](strings, show_string)
end start_up