Generic nested class function in Free Pascal - freepascal

I tried writing the following to see if I could simulate generic methods in Free Pascal 3 by combining its support for generic class functions and nested classes:
{$mode delphi}
type TFoo = class
public
type TBar<T> = class
class function Min(const A, B: T): T;
end;
end;
class function TFoo.TBar<T>.Min(const A, B: T): T;
begin
if A < B then
Result := A
else
Result := B;
end;
I have tried several syntactical variations, but I can't get it to compile no matter what. In this form, the compiler gives me a fatal error on line 8 (method identifier expected, Syntax error, ";" expected but "<" found).
What is the proper syntax for this, if at all possible?

Correct and working syntax in fpc 3.0.4, at least in mode objfpc (mode delphi not tested):
{$mode objfpc}
type TFoo = class
public
type generic TBar<T> = class
class function Min(const A, B: T): T;
end;
end;
class function TFoo.TBar.Min(const A, B: T): T;
begin
...
end;

Related

How do I pass a type to a function called in the inner constructor ("this" equivalent)?

I have a function that runs inside different structs, how to know in which struct that my function runs in.
Example:
function foo()
#here I need to find out the name of the struct this function runs (which constructor called it)
in, A or B
end
struct A
arg
function A(arg)
foo(arg)
return new(arg)
end
end
struct B
arg
function B(arg)
foo(arg)
return new(arg)
end
end
Use the instance created by new in your inner constructor to dispatch foo. Of course, you are free to customize foo to do much more varying things than just print the symbol of the type.
foo(t::T) where T = Symbol(T)
struct A
function A()
instance = new()
println("foo was called in ", foo(instance))
return instance
end
end
struct B
function B()
instance = new()
println("foo was called in ", foo(instance))
return instance
end
end
A() # prints: foo was called in A
B() # prints: foo was called in B
If it is in runtime you normally would use multiple dispatch in one way or another or pass the argument or pass the type (see other answers and comments).
However, if it is for debugging you could use stacktrace():
function foo()
st = stacktrace()[2]
println("Debug info :", st)
end
And now using your structs:
julia> A();
Debug info :A() at REPL[3]:3
julia> B();
Debug info :B() at REPL[12]:3
#EDIT if you plan to pass type an elegant high-performance solution could be:
function foo(::Type{A})
#show "typeA"
end
function foo(::Type{B})
#show "typeB"
end
struct B
function B()
foo(B)
return new()
end
end
And now:
julia> B();
"typeB" = "typeB"

Redeclare type helper in other unit, Free Pascal failed to compile

I have this unit
unit helper;
interface
{$MODE OBJFPC}
{$MODESWITCH TYPEHELPERS}
{$H+}
uses
sysutils;
type
THelloWorldHelper = type helper(TStringHelper) for string
public
function world() : string;
end;
implementation
function THelloWorldHelper.world() : string;
begin
result := self + ' world';
end;
end.
and other unit that redeclare this type helper
unit helperalias;
interface
{$MODE OBJFPC}
{$MODESWITCH TYPEHELPERS}
{$H+}
uses
helper;
type
THelloWorldHelper = helper.THelloWorldHelper;
implementation
end.
and program as follows
program helloworld;
{$MODE OBJFPC}
{$MODESWITCH TYPEHELPERS}
{$H+}
uses
helperalias;
var hello : string;
world :string;
begin
hello:='hello';
world := hello.world();
writeln(world);
end.
When I run
fpc helloworld.pas
It refused to compile with message Error: Objective-C categories and Object Pascal class helpers cannot be used as types.
If in helloword.pas, I replaced helperalias unit with helper, it worked.
I read about helper restriction.
Why is redeclaring type helper prohibited?

If a class has more than once constructor which of them gets called?

Like the titles says, if I have multiple constructors (which is not good practice), which of them gets called?
Where did you hear that it was bad practice?
You can only have one constructor with a certain parameter list order so the one that gets called is the one specified by the argument you've passed in.
public class Test {
public Test() {...}
public Test(String str, int x) {...}
}
Say later on you call:
Test test = new Test("Hello", 46);
The constructor that gets called is this one:
public Test(String str, int x) {...}
Where the String "Hello" and the number 46 are passed in str and x respectively.
What programming language?
Everything depends on the language.
For Delphi, for example, it is valid to have to have multiple constructors. Even with the same name and with different parameters (both in quantity and type). In this case builders should be overloaded.
constructor TMyClass.Create overrride;
begin
// Code here
end;
constructor TMyClass.Create(Value: integer); override;
begin
// Code here
end;
constructor TMyClass.Create(Value1: integer; Value2: string); override;
begin
// Code here
end;
The compiler on their own know which one is going to run.
Indeed, it is even legal to do this:
constructor TMyClass.Create(Value3: double);
begin
Create(Random (9), 'Hello');
end;
Ie invoke one another.
The magic of the compiler decides when and what has to execute. And I have understood that this is in all LOO. ;)

Deserialization JSON to objects with interface fields using SuperObject

I'm having trouble deserializing an object containing a interface field from json using SuperObject (serialization works fine) on DXE2. Consider the following:
ITest = interface(IInterface)
['{9E5623FF-1BC9-4FFA-919D-80C45EE24F38}']
function GetField3() : string;
procedure SetField3(Value: string);
property FField3: string read GetField3 write SetField3;
end;
TTest = class(TInterfacedObject, ITest)
private
FField3: string;
function GetField3() : string;
procedure SetField3(Value: string);
public
property Field3: string read GetField3 write SetField3;
constructor Create(Field3: string);
end;
TMyClass = class(TObject)
public
FField1: string;
FField2: string;
FTest: ITest;
constructor Create(Field1: string; Field2: string; Test: ITest);
end;
// TTest-stuff omitted for brevity.
constructor TMyClass.Create(Field1, Field2: string; Test: ITest);
begin
FField1 := Field1;
FField2 := Field2;
FTest := Test;
end;
var
MyClass: TMyClass;
MyClass2: TMyClass;
JSONObj: ISuperObject;
SuperContext: TSuperRttiContext;
begin
MyClass := TMyClass.Create('Test1', 'Test2', TTest.Create('Test3'));
SuperContext := TSuperRttiContext.Create();
JSONObj := SuperContext.AsJson<TMyClass>(MyClass);
WriteLn(JSONObj.AsString);
MyClass2 := SuperContext.AsType<TMyClass>(JSONObj);
MyClass2.Free();
ReadLn;
end.
When execution gets to TSuperRttiContext.FromJson.FromClass checking the FTest-field, the doo-doo hits the propeller in the ceiling (or table mounted, if you prefer that). At this point, Result := FromJson(f.FieldType.Handle, GetFieldDefault(f, obj.AsObject[GetFieldName(f)]), v); is called, which leads us into the interesting part of the SuperObject.pas code. I'll duplicated it here for brevity.
procedure FromInterface;
const soguid: TGuid = '{4B86A9E3-E094-4E5A-954A-69048B7B6327}';
var
o: ISuperObject;
begin
if CompareMem(#(GetTypeData(TypeInfo).Guid), #soguid, SizeOf(TGUID)) then
begin
if obj <> nil then
TValue.Make(#obj, TypeInfo, Value) else
begin
o := TSuperObject.Create(stNull);
TValue.Make(#o, TypeInfo, Value);
end;
Result := True;
end else
Result := False;
end;
The value assigned to soguid is that of ISuperObject, so clearly the two won't match (I'm testing for ITest, remember?). And so I'm a little lost of what to make of this. Is it illegal to deserialize any object composed of one or more interface fields?
This seems like such a common use case, that I find it hard to believe. I can appreciate the fact that knowing what implementation of a given interface to choose may be non-trivial. Yet, I see from the comment in the preamble, that interfaced objects are supposed to be supported - http://code.google.com/p/superobject/source/browse/trunk/superobject.pas#47.
Sure would be great if anyone have solved this out there. Thanks! :)

Defining Scala Function Differently [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between method and function in Scala
Two ways of defining functions in Scala. What is the difference?
There are 2 ways to define a function.
scala> def a : (Int, Int) => Int = {(s:Int, t:Int) => s + t}
a: (Int, Int) => Int
scala> a
res15: (Int, Int) => Int = <function2>
scala> def b(s:Int, t:Int) : Int = s+t
b: (s: Int, t: Int)Int
scala> b
<console>:9: error: missing arguments for method b in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
b
^
scala> b(3,4)
res17: Int = 7
scala> a(3,4)
res18: Int = 7
Is there any difference in how I define functions a and b? Why do I have missing arguments error with b?
b is not a function, but a method. You can however turn b into a function by adding the _ as the compiler mentions. val f = b _. But you should only do this, if you want to pass a method of an object to a method/function that takes a function as parameter. If you just want to define a function go the normal way.
But to answer your question, there is another way:
val f = new Function2[Int,Int,Int] {
def apply(x: Int, y: Int) = x + y
}
Object Oriented languages (e.g. java) typically have classes and classes have methods, while functions are not "first-class citizens", meaning you can't assign a function directly to a variable or put a few functions in a list or send them as arguments to other functions.
If you want to send a function around in java, you have to create a class with a method and send the class around.
For instance, if you want to have a function that calculates the double of its input, you have to put it in a class, like this:
class Doubler
{
public int apply(int a)
{
return a * 2;
}
}
In functional programming languages, like Haskell, functions are "first-class", and you can store them in variables and send them around.
doubleIt :: Integer -> Integer
doubleIt x = 2 * x
As a beautiful combination of functional and object oriented, scala has both methods and functions.
// a function like in haskell
val doubleIt = (x:Int) => x * 2
// a method in an object like in java
object Doubler {
def apply(x:Int) = x * 2
}
In scala def always defines a method. Note that the REPL wraps everything you write in an object with a main (in order to be able to compile and execute it on the fly), but writing a def something not wrapped in a class/object/trait in a program would not compile.
Scala also has a few more perks to offer, to decrease the disconnect between object and first-class functions.
For one thing, the "apply" method over there in the Doubler object definition in scala is sort of magic.
Given the definition above, you can write Doubler(2) and scala's compiler will transform this into Doubler.apply(2) and happily return 4.
So you can sort of use objects as functions.
But also, you can (by putting a _ sign after the call to a method) transform the method into a real function and (say) assign it to a val.
scala> val d = Doubler.apply _
d: Int => Int = <function1>
scala> d(2)
res1: Int = 4
On the other hand, the way scala makes a function like val doubleIt = (x:Int) => x * 2 into a first class "thing" is by turning it into something like this behind your back.
object Doubler extends Function[Int, Int] {
def apply(x: Int) = x*2
}
val doubleIt = Doubler
So, yeah... a function is actually still a class with a method, more or less like in java. Except that scala does it for you and gives you a lot of syntactic sugar to use that generated class as you would use an actual function.
To make things even more interesting, since functions are first-class, one of the things you can do with them in scala is use them as return values from other functions or methods.
So when you wrote def a : (Int, Int) => Int = {(s:Int, t:Int) => s + t} you actually defined a method, called a that returns a function. It may be confusing at first (and at second, and at third....) but around the fourth time around it will probably start looking beautiful. At least that's what it did for me.