Catamorphism: Difference between revisions

(→‎{{header|Forth}}: Add Fortran.)
Line 616:
 
=={{header|Fortran}}==
If Fortran were to offer the ability to pass a parameter "by name", as is used in [[Jensen's_Device#Fortran|Jensen's device]], then the code might be something like <lang Fortran> SUBROUTINE FOLD(t,F,i,ist,lst)
INTEGER t
BYNAME F
t = 0
DO i = ist,lst
t = F
END DO
END SUBROUTINE FOLD
 
CALL FOLD(temp,temp*a(i),i,1,N) !Result in temp.</lang>
Here, the function manifests as the expression that is the second parameter of subroutine FOLD, and the "by name" protocol for parameter F means that within the subroutine, whenever there is a reference to F, its value is evaluated afresh in the caller's environment, using the current values of ''temp'' and ''i'' as modified by the subroutine - they being passed by reference. An evaluation for a different function requires merely another statement with a different expression.
 
Fortran however does not provide such a facility. Any parameter that is an expression is evaluated once in the caller's environment, the result placed in temporary storage, and the address of that storage location is passed to the subroutine. Repeated references to that parameter will elicit the same value. But there is special provision for passing a function to a routine, involving the special word EXTERNAL. For every different function in mind, one must diligently supply a name, and work through the overhead of declaring each such function.
 
Here is such an arrangement, in the style of F77 though somewhat affected by F90 in that the END statement names the routine being ended. Similarly, to abate petty complaints about the types of the functions being undeclared, explicit types are specified, though unselecting the compiler diagnostic for that would match the habits of earlier compilers. Also in F90 is the MODULE protocol which involves rather more organised checking of types and additional facilities for arrays [[Array_length#Fortran|so that N need not be passed]] because secret additional parameters do so.
 
However, only programmer diligence in devising functions with the correct type of result and the correct type and number of parameters will evade mishaps. Note that the EXTERNAL statement does not specify the number and type of parameters.
<lang Fortran> INTEGER FUNCTION IFOLD(F,A,N) !"Catamorphism"...
INTEGER F !We're working only with integers.
Line 668 ⟶ 685:
WRITE (MSG,*) "Idiv",IFOLD(IDIV,A,ENUFF)
WRITE (MSG,*) "Ivid",IFOLD(IVID,A,ENUFF)
END PROGRAM POKE
</lang>
Output:
1,220

edits