Advertisement
sglienke

IfThenElse proposal

May 15th, 2015
444
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. program IfThenElse_Proposal;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. uses
  6.   System.SysUtils;
  7.  
  8. type
  9.   Generics = record
  10.     class function IfThenElse<T>(condition: Boolean;
  11.       trueCase, falseCase: TFunc<T>): T; static; inline;
  12.   end;
  13.  
  14. class function Generics.IfThenElse<T>(condition: Boolean; trueCase,
  15.   falseCase: TFunc<T>): T;
  16. begin
  17.   if condition then
  18.     Result := trueCase
  19.   else
  20.     Result := falseCase;
  21. end;
  22.  
  23. procedure Main;
  24. var
  25.   a, b, c: Integer;
  26. begin
  27.   a := 10;
  28.   b := 0;
  29.   c := Generics.IfThenElse<Integer>(b <> 0,
  30.     function: Integer
  31.     begin
  32.       Result := a div b
  33.     end,
  34.     function: Integer
  35.     begin
  36.       Result := 0;
  37.     end);
  38.   (*  Short syntax:
  39.   c := IfThenElse(b <> 0, a div b, 0);
  40.   // What do we need?
  41.   // 1. standalone generic functions without the need to define them
  42.   // inside a static class (or record)
  43.   // 2. return type inference. c is of type Integer so it does not need to
  44.   // be specified explicitly and it now can construct the TFunc<T> arguments
  45.   // 3. implicit assignment compatibility of an expression to a TFunc<T> (or
  46.   // lazy of T if you want a new language construct for it to distinguish better)
  47.   *)
  48. end;
  49.  
  50. begin
  51.   try
  52.     Main;
  53.   except
  54.     on E: Exception do
  55.       Writeln(E.ClassName, ': ', E.Message);
  56.   end;
  57. end.
Advertisement
RAW Paste Data Copied
Advertisement