• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

Passing a function as an argument to a function

I have a function to find the root of a function of x:

function TMyAppForm.FindRoot(x1, x2: Double): Double;

where the root lies between x1 and x2.

At present the root finding function assumes there is an externally defined function f(x: Double): Double, the root of which is to be found. However, I would like to apply the root-finding function to several different functions of x. Hence, I am interested in passing the function as an argument. For example, in one method of the program, I may have:

function f(x: Double): Double;
begin
  f:=<some function of x>;
end;

Then in another method of the program, I may have:
function f(x: Double): Double;
begin
  f:=<some entirely different function of x>;
end;

How can I get the root finding function to operate on these different definitions of f ?
0
riskassessor
Asked:
riskassessor
1 Solution
 
ziolkoCommented:
this should work:

type
  TMyfunction = function(x: Double):Double;

procedure PassFunc(AFunction: TMyFunction);
var d: Double;
begin
  d := AFunction(12.45);
end;

procedure Func1(x: Double):Double;
begin
  Result := x;
end;

procedure Func2(x: Double):Double;
begin
  Result := x * x;
end;

PassFunc(Func1);
PassFunc(Func2);

if Func1, Finc2 are about to be object methods
TMyFunction should be declared:
type
  TMyfunction = function(x: Double):Double of object;

ziolko.
0
 
riskassessorAuthor Commented:
Thank you very much, that seems to work! Except that it should be PassFunc(@Func1); PassFunc(@Func2), I think.

Peter
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now