### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Array methods  (Read 2255 times)

#### riwu

• New Member
• Posts: 15
##### Array methods
« on: December 26, 2015, 10:12:48 am »
Code: Pascal  [Select][+][-]
1. type
2.   PointArr = array of TPoint;
3. function PointArr.contains(x: TPoint): Boolean;
Is there a simple way to create routines that operates on arrays?

One way i know of is to declare PointArr as 'object', which allows type routines, but i wouldn't be able to use built-in array routines like Length(), SetLength(), [] property etc, so i would have to keep track of the length and implement these custom methods myself which makes it unnecessarily complicated, but is that the only way to achieve what i want?

#### Leledumbo

• Hero Member
• Posts: 8324
• Programming + Glam Metal + Tae Kwon Do = Me
##### Re: Array methods
« Reply #1 on: December 26, 2015, 10:48:49 am »

#### howardpc

• Hero Member
• Posts: 3692
##### Re: Array methods
« Reply #2 on: December 26, 2015, 11:38:12 am »
Note that if you have FPC 3.0 it is now possible to write constructs like this:

Code: Pascal  [Select][+][-]
1.
2. {\$ModeSwitch typehelpers}
3. type
4.   PointArr = array of TPoint;
5.
6.
7.   PointArrayHelper = type helper for PointArr
8.     function Contains(x: TPoint): Boolean;
9.   end;
10.
11.
12.   ...
13.
14.
15.   function PointArrayHelper.Contains(x: TPoint): Boolean;
16. var
17.   p: TPoint;
18. begin
19.   Result:=False;
20.   if (Length(Self) = 0) then
21.     Exit
22.   else begin
23.     for p in Self do
24.       if (p.x = x.x) and (p.y = x.y) then
25.         Exit(True);
26.   end;
27. end;
28.
29.
30. var
31.   pa: PointArray;
32.
33.
34.   ...
35.
36.
37.   if pa.Contains(Point(0, 3)) then
38.     ...
39.
40.