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 - Wrong Method

Example-1: Use a function as Input Argument - Wrong Method

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


//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(a,b:real):real;
begin
  result:=(a+b)/2;
end;
  

//Call the above function
BEGIN
  writeln(average_value(func(1),func(10))); //Error!!! 
  //cannot pass "func" as argument.

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.1536460912.txt.gz · Last modified: 2018/09/09 09:41 by admin