Wrong number of parameters specified for call to "f1"

Viewed 412

When creating a procedural data type, Free Pascal throws a strange error. But I'm passing one parameter, why is the number of parameters incorrect?

Type
    Func = Function (x:Real):Real;
    
Function middlfunc(a, b:Real; n:Integer; f:Func): Real;
Var
    x,s,d: Real; k:Integer;
Begin
    d:=(b-a)/n;
    s:=0;
    For k:=0 To n Do
    Begin
        x:=a+k*d;
        s:=s+f(x);
    End;
    middlfunc:=s/(n+1);
End;

Function f1(x:Real):Real; {There is the error}
Begin
    f1:=x*x;
End;

Var
    mf1:Real;
    a, b: real;
    n: integer;
    
Begin
    a := 0;
    b := 3.1415;
    n := 100;
    mf1 := middlfunc(a,b,n,f1); {ERROR :((((((((}
    WriteLn(mf1)
End.
2 Answers

USE PASCAL PROCEDURE INSTEAD OF FUNCTION for suitability

If you want to use a Function as a parameter to another function, then you have to do it like this:

Type
    TFunctionParameter = function(x: Real): Real;
    
Function middlfunc(a, b:Real; n:Integer; f:TFunctionParameter): Real;
Var
    x,s,d: Real; k:Integer;
Begin
    d:=(b-a)/n;
    s:=0;
    For k:=0 To n Do
    Begin
        x:=a+k*d;
        s:=s+f(x);
    End;
    middlfunc:=s/(n+1);
End;

function RaiseToSecondPower(x: Real): Real;
begin
  result := x*x;
end;

Var
    mf1:Real;
    a, b: real;
    n: integer;
Begin
    a := 0;
    b := 3.1415;
    n := 100;
    mf1 := middlfunc(a,b,n,RaiseToSecondPower);
    WriteLn(mf1)
End.
Related