Recent

Author Topic: Feature announcement: Function References and Anonymous Functions  (Read 65278 times)

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 10997
  • Debugger - SynEdit - and more
    • wiki
Re: Feature announcement: Function References and Anonymous Functions
« Reply #105 on: April 13, 2025, 12:14:38 am »
Code: Pascal  [Select][+][-]
  1. {$ModeSwitch anonymousfunctions}

beria2

  • New Member
  • *
  • Posts: 16
Re: Feature announcement: Function References and Anonymous Functions
« Reply #106 on: April 16, 2025, 03:14:32 am »
Code: Pascal  [Select][+][-]
  1. {$ModeSwitch anonymousfunctions}


It's not that simple. Here are my compiler directives:
 {$mode objfpc}// Основной режим Object Pascal
{$ASMMODE INTEL}           // Синтаксис Intel для ассемблерных блоков
{$COPERATORS ON}           // Операторы C-style (+=, -= и т.д.)
{$GOTO ON}                 // Разрешает использование меток и goto
{$INLINE ON}               // Включение инлайнинга функций
{$MACRO ON}                // Поддержка макросов препроцессора
// Мод-свитчи:
{$MODESWITCH ADVANCEDRECORDS}  // Методы в records
{$MODESWITCH ANONYMOUSFUNCTIONS} // Анонимные функции  (sic!)
{$MODESWITCH ARRAYOPERATORS}   // Перегрузка операторов для массивов
{$MODESWITCH CLASS}           // Полная поддержка классов
{$MODESWITCH CLASSICPROCVARS} // Классические процедурные переменные
{$MODESWITCH DUPLICATELOCALS} // Разрешение дублирования имен переменных
{$MODESWITCH NESTEDPROCVARS}  // Вложенные процедурные переменные
{$MODESWITCH OUT}             // Параметры out
{$MODESWITCH POINTERTOPROCVAR} // Преобразование указателей в procvar
{$MODESWITCH RESULT}          // Использование Result в функциях
{$MODESWITCH TYPEHELPERS}     // Хелперы для типов
{$PACKENUM 4}            // Минимальный размер перечислений
{$PACKRECORDS C}         // C-совместимое выравнивание записей
{$PACKSET 4}             // Минимальный размер множеств
{$Q-}                    // Проверка переполнения
{$R-}                    // Проверка диапазона
{$T-}                    // Проверка типизированных указателей                                                       
{$H+}                    // Режим расширенного диапазона для типа integer
{$S+}                    // Выравнивание полей


type
  TProc = reference to procedure;




Компиляция проекта, режим: Default, цель: z:\Number\number.exe: Код завершения 1, ошибок: 3, подсказок: 3
Hint: Start of reading config file Z:\fpcupdeluxe\fpc\bin\x86_64-win64\fpc.cfg
Hint: End of reading config file Z:\fpcupdeluxe\fpc\bin\x86_64-win64\fpc.cfg
Verbose: Free Pascal Compiler version 3.3.1-17788-gc6d3e42129-dirty [2025/04/12] for x86_64
Verbose: Copyright (c) 1993-2025 by Florian Klaempfl and others
Note: Switching assembler to default source writing assembler
Verbose: Target OS: Win64 for x64
Verbose: Compiling number.lpr
Verbose: Compiling Bit.pas
Bit.pas(187,14) Error: Identifier not found "reference"
Bit.pas(187,24) Error: Error in type definition
Bit.pas(187,24) Error: Syntax error, ";" expected but "TO" found
Verbose: Compilation aborted
Verbose: Z:\fpcupdeluxe\fpc\bin\x86_64-win64\ppcx64.exe returned an error exitcode


TRon

  • Hero Member
  • *****
  • Posts: 4267
Re: Feature announcement: Function References and Anonymous Functions
« Reply #107 on: April 16, 2025, 03:57:58 am »
Code: Pascal  [Select][+][-]
  1. {$ModeSwitch anonymousfunctions}

It's not that simple. Here are my compiler directives:
...
{$MODESWITCH ANONYMOUSFUNCTIONS} // Анонимные функции  (sic!)
...
Code: Pascal  [Select][+][-]
  1. type
  2.   TProc = reference to procedure;
  3.  

It is actually that simple because anonymous function <> function reference.

Code: Pascal  [Select][+][-]
  1. {$modeswitch functionreferences}
  2.  

Two different concepts, two different modeswitches.
Today is tomorrow's yesterday.

Thaddy

  • Hero Member
  • *****
  • Posts: 16763
  • Ceterum censeo Trump esse delendam
Re: Feature announcement: Function References and Anonymous Functions
« Reply #108 on: April 16, 2025, 06:22:59 am »
@TRon
@beria2
Yes TRon, indeed, let's illustrate the different concepts with two more simple examples:
1. anonymous functions:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}{$modeswitch anonymousfunctions}
  2. begin
  3.   writeln(function:string
  4.              begin
  5.                 result := 'hello, World';
  6.              end());
  7. end.
2. function references:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$modeswitch functionreferences}
  2. Type
  3.   THelloWorld = reference to function:string;
  4.  
  5.   function hello:string;
  6.   begin
  7.     Result := 'hello';
  8.   end;
  9.  
  10.   function world:string;
  11.   begin
  12.     Result := ', world';
  13.   end;
  14.  
  15. var
  16.   hw:THelloWorld;
  17. begin
  18.   hw :=@hello;
  19.   write(hw());
  20.   hw :=@world;
  21.   writeln(hw());
  22. end.
1. demonstrates an anonymous function, uses no outer variables and executes the function inline.
2. demonstrates function references, a variable of the type of the function reference can point to and execute different functions with the same prototype.

Note that in these examples I use no parameters but in both cases you can use parameters for the functions or procedures.

I could not come up with simpler examples.

Wait Uhhhh,
-----------------------------------------------
warning: just because we can code follows
-----------------------------------------------
A contrived example that combines the two  :D :
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}
  2. {$modeswitch functionreferences}
  3. {$modeswitch anonymousfunctions}
  4. begin
  5.   writeln(function:string
  6.          Type
  7.             THelloWorld = reference to function:string;
  8.             function hello:string;
  9.             begin
  10.               Result := 'hello';
  11.             end;
  12.  
  13.             function world:string;
  14.             begin
  15.               Result :=', world';
  16.             end;
  17.            
  18.             var hw:THelloWorld;
  19.           begin
  20.             hw := @hello;
  21.             result:=hw();
  22.             hw := @world;
  23.             result := result+hw();
  24.           end());
  25. end.
I hope the latter will not add to the confusion.. 8)
@cdbc
Beyond cool innit?  %)


« Last Edit: April 16, 2025, 07:47:27 am by Thaddy »
Changing servers. thaddy.com may be temporary unreachable but restored when the domain name transfer is done.

beria2

  • New Member
  • *
  • Posts: 16
Re: Feature announcement: Function References and Anonymous Functions
« Reply #109 on: April 16, 2025, 01:24:08 pm »
  for I := 0 to function: integer
  begin
    if StrLen < TypeBits then Result := StrLen
    else
      Result := TypeBits;
  end() - 1 do


 :P :P :P :P

Thaddy

  • Hero Member
  • *****
  • Posts: 16763
  • Ceterum censeo Trump esse delendam
Re: Feature announcement: Function References and Anonymous Functions
« Reply #110 on: April 16, 2025, 01:43:25 pm »
 ;) That won't work.(I hope... :o )
Loop variables need to be known at compile time.
« Last Edit: April 16, 2025, 01:50:35 pm by Thaddy »
Changing servers. thaddy.com may be temporary unreachable but restored when the domain name transfer is done.

Marc

  • Administrator
  • Hero Member
  • *
  • Posts: 2645
Re: Feature announcement: Function References and Anonymous Functions
« Reply #111 on: April 16, 2025, 02:25:36 pm »
The loop variable (I) is known. The terminating expression is evaluated before the loop starts so my guess is that this is valid (not that I ever will use it)
//--
{$I stdsig.inc}
//-I still can't read someones mind
//-Bugs reported here will be forgotten. Use the bug tracker

cdbc

  • Hero Member
  • *****
  • Posts: 2064
    • http://www.cdbc.dk
Re: Feature announcement: Function References and Anonymous Functions
« Reply #112 on: April 16, 2025, 03:01:03 pm »
Hi
Quote
@cdbc
Beyond cool innit?  %)
Yup  8-) ...and to think, all of this magic happens via interfaces behind the scenes...  %) %)
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 3.6 up until Jan 2024 from then on it's both above &: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 4.99

beria2

  • New Member
  • *
  • Posts: 16
Re: Feature announcement: Function References and Anonymous Functions
« Reply #113 on: April 16, 2025, 03:08:34 pm »
;) That won't work.(I hope... :o )
Loop variables need to be known at compile time.
It's working  :-[

Thaddy

  • Hero Member
  • *****
  • Posts: 16763
  • Ceterum censeo Trump esse delendam
Re: Feature announcement: Function References and Anonymous Functions
« Reply #114 on: April 16, 2025, 04:50:44 pm »
My point was 1 and 2, which are educational. The third was a joke.. :P
« Last Edit: April 16, 2025, 04:55:37 pm by Thaddy »
Changing servers. thaddy.com may be temporary unreachable but restored when the domain name transfer is done.

cdbc

  • Hero Member
  • *****
  • Posts: 2064
    • http://www.cdbc.dk
Re: Feature announcement: Function References and Anonymous Functions
« Reply #115 on: April 16, 2025, 05:48:11 pm »
Hi
Ofc. Thaddy  ;D
I wouldn't want to see 3) in any codebase, anytime soon  ...or later for that matter  :D
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 3.6 up until Jan 2024 from then on it's both above &: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 4.99

 

TinyPortal © 2005-2018