Apply a callback to an array: Difference between revisions

Add CLU
(Add CLU)
Line 721:
<lang lisp>;; shortcut syntax for a function
(map #(* % %) [1 2 3 4])</lang>
 
=={{header|CLU}}==
<lang clu>% 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</lang>
{{out}}
<pre>Ints:
array[1] = 2
array[2] = 3
array[3] = 5
array[4] = 7
array[5] = 11
 
Strings:
array[1] = enemy
array[2] = lasagna
array[3] = robust
array[4] = below
array[5] = wax</pre>
 
=={{header|COBOL}}==
2,114

edits