[fpc-pascal] How can I implement "thrice" in Free Pascal?

Vladimir Zhirov vvzh.lists at gmail.com
Tue Oct 18 10:52:40 CEST 2011


Andrew Pennebaker wrote:
> thrice :: a -> [a]
> thrice x = [x, x, x]
> I know the answer involves generics, but the docs don't
> offer examples using Free Pascal's built-in generic types.

The solution would require generic functions, these are
implemented in FPC trunk only. In the latest release (2.4.4)
the result you want can be achieved with overloading and some
copy-paste (that can be avoided using include files).
See attached code for an example.

However note that it does not work properly for class instances.
Since they are basically pointers the output would be three
pointers to the same class instance. AFAIK there is no way 
in FPC (and Delphi) to deep-copy arbitrary class instance because
TObject does not force us to define copy constructors.

--------------------------------------------------------
program project1;

uses
  Classes;

{$mode delphi}

type
  TIntegerArray = array of Integer;
  TStringArray = array of String;

function Thrice(AValue: Integer): TIntegerArray; overload;
var
  I: Integer;
begin
  SetLength(Result, 3);
  for I := 0 to 2 do
    Result[I] := AValue;
end;

function Thrice(const AValue: String): TStringArray; overload;
var
  I: Integer;
begin
  SetLength(Result, 3);
  for I := 0 to 2 do
    Result[I] := AValue;
end;

var
  I: Integer;
  Thrice5: TIntegerArray;
  ThriceHello: TStringArray;
  ThriceWorld: TStringList;
begin
  Thrice5 := Thrice(5);
  for I := 0 to High(Thrice5) do
    Write(Thrice5[I], ' ');

  WriteLn();

  ThriceHello := Thrice('hello');
  for I := 0 to High(ThriceHello) do
    Write(ThriceHello[I], ' ');
end.




More information about the fpc-pascal mailing list