4

Haskell 允许您定义像三次这样的函数,它接受一个类型的元素a并返回重复三次的元素列表,对于任何数据类型a

thrice :: a -> [a]
thrice x = [x, x, x]

Free Pascal 是否允许类型变量?如果没有,在 Free Pascal 中是否有另一种方法可以做到这一点?

4

3 回答 3

3

作为一个不了解 Pascal 的 haskell 人,这似乎是类似的事情。抱歉无法展开。

http://wiki.freepascal.org/Generics

于 2011-10-17T20:26:31.433 回答
1

不幸的是,FreePascal 目前只有泛型类,没有泛型函数。虽然,你的目标仍然可以实现,尽管有点尴尬。您需要定义一个新类来封装您的操作:

unit Thrice;

interface

type

generic ThriceCalculator<A> = class
public
  class function Calculate(x: A): array of A;
  // We define it as a class function to avoid having to create an object when 
  // using Calculate. Similar to C++'s static member functions.
end;

implementation

function ThriceCalculator.Calculate(x: A): array of A;
begin
  SetLength(Result, 3);
  Result[0]:= x;
  Result[1]:= x;
  Result[2]:= x;
end;

end.

现在,不幸的是,当您想将此类用于任何特定类型时,您需要对其进行专门化:

type

  IntegerThrice = specialize ThriceCalculator<Integer>;

只有这样,您才能将其用作:

myArray:= IntegerThrice.Calculate(10);

如您所见,Pascal 还不是通用编程的方法。

于 2011-10-31T20:37:28.820 回答
0

...从未来回答。

FreePascal 支持类之外的通用函数和过程。

下面的代码显示了如何将 Thrice 实现为 Times 的特例,以说明您对“FourTimes、FiveTimes 等”的询问。

该代码包括几个使用不同类型(整数、字符串、记录)的示例:

{$mode objfpc}

program Thrice;

uses sysutils;

type
   TPerson = record
      First: String;
      Age: Integer;
   end;

   generic TArray<T> = array of T;

var
   aNumber: integer;
   aWord: String;
   
   thePerson: TPerson;
   aPerson: TPerson;

generic function TimesFn<T, RT>(thing: T; times: Integer): RT;
var i: integer;
begin
   setLength(Result, times);
   for i:= 0 to times-1 do
      Result[i] := thing;      
end;
  
generic function ThriceFn<T, RT>(thing: T): RT;
begin
   Result := specialize TimesFn<T, RT>(thing, 3);
end;


begin
   { Thrice examples }
   
   for aNumber in specialize ThriceFn<Integer, specialize TArray<Integer>>(45) do
                                                  writeln(aNumber);   

   for aWord in specialize ThriceFn<String, specialize TArray<String>>('a word') do
                                                writeln(aWord);

   thePerson.First := 'Adam';
   thePerson.Age := 23;

   for aPerson in specialize ThriceFn<TPerson, specialize TArray<TPerson>>(thePerson) do
                                                   writeln(format('First: %s; Age: %d', [aPerson.First, aPerson.Age]));

   { Times example } 
   for aNumber in specialize TimesFn<Integer, specialize TArray<Integer>>(24, 10) do
                                                 writeln(aNumber);
end.
   
于 2021-01-04T21:47:48.747 回答