User Tools

Site Tools


Sidebar


Introduction


Basic Tutorials


Advance Tutorials


Useful Techniques


Examples

  • Simple Pipe Weight Calculator
  • Unit Convertor

Sidebar

tutorial:proceduraltype

This is an old revision of the document!


Procedural Type

Procedural Type คืออะไร

คือ การสร้างตัวแปรชนิดที่เป็น procedure/function เพื่อให้สามารถนำไปใส่ใน input Argument ของ procedure/function อันอื่นได้ หรือเรียกอีกอย่างหนึ่งคือ การทำให้ procedure/function กลายเป็นตั่วแปร

Example-1: Use a function as Input Argument

Example-1: Use a function as Input Argument

ตัวอย่าง การส่ง function เข้าไปอีก function หนึ่ง
ข้อสังเกต: ปัญหาการส่งผ่าน func เข้าไปใน average_value ไม่สามารถทำได้

program Find_MaxValue_Of_Function;

type
  Tfunc = function(x:real):real; //Procedural Type

//define polynomial function f(x) = x^2+2*x-5
//This function has the Max value = 15 at x = 5
function func(x:real):real;
begin
  result:=-x*x+10*x-10 ;  
end;

function Find_Max(f:Tfunc; xFirst,xLast,increment:real):real;
var x,xMax,max:real;
begin
  x:=xFirst;
  xMax:=x;
  max:= f(x);
  while x<xLast do
   begin
     x:=x+increment;
     if f(x)>max then xMax := x;
     max:= f(x);
   end;
  result:=f(xMax);
end;

//Call the above function
BEGIN
  writeln('Max value between x = 0 to x = 10 is : ',Find_Max(@func,0,10,0.001));
  readln;
END.  


จาก Example-1 จะเห็นว่า เราไม่สามารถส่งตัวแปรที่เป็น procedure/function เข้าไปใน Argument ของ function average_value ได้ จึงจำเป็นต้องมีการประการ Type ของ function ก่อน ดังตัวอย่างต่อไปนี้

Example-2: แก้ปัญหาโดยการประกาศตัวแปร Procedural Type ก่อน

Example-2: แก้ปัญหาโดยการประกาศตัวแปร Procedural Type ก่อน

Type
  Tfunc = function(x:real):real; 

//define polynomial function f(x) = x^2+2*x-5
function func(x:real):real;
begin
  result:=x*x+2*x-5 ;
end;

//create function to find the average value between a and b of any function
function average_value(f:Tfunc; a,b:real):real;
begin
  result:=(f(a)+f(b))/2;
end;
  
//Call the above function
BEGIN
  writeln(average_value(@func,1,10)); 

END.  


ข้อแตกต่างระหว่าง Lazaus กับ Delphi

ข้อสังเกต การใส่ function เข้าไปสำหรับ lazarus กับ delphi จะแตกต่างกัน โดย Lazarus จะใช้การส่งค่าผ่าน pointer ดังนั้นจึงต้องมีเครื่องหมาย @ นำหน้าชื่อ function แต่สำหรับ delphi สามารถส่งชื่อ function เข้าไปได้เลย ดูตัวอย่างที่ 3

Example-3: เปรียบเทียบการเรียก function โดย Lazarus กับ Delphi

Example-3: เปรียบเทียบการเรียก function โดย Lazarus กับ Delphi

Type
  Tfunc = function(x:real):real; 

//define polynomial function f(x) = x^2+2*x-5
function func(x:real):real;
begin
  result:=x*x+2*x-5 ;
end;

//create function to find the average value between a and b of any function
function average_value(f:Tfunc; a,b:real):real;
begin
  result:=(f(a)+f(b))/2;
end;
  
//Call the above function
BEGIN
  //Lazarus
  writeln(average_value(@func,1,10)); 
  
  //Delhpi
  writeln(average_value(func,1,10)); 

END.  

tutorial/proceduraltype.1536463232.txt.gz · Last modified: 2018/09/09 10:20 by admin