How to resolve the algorithm Apply a callback to an array step by step in the CLU programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Apply a callback to an array step by step in the CLU programming language

Table of Contents

Problem Statement

Take a combined set of elements and apply a function to each element.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Apply a callback to an array step by step in the CLU programming language

Source code in the clu programming language

% 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

  

You may also check:How to resolve the algorithm Averages/Pythagorean means step by step in the Pascal programming language
You may also check:How to resolve the algorithm Distribution of 0 digits in factorial series step by step in the Rust programming language
You may also check:How to resolve the algorithm Literals/Integer step by step in the HolyC programming language
You may also check:How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Scala programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the Standard ML programming language