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: ปัญหาการส่งผ่านตัวแปรชนิด function เข้าไปในอีก function หนึ่ง ไม่สามารถทำได้ทันที ดังตัวอย่าง

Example-1: ปัญหาการส่งผ่านตัวแปรชนิด function เข้าไปในอีก function หนึ่ง ไม่สามารถทำได้ทันที ดังตัวอย่าง


//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 of object; 

//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.  

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

Lazarus Delphi
BEGIN
  //Lazarus
  writeln(average_value(@func,1,10)); 

END.
tutorial/proceduraltype.1536459766.txt.gz · Last modified: 2018/09/09 09:22 by admin