How to resolve the algorithm Catamorphism step by step in the Modula-2 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Catamorphism step by step in the Modula-2 programming language
Table of Contents
Problem Statement
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Catamorphism step by step in the Modula-2 programming language
Source code in the modula-2 programming language
MODULE Catamorphism;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
(* Alas, there are no generic types. This function works for
CARDINAL only - you would have to copy it and change the types
to reduce functions of other types. *)
TYPE Reduction = PROCEDURE (CARDINAL, CARDINAL): CARDINAL;
PROCEDURE reduce(func: Reduction;
arr: ARRAY OF CARDINAL;
first: CARDINAL): CARDINAL;
VAR i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(arr) DO
first := func(first, arr[i]);
END;
RETURN first;
END reduce;
(* Demonstration *)
PROCEDURE add(a,b: CARDINAL): CARDINAL;
BEGIN RETURN a+b; END add;
PROCEDURE mul(a,b: CARDINAL): CARDINAL;
BEGIN RETURN a*b; END mul;
PROCEDURE Demonstration;
VAR a: ARRAY [1..5] OF CARDINAL;
i: CARDINAL;
BEGIN
FOR i := 1 TO 5 DO a[i] := i; END;
WriteString("Sum of [1..5]: ");
WriteCard(reduce(add, a, 0), 3);
WriteLn;
WriteString("Product of [1..5]: ");
WriteCard(reduce(mul, a, 1), 3);
WriteLn;
END Demonstration;
BEGIN Demonstration;
END Catamorphism.
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the COBOL programming language
You may also check:How to resolve the algorithm Bitmap step by step in the F# programming language
You may also check:How to resolve the algorithm Read entire file step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Environment variables step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the APL programming language