### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Functional programming in Pascal  (Read 10584 times)

#### mr-highball

• Full Member
• Posts: 205
##### Re: Functional programming in Pascal
« Reply #75 on: August 04, 2019, 07:29:24 am »
As a proof of concept I decided to implement the "map" functional method using ezthreads. It makes use of the new method generics, so to try it out you'll have to compile with trunk, but here's a simple example, where the input is a generic string list that gets '_modified' appended to each item

Code: Pascal  [Select][+][-]
1. {\$mode delphi}
2. {\$ModeSwitch nestedprocvars}
3.
5.
6. uses
8.
9. procedure TestSimpleList;
10. var
11.   LList : TFPGList<String>;
12.   LResult : IFPGListResult<String>;
13.   I: Integer;
14.
15.   (*
16.     method passed into map to perform some simple processing
17.   *)
18.   function Start(Const AThread : IEZThread; Const AItem : String) : String;
19.   begin
20.     Result := AItem + '_modified';
21.   end;
22.
23. begin
24.   //input list with a few entries
25.   LList := TFPGList<String>.Create;
28.
29.   WriteLn('--Before--');
30.   for I := 0 to Pred(LList.Count) do
31.     WriteLn(LList[I]);
32.
33.   //now we should be able to call map with on our list
34.   LResult := Map<String>(LList, Start);
35.
36.   //await the result before assigning new values to the list
37.   Await(LResult);
38.
39.   //assign the modified values
40.   LList.Assign(LResult.Result);
41.
42.   WriteLn('--After--');
43.   for I := 0 to Pred(LList.Count) do
44.     WriteLn(LList[I]);
45.   LList.Free;
46. end;
47.
48. begin
49.   TestSimpleList;
50. end.
51.
52.
One thing to note is that the processing is done in a separate thread, so Await(IEZThread) is called to wait until it's finished.
Attached is the result after running

here's the link to my tester app if anyone wants to play around with it: