Last active
January 4, 2021 21:49
-
-
Save joubertnel/04d3407188c3cfc09f73ec2600edda19 to your computer and use it in GitHub Desktop.
Pascal - generic function example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ FreePascal: Generic function example prompted by StackOverflow question: | |
"Does Free Pascal have type variable like Haskell?" | |
https://stackoverflow.com/questions/7799037/does-free-pascal-have-type-variables-like-haskell } | |
{$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. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
$ fpc thrice.pas
Free Pascal Compiler version 3.2.0 [2020/05/31] for x86_64
Copyright (c) 1993-2020 by Florian Klaempfl and others
Target OS: Darwin for x86_64
Compiling thrice.pas
thrice.pas(28,20) Warning: function result variable of a managed type does not seem to be initialized
thrice.pas(28,20) Warning: function result variable of a managed type does not seem to be initialized
thrice.pas(28,20) Warning: function result variable of a managed type does not seem to be initialized
thrice.pas(37,20) Warning: function result variable of a managed type does not seem to be initialized
Assembling (pipe) thrice.s
Linking thrice
63 lines compiled, 0.3 sec
4 warning(s) issued
$ ./thrice
45
45
45
a word
a word
a word
First: Adam; Age: 23
First: Adam; Age: 23
First: Adam; Age: 23
24
24
24
24
24
24
24
24
24
24
$