C
C
Che_Bu_Rashka2016-03-23 11:44:34
Delphi
Che_Bu_Rashka, 2016-03-23 11:44:34

Anonymous methods, closures. Can you explain an example?

I quote:

As the name suggests, anonymous methods are procedures or functions that do not have an associated name. An anonymous method is a block of code that can be associated with a variable or used as a parameter to another method. In addition, anonymous methods can use variables from the context where the method is defined. Declaring and using anonymous methods does not require complex syntax. Their syntax is similar to the construction of closures (closures), characteristic of other programming languages.

function MakeAdder(y: Integer): TFuncOfInt;
begin
 Result := function(x: Integer)
 begin
 Result := x + y;
 end; 
end;

The MakeAdder function returns an unnamed function, i.e. anonymous method. The type of an anonymous method is declared as a method reference.
Example : executing the MakeAdder function
var
 adder: TFuncOfInt;
begin
adder := MakeAdder(20);               // что происходит тут ?
 Writeln(adder(22));  // prints 42  // и тут ?
end.
type
 TFuncOfInt = reference to function(x: Integer): Integer;

  1. can anyone explain step by step how it works?
  2. did I understand correctly that in the line adder := MakeAdder(20); in the body of the function, the value 20 is stored, in the variable y , which remains as long as the variable adder lives ? And is this a closure?
  3. And in the Writeln(adder(22)) line , the internal unnamed function function(x: Integer) is called , where the value 22 is passed to the x variable.

And further. Is it true that now with such a mechanism, functions in Delphi become first-class objects , because now they can be passed as parameters to other functions. Is this functional programming?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question