i have this unit:
unit Main.TIns;
interface
type
TIns = record
private type
TInsArray = array [0..90] of Integer;
var
FInsArray: TInsArray;
public
class operator Implicit(const Value: Integer): TIns;
class operator Add(const Elem1: TIns; const Elem2: Integer): TIns;
end;
implementation
class operator TIns.Implicit(const Value: Integer): TIns;
var
iIndex: Integer;
begin
if Value = 0 then
for iIndex := 0 to 90 do Result.FInsArray[iIndex] := 0;
end;
class operator TIns.Add(const Elem1: TIns; const Elem2: Integer): TIns;
begin
Inc(Result.FInsArray[0]);
Result.FInsArray[Result.FInsArray[0]] := Elem2;
end;
end.
And main program is:
program InsMain;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Main.TIns in 'Main.TIns.pas';
var
s: TIns;
begin
s := 0; // Initialize ins; similar t := [] //
s := s + 5; // Add a element, in this case 5 //
writeln(s[0]); // Read number of element in s, should to be 1 //
end.
The problem is that i receive this error: [DCC Error] InsMain.dpr(20): E2149 Class does not have a default property.
Why i can't read element of array?
I have thinked to solve add a variable MyVal for example, doing so:
type
TIns = record
private type
TInsArray = array [0..90] of Integer;
var
FInsArray: TInsArray;
public
MyVal: TInsArray;
class operator Implicit(const Value: Integer): TIns;
class operator Add(const Elem1: TIns; const Elem2: Integer): TIns;
end;
then i modify add so:
class operator TIns.Add(const Elem1: TIns; const Elem2: Integer): TIns;
begin
Inc(Result.FInsArray[0]);
Result.FInsArray[Result.FInsArray[0]] := Elem2;
MyVal := Result; // <--- error E2124 here.
end;
and writing:
writeln(s.MyVal[0]);
not return error, but give error on Add, writing: [DCC Error] Main.TIns.pas(31): E2124 Instance member 'MyVal' inaccessible here, so not understood where i mistake.
In TExtracts.Add you never initialize the result with the content of Elem1. That is why you always end with an empty result.
Update: Your change did more harm than good! Now you are writing to a record field inside a class method. This is not possible as the error message is trying to make clear. Let alone that I don't know what MyVal shall be good for.
Here is a working example of what you are trying to do :
type
TIns = record
private type
TInsArray = array [0..90] of Integer;
private var
FInsArray : TInsArray;
function GetItem( index : integer) : integer;
function GetCount : integer;
public
class operator Implicit(const Value: Integer): TIns;
class operator Add(const Elem1: TIns; const Elem2: Integer): TIns;
property Items[index : integer] : integer read GetItem; default;
property Count : integer read GetCount;
end;
function TIns.GetCount: integer;
begin
Result := Self.FInsArray[0];
end;
function TIns.GetItem(index: integer): integer;
begin
Result := Self.FInsArray[index];
end;
class operator TIns.Implicit(const Value: Integer): TIns;
var
iIndex: Integer;
begin
if Value = 0 then
for iIndex := 0 to 90 do Result.FInsArray[iIndex] := 0;
end;
class operator TIns.Add(const Elem1: TIns; const Elem2: Integer): TIns;
begin
Result := Elem1;
Inc(Result.FInsArray[0]);
Result.FInsArray[Result.FInsArray[0]] := Elem2;
end;
var
i : integer;
s,s1 : TIns;
begin
s := 0; // Initialize ins; similar t := [] //
s1 := 0;
s := s + 5; // Add a element, in this case 5 //
s1 := s1 + 10;
for i := 1 to s.Count do
writeln( 'S[',i,']=',s[i]); // Read element values in s
for i := 1 to s1.Count do
writeln( 'S1[',i,']=',s1[i]); // Read element values in s1
ReadLn;
end.
To pull out array elements, declare the default property Items.
Expose the element count via the property Count.
And as Uwe pointed out, set the Result to Elem1 first in the Add operator.
Related
I am trying to create a nullable data type in Delphi:
type
TNullable<T> = record
public
Value: T;
IsNull: Boolean;
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: Variant): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
end;
So far so good, but what to assign as a null literal so that the nullable data type remains of its basic type? For example:
var
v: TNullable<Integer>;
begin
//What type is this "null"? A Variant null?
//How TNullable<Integer> could remain of Integer after the assignment?
v := null;
//How to compare this "null"? Compare to what type?
if v = null then begin
end;
end;
Let us assume that null is the variant null:
class operator TNullable<T>.Implicit(const AValue: Variant): TNullable<T>;
begin
if VarIsNull(AValue) or VarIsClear(AValue) then begin
Result.IsNull := True;
Result.Value := Default(T);
end
else begin
Result.IsNull := False;
Result.Value := AValue; //Version 1: Incompatible types: 'T' and 'Variant'!!!
Result.Value := T(AValue); //Version 2: Invalid typecast!!!
//Should I write a big "case" block here in order to handle each data type?!
end;
end;
Do you have ideas?
Null in this case is indeed a Variant, see System.Variants.Null. Using a Variant in this situation is not a good idea, in part because of the assignment troubles you are seeing with it.
A better option is to define a distinct type to represent your null values (similar to nullptr_t in C++11 and later), eg:
type
TNullValue = record
end;
TNullable<T{: record}> = record
public
Value: T;
HasValue: Boolean;
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: TNullValue): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
// add these...
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
...
end;
const
NullValue: TNullValue;
...
class operator TNullable<T>.Implicit(const AValue: T): TNullable<T>;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable<T>.Implicit(const AValue: TNullable<T>): T;
begin
if AValue.HasValue then
Result := AValue.Value
else
Result := Default(T); // or raise an exception
end;
class operator TNullable<T>.Implicit(const AValue: TNullValue): TNullable<T>;
begin
Result.Value := Default(T);
Result.HasValue := False;
end;
class operator TNullable<T>.Explicit(const AValue: T): TNullable<T>;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable<T>.Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
Result := not A.HasValue;
end;
class operator TNullable<T>.NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
begin
Result := A.HasValue;
end;
var
v: TNullable<Integer>;
begin
v := NullValue;
if v = NullValue then begin
...
end;
if v <> NullValue then begin
...
end;
end;
I have following statement in my Delphi 7 code.
TMyCharSet = set of char;
When I migrated that code to Delphi XE4, I am getting following compiler warning at above line.
W1050 WideChar reduced to byte char in set expressions. Consider using 'CharInSet' function in 'SysUtils' unit.
How should I redeclare TMyCharSet?
A set cannot contain items larger than a byte. Since Char in UniCode Delphi is a WideChar which is two bytes in size, a set type is an inappropriate container.
Here is an example of a generic set type based on a record, TSet<T>. This means that you don't have to think about creation and destruction of variables of this type. Use this type as a container for simple types. I tried to mimic most of the behavior of the set type.
Addition and subtraction of items can be done with + and - operators. Added the in operator as well.
Note: The record holds the data in a dynamic array. Assigning a variable to another will make both variables using the same dynamic array. A Copy-On-Write (COW) protection built-in will prevent a change in one variable to be reflected on the other one.
unit GenericSet;
interface
Uses
System.Generics.Defaults;
Type
TSet<T> = record
class operator Add(const aSet: TSet<T>; aValue: T) : TSet<T>; overload;
class operator Add(const aSet: TSet<T>; const aSetOfT: TArray<T>) : TSet<T>; overload;
class operator Add(const aSet1: TSet<T>; const aSet2: TSet<T>) : TSet<T>; overload;
class operator Subtract(const aSet: TSet<T>; aValue: T): TSet<T>; overload;
class operator Subtract(const aSet: TSet<T>; const aSetOfT: TArray<T>) : TSet<T>; overload;
class operator Subtract(const aSet1: TSet<T>; const aSet2: TSet<T>) : TSet<T>; overload;
class operator In(aValue: T; const aSet: TSet<T>): Boolean; overload;
class operator In(const aSetOf: TArray<T>; const aSet: TSet<T>): Boolean; overload;
class operator In(const aSet1: TSet<T>; const aSet2: TSet<T>): Boolean; overload;
private
FSetArray : TArray<T>;
function GetEmpty: Boolean;
public
procedure Add(aValue: T);
procedure AddSet(const setOfT: array of T); overload;
procedure AddSet(const aSet: TSet<T>); overload;
procedure Remove(aValue: T);
procedure RemoveSet(const setOfT: array of T); overload;
procedure RemoveSet(const aSet : TSet<T>); overload;
function Contains(aValue: T): Boolean; overload;
function Contains(const aSetOfT: array of T): Boolean; overload;
function Contains(const aSet : TSet<T>): Boolean; overload;
procedure Clear;
property Empty: Boolean read GetEmpty;
end;
implementation
procedure TSet<T>.Add(aValue: T);
begin
if not Contains(aValue) then begin
SetLength(FSetArray,Length(FSetArray)+1);
FSetArray[Length(FSetArray)-1] := aValue;
end;
end;
class operator TSet<T>.Add(const aSet: TSet<T>; aValue: T): TSet<T>;
begin
Result.AddSet(aSet.FSetArray);
Result.Add(aValue);
end;
class operator TSet<T>.Add(const aSet: TSet<T>; const aSetOfT: TArray<T>): TSet<T>;
begin
Result.AddSet(aSet.FSetArray);
Result.AddSet(aSetOfT);
end;
class operator TSet<T>.Add(const aSet1, aSet2: TSet<T>): TSet<T>;
begin
Result.AddSet(aSet1.FSetArray);
Result.AddSet(aSet2.FSetArray);
end;
procedure TSet<T>.AddSet(const setOfT: array of T);
var
i : Integer;
begin
for i := 0 to High(setOfT) do
Self.Add(setOfT[i]);
end;
procedure TSet<T>.AddSet(const aSet: TSet<T>);
begin
AddSet(aSet.FSetArray);
end;
procedure TSet<T>.RemoveSet(const setOfT: array of T);
var
i : Integer;
begin
for i := 0 to High(setOfT) do
Self.Remove(setOfT[i]);
end;
procedure TSet<T>.RemoveSet(const aSet: TSet<T>);
begin
RemoveSet(aSet.FSetArray);
end;
class operator TSet<T>.Subtract(const aSet1, aSet2: TSet<T>): TSet<T>;
begin
Result.AddSet(aSet1.FSetArray);
Result.RemoveSet(aSet2.FSetArray);
end;
class operator TSet<T>.Subtract(const aSet: TSet<T>;
const aSetOfT: TArray<T>): TSet<T>;
begin
Result.AddSet(aSet.FSetArray);
Result.RemoveSet(aSetOfT);
end;
class operator TSet<T>.Subtract(const aSet: TSet<T>; aValue: T): TSet<T>;
begin
Result.AddSet(aSet.FSetArray);
Result.RemoveSet(aValue);
end;
class operator TSet<T>.In(aValue: T; const aSet: TSet<T>): Boolean;
begin
Result := aSet.Contains(aValue);
end;
class operator TSet<T>.In(const aSetOf: TArray<T>; const aSet: TSet<T>): Boolean;
begin
Result := aSet.Contains(aSetOf);
end;
class operator TSet<T>.In(const aSet1: TSet<T>; const aSet2: TSet<T>): Boolean;
begin
Result := aSet2.Contains(aSet1.FSetArray);
end;
function TSet<T>.Contains(aValue: T): Boolean;
var
i : Integer;
c : IEqualityComparer<T>;
begin
c := TEqualityComparer<T>.Default;
Result := false;
for i := 0 to Length(FSetArray)-1 do
if c.Equals(FSetArray[i],aValue) then
Exit(True);
end;
function TSet<T>.GetEmpty: Boolean;
begin
Result := (Length(FSetArray) = 0);
end;
procedure TSet<T>.Clear;
begin
SetLength(FSetArray,0);
end;
function TSet<T>.Contains(const aSetOfT: array of T): Boolean;
var
i : Integer;
begin
Result := High(aSetOfT) >= 0;
for i := 0 to High(aSetOfT) do
begin
Result := Contains(ASetOfT[i]);
if not Result then
Exit(false);
end;
end;
function TSet<T>.Contains(const aSet: TSet<T>): Boolean;
begin
Result := Contains(aSet.FSetArray);
end;
procedure TSet<T>.Remove(aValue: T);
var
i : Integer;
c : IEqualityComparer<T>;
begin
c := TEqualityComparer<T>.Default;
for i := 0 to Length(FSetArray)-1 do
begin
if c.Equals(FSetArray[i],aValue) then
begin
SetLength(FSetArray,Length(FSetArray)); // Ensure unique dyn array
if (i < Length(FSetArray)-1) then
FSetArray[i] := FSetArray[Length(FSetArray)-1]; // Move last element
SetLength(FSetArray,Length(FSetArray)-1);
Break;
end;
end;
end;
end.
A sample test program:
program ProjectGenericSet;
{$APPTYPE CONSOLE}
uses
GenericSet in 'GenericSet.pas';
var
mySet,mySet1 : TSet<Char>;
begin
mySet.AddSet(['A','B','C']);
WriteLn(mySet.Contains('C'));
WriteLn(mySet.Contains('D')); // False
mySet := mySet + 'D';
WriteLn(mySet.Contains('D'));
WriteLn('D' in mySet);
mySet := mySet - 'D';
WriteLn(mySet.Contains('D')); // False
mySet := mySet + TArray<Char>.Create('D','E');
WriteLn(mySet.Contains('D'));
WriteLn(mySet.Contains(['A','D']));
mySet1 := mySet;
// Testing COW
mySet1.Remove('A');
WriteLn(mySet.Contains('A'));
mySet1:= mySet1 + mySet;
WriteLn(mySet1.Contains('A'));
mySet := mySet1;
mySet1.Clear;
WriteLn(mySet.Contains('A'));
ReadLn;
end.
You get the warning because XE4 uses WideChar for variable of Char type (and WideString for String), so Char takes 2 bytes instead of 1 byte now. Now it is possible to keep unicode characters in String/Char, but for same reason it is impossible to use set of char anymore (in Delphi it is fixed size, 32-bytes bits map and can keep up to 256 items so).
If you use only chars from range #0..#127 (only latin/regular symbols), then you can just replace Char -> AnsiChar (but when you will assign it from Char you will see another warning, you will have to use explicit type conversion to suppress it).
If you need national/unicode symbols, then there is no "ready to use" structure in Delphi, but you can use Tdictionary for this purpose:
type
TEmptyRecord = record end;
TSet<T> = class(TDictionary<T,TEmptyRecord>)
public
procedure Add(Value: T); reintroduce; inline;
procedure AddOrSetValue(Value: T); reintroduce; inline;
function Contains(Value: T):Boolean; reintroduce; inline;
end;
procedure TSet<T>.Add(Value: T);
var Dummy: TEmptyRecord;
begin
inherited AddOrSetValue(Value, Dummy);
end;
procedure TSet<T>.AddOrSetValue(Value: T);
var Dummy: TEmptyRecord;
begin
inherited AddOrSetValue(Value, Dummy);
end;
function TSet<T>.Contains(Value: T): Boolean;
begin
result := inherited ContainsKey(Value);
end;
Of course you will have initialize at as any other regular class.
But it will be still quite efficient (not so fast as "set of" of course, just because "set" is always limited by 256 items max size but highly optimized).
Alternatively you can create your own set class for unicode chars as map of bits, it will take 8kb of memory to keep all the bits and will be almost as fast as "set of".
See fourm suggestions from web:
if not (CharInSet(Key,['0'..'9',#8]) then key := #0;
From: http://www.activedelphi.com.br/forum/viewtopic.php?t=66035&sid=f5838cc7dc991f7b3340e4e2689b222a
When I use TObjectDictionary, where TKey is object, my application work uncorrectly.
I have two units, thats contain two classes. First unit:
unit RubTerm;
interface
type
TRubTerm = Class(TObject)
private
FRubricName: String;
FTermName: String;
public
property RubricName: String read FRubricName;
property TermName: String read FTermName;
constructor Create(ARubricName, ATermName: String);
end;
implementation
constructor TRubTerm.Create(ARubricName, ATermName: String);
begin
Self.FRubricName := ARubricName;
Self.FTermName := ATermName;
end;
end;
And second unit:
unit ClassificationMatrix;
interface
uses
System.Generics.Collections, System.Generics.Defaults, System.SysUtils, RubTerm;
type
TClassificationMatrix = class(TObject)
private
FTable: TObjectDictionary<TRubTerm, Integer>;
public
constructor Create;
procedure TClassificationMatrix.AddCount(ADocsCount: Integer; ARubName, ATermName: String);
function TClassificationMatrix.GetCount(ARubName, ATermName: String): Integer;
end;
implementation
constructor TClassificationMatrix.Create;
begin
FTable := TObjectDictionary<TRubTerm, Integer>.Create;
end;
procedure TClassificationMatrix.AddCount(ADocsCount: Integer; ARubName, ATermName: String);
var
ARubTerm: TRubTerm;
begin
ARubTerm := TRubTerm.Create(ARubName, ATermName);
FTable.Add(ARubTerm, ADocsCount);
end;
function TClassificationMatrix.GetCount(ARubName, ATermName: String): Integer;
var
ARubTerm: TRubTerm;
begin
ARubTerm := TRubTerm.Create(ARubName, ATermName);
FTable.TryGetValue(ARubTerm, Result);
end;
end;
But this fragment of code work unnormal:
procedure TestTClassificationMatrix.TestGetCount;
var
DocsCountTest: Integer;
begin
FClassificationMatrix.AddCount(10, 'R', 'T');
DocsCountTest := FClassificationMatrix.GetCount('R', 'T');
end;
// DocsCountTest = 0! Why not 10? Where is problem?
Thanks!
The fundamental issue here is that the default equality comparer for your type does not behave the way you want it to. You want equality to mean value equality, but the default comparison gives reference equality.
The very fact that you are hoping for value equality is a strong indication that you should be using a value type rather than a reference type. And that's the first change that I would suggest.
type
TRubTerm = record
RubricName: string;
TermName: string;
class function New(const RubricName, TermName: string): TRubTerm; static;
class operator Equal(const A, B: TRubTerm): Boolean;
class operator NotEqual(const A, B: TRubTerm): Boolean;
end;
class function TRubTerm.New(const RubricName, TermName: string): TRubTerm;
begin
Result.RubricName := RubricName;
Result.TermName := TermName;
end;
class operator TRubTerm.Equal(const A, B: TRubTerm): Boolean;
begin
Result := (A.RubricName=B.RubricName) and (A.TermName=B.TermName);
end;
class operator TRubTerm.NotEqual(const A, B: TRubTerm): Boolean;
begin
Result := not (A=B);
end;
I've added TRubTerm.New as a helper method to make it easy to initialize new instances of the record. And for convenience, you may also find it useful to overload the equality and inequality operators, as I have done above.
Once you switch to a value type, then you would also change the dictionary to match. Use TDictionary<TRubTerm, Integer> instead of TObjectDictionary<TRubTerm, Integer>. Switching to a value type will also have the benefit of fixing all the memory leaks in your existing code. Your existing code creates objects but never destroys them.
This gets you part way home, but you still need to define an equality comparer for your dictionary. The default comparer for a record will be based on reference equality since strings, despite behaving as value types, are stored as references.
To make a suitable equality comparer you need to implement the following comparison functions, where T is replaced by TRubTerm:
TEqualityComparison<T> = reference to function(const Left, Right: T): Boolean;
THasher<T> = reference to function(const Value: T): Integer;
I'd implement these as static class methods of the record.
type
TRubTerm = record
RubricName: string;
TermName: string;
class function New(const RubricName, TermName: string): TRubTerm; static;
class function EqualityComparison(const Left,
Right: TRubTerm): Boolean; static;
class function Hasher(const Value: TRubTerm): Integer; static;
class operator Equal(const A, B: TRubTerm): Boolean;
class operator NotEqual(const A, B: TRubTerm): Boolean;
end;
Implementing EqualityComparison is easy enough:
class function TRubTerm.EqualityComparison(const Left, Right: TRubTerm): Boolean;
begin
Result := Left=Right;
end;
But the hasher requires a little more thought. You need to hash each field individually and then combine the hashes. For reference:
Quick and Simple Hash Code Combinations
What is the canonical way to write a hasher function for TEqualityComparer.Construct?
The code looks like this:
{$IFOPT Q+}
{$DEFINE OverflowChecksEnabled}
{$Q-}
{$ENDIF}
function CombinedHash(const Values: array of Integer): Integer;
var
Value: Integer;
begin
Result := 17;
for Value in Values do begin
Result := Result*37 + Value;
end;
end;
{$IFDEF OverflowChecksEnabled}
{$Q+}
{$ENDIF}
function GetHashCodeString(const Value: string): Integer;
begin
Result := BobJenkinsHash(PChar(Value)^, SizeOf(Char) * Length(Value), 0);
end;
class function TRubTerm.Hasher(const Value: TRubTerm): Integer;
begin
Result := CombinedHash([GetHashCodeString(Value.RubricName),
GetHashCodeString(Value.TermName)]);
end;
Finally, when you instantiate your dictionary, you need to provide an IEqualityComparison<TRubTerm>. Instantiate your dictionary like this:
Dict := TDictionary<TRubTerm,Integer>.Create(
TEqualityComparer<TRubTerm>.Construct(
TRubTerm.EqualityComparison,
TRubTerm.Hasher
)
);
A Dictionary depends on a key value. You are storing a reference to an object in the key. If you create two objects that are setup identically the have different values and hence different keys.
var
ARubTerm1: TRubTerm;
ARubTerm2: TRubTerm;
begin
ARubTerm1 := TRubTerm.Create('1', '1');
ARubTerm2 := TRubTerm.Create('1', '1');
// ARubTerm1 = ARubTerm2 is not possible here as ARubTerm1 points to a different address than ARubTerm2
end;
Instead you could uses a String as the First Type Parameter in the TObjectDictonary that is based on RubricName and TermName. With this you would then get back the same value.
It should also be noted, that above code in XE2 creates two memory leaks. Every object created must be freed. Hence this section of code also is leaking memory
function TClassificationMatrix.GetCount(ARubName, ATermName: String): Integer;
var
ARubTerm: TRubTerm;
begin
ARubTerm := TRubTerm.Create(ARubName, ATermName);
FTable.TryGetValue(ARubTerm, Result);
end;
Given all of that. If you want to use an Object as a Key you can do it with a Custom Equality Comparer. Here is your example changed to implement IEqualityComparer<T>, and fix a few memory leaks.
unit ClassificationMatrix;
interface
uses
Generics.Collections, Generics.Defaults, SysUtils, RubTerm;
type
TClassificationMatrix = class(TObject)
private
FTable: TObjectDictionary<TRubTerm, Integer>;
public
constructor Create;
procedure AddCount(ADocsCount: Integer; ARubName, ATermName: String);
function GetCount(ARubName, ATermName: String): Integer;
end;
implementation
constructor TClassificationMatrix.Create;
var
Comparer : IEqualityComparer<RubTerm.TRubTerm>;
begin
Comparer := TRubTermComparer.Create;
FTable := TObjectDictionary<TRubTerm, Integer>.Create([doOwnsKeys],TRubTermComparer.Create);
end;
procedure TClassificationMatrix.AddCount(ADocsCount: Integer; ARubName, ATermName: String);
var
ARubTerm: TRubTerm;
begin
ARubTerm := TRubTerm.Create(ARubName, ATermName);
FTable.Add(ARubTerm, ADocsCount);
end;
function TClassificationMatrix.GetCount(ARubName, ATermName: String): Integer;
var
ARubTerm: TRubTerm;
begin
ARubTerm := TRubTerm.Create(ARubName, ATermName);
try
if Not FTable.TryGetValue(ARubTerm, Result) then
result := 0;
finally
ARubTerm.Free;
end;
end;
end.
And the RubTerm.pas unit
unit RubTerm;
interface
uses Generics.Defaults;
type
TRubTerm = Class(TObject)
private
FRubricName: String;
FTermName: String;
public
property RubricName: String read FRubricName;
property TermName: String read FTermName;
constructor Create(ARubricName, ATermName: String);
function GetHashCode: Integer; override;
end;
TRubTermComparer = class(TInterfacedObject, IEqualityComparer<TRubTerm>)
public
function Equals(const Left, Right: TRubTerm): Boolean;
function GetHashCode(const Value: TRubTerm): Integer;
end;
implementation
constructor TRubTerm.Create(ARubricName, ATermName: String);
begin
Self.FRubricName := ARubricName;
Self.FTermName := ATermName;
end;
{ TRubTermComparer }
function TRubTermComparer.Equals(const Left, Right: TRubTerm): Boolean;
begin
result := (Left.RubricName = Right.RubricName) and (Left.TermName = Right.TermName);
end;
function TRubTermComparer.GetHashCode(const Value: TRubTerm): Integer;
begin
result := Value.GetHashCode;
end;
//The Hashing code was taken from David's Answer to make this a complete answer.
{$IFOPT Q+}
{$DEFINE OverflowChecksEnabled}
{$Q-}
{$ENDIF}
function CombinedHash(const Values: array of Integer): Integer;
var
Value: Integer;
begin
Result := 17;
for Value in Values do begin
Result := Result*37 + Value;
end;
end;
{$IFDEF OverflowChecksEnabled}
{$Q+}
{$ENDIF}
function GetHashCodeString(const Value: string): Integer;
begin
Result := BobJenkinsHash(PChar(Value)^, SizeOf(Char) * Length(Value), 0);
end;
function TRubTerm.GetHashCode: Integer;
begin
Result := CombinedHash([GetHashCodeString(Value.RubricName),
GetHashCodeString(Value.TermName)]);
end;
end.
Is there a function in the Delphi standard library to search string arrays for a particular value?
e.g.
someArray:=TArray<string>.Create('One','Two','Three');
if ArrayContains(someArray, 'Two') then
ShowMessage('It contains Two');
There is absolutely no need to reinvent the wheel. StrUtils.MatchStr does the job.
procedure TForm1.FormCreate(Sender: TObject);
var
someArray: TArray<string>;
begin
someArray:=TArray<string>.Create('One','Two','Three');
if MatchStr('Two', someArray) then
ShowMessage('It contains Two');
end;
Note the parameter order convention.
Another note: MatchStr is a canonicalized name assigned to this function somewhen in between Delphi 7 and Delphi 2007. Historical name is AnsiMatchStr (convention is the same as in the rest of RTL: Str/Text suffix for case-sensitivity, Ansi prefix for MBCS/Locale)
I wrote one I modeled after the old Clipper AScan function (tested in XE). #RRUZ's answer is more correct (there is one existing), but mine doesn't require the array to be sorted first and is fast enough on small arrays. (It also works in pre-generics versions of Delphi.) I also overload it for various types of array - here are the implementations for string and integer:
// Returns the 0-based index of Value if it's found in the array,
// -1 if not. (Similar to TStrings.IndexOf)
function AScan(const Ar: array of string; const Value: string): Integer; overload;
var
i: Integer;
begin
Result := -1;
for i := Low(Ar) to High(Ar) do
if SameText(Ar[i], Value) then
begin
Result := i;
Break
end;
end;
function AScan(const Ar: array of Integer; const Value: Integer): Integer; overload;
var
i: Integer;
begin
Result := -1;
for i := Low(Ar) to High(Ar) do
if (Ar[i] = Value) then
begin
Result := i;
Break
end;
end;
procedure TForm2.FormShow(Sender: TObject);
var
someStrArray: TArray<string>;
someIntArray: TArray<Integer>;
Idx: Integer;
begin
someStrArray := TArray<string>.Create('One', 'Two', 'Three');
Idx := AScan(someStrArray, 'Two');
if Idx > -1 then
ShowMessage(Format('It contains Two at index %d', [Idx]))
else
ShowMessage('Not found');
someIntArray := TArray<Integer>.Create(8, 16, 32);
Idx := AScan(someIntArray, 32);
if Idx > -1 then
ShowMessage(Format('It contains 32 at %d', [Idx]))
else
ShowMessage('16 not found');
end;
For versions of Delphi that support generics, here's a version that doesn't require the array to be sorted, and that also allows you to provide the comparison function if needed:
Interface:
type
TGenericsUtils = class
public
class function AScan<T>(const Arr: array of T; const Value: T; const Comparer: IEqualityComparer<T>): Integer; overload;
class function AScan<T>(const Arr: array of T; const Value: T): Integer; overload;
end;
Implementation
class function TGenericsUtils.AScan<T>(const Arr: array of T; const Value: T): Integer;
begin
Result := AScan<T>(Arr, Value, TEqualityComparer<T>.Default);
end;
class function TGenericsUtils.AScan<T>(const Arr: array of T; const Value: T;
const Comparer: IEqualityComparer<T>): Integer;
var
i: Integer;
begin
for i := Low(Arr) to High(Arr) do
if Comparer.Equals(Arr[i], Value) then
Exit(i);
Exit(-1);
end;
Test code:
var
AIntTest: TIntegerDynArray;
AStrTest: TStringDynArray;
begin
AIntTest := TIntegerDynArray.Create(12, 15, 6, 1, 4, 9, 5);
AStrTest := TStringDynArray.Create('One', 'Six', 'Three', 'Four', 'Twelve');
WriteLn('AIntTest contains 9 at index ', TGenericsUtils.AScan<Integer>(AIntTest, 9));
WriteLn('AStrTest contains ''Four'' at index ', TGenericsUtils.AScan<String>(AStrTest, 'Four'));
ReadLn;
end.
you can use the TArray.BinarySearch function, which is part of the Generics.Collections unit.
check this sample
{$APPTYPE CONSOLE}
{$R *.res}
uses
Generics.Defaults,
Generics.Collections,
System.SysUtils;
Var
someArray: TArray<string>;
FoundIndex : Integer;
begin
try
someArray:=TArray<string>.Create('a','b','c');
if TArray.BinarySearch<String>(someArray, 'b', FoundIndex, TStringComparer.Ordinal) then
Writeln(Format('Found in index %d',[FoundIndex]))
else
Writeln('Not Found');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Note: BinarySearch requires that the array be sorted.
In Delphi XE2, I'm trying to overload the in operator on a record to allow me to check whether the value represented by the record is part of a set. My code looks like this:
type
MyEnum = (value1, value2, value3);
MySet = set of MyEnum;
MyRecord = record
Value: MyEnum;
class operator In(const A: MyRecord; B: MySet): Boolean;
end;
class operator MyRecord.In(const A: MyRecord; B: MySet): Boolean;
begin
Result := A.Value in B;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
S: MySet;
begin
R.Value := value1;
S := [value1, value2];
Button1.Caption := BoolToStr(R in S);
end;
The code fails to compile. For the statement R in S the compiler says: Incompatible types MyRecord and MyEnum.
How can I overload the In operator on MyRecord so that R in S will evaluate to True in the above code?
For the in operator to work the right operand must be of the record type since it's a set operator and not a binary operator. In your case it is the left operand.
So the following will work:
type
MyRecord = record
Value: MyEnum;
class operator In(const A: MyRecord; const B: MySet): Boolean;
end;
MyRecord2 = record
Value: MySet;
class operator In(const A: MyRecord; const B: MyRecord2): Boolean;
class operator In(const A: MyEnum; const B: MyRecord2): Boolean;
end;
class operator MyRecord.In(const A: MyRecord; const B: MySet): Boolean;
begin
Result := A.Value in B;
end;
class operator MyRecord2.In(const A: MyRecord; const B: MyRecord2): Boolean;
begin
Result := A.Value in B.Value;
end;
class operator MyRecord2.In(const A: MyEnum; const B: MyRecord2): Boolean;
begin
Result := A in B.Value;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
R2: MyRecord2;
begin
R.Value := value1;
R2.Value := [value1, value2];
if R in R2 then;
if value1 in R2 then;
end;
Well, you can almost do this, but you may not want to. AFAIK, class operators only work on the class (or record) they are defined within, so both R and S in your code have to be TMyRecord. With some injudicious use of implicit casting, we get the following:
unit Unit2;
interface
type
MyEnum = (value1, value2, value3);
MySet = set of MyEnum;
MyRecord = record
Value: MyEnum;
ValueSet: MySet;
class operator Implicit(A: MyEnum): MyRecord;
class operator Implicit(A: MySet): MyRecord;
class operator In (Left,Right:MyRecord): Boolean;
end;
implementation
class operator MyRecord.Implicit(A: MyEnum): MyRecord;
begin
Result.Value := A;
end;
class operator MyRecord.Implicit(A: MySet): MyRecord;
begin
Result.ValueSet := A;
end;
class operator MyRecord.In(Left, Right: MyRecord): Boolean;
begin
Result:= left.Value in Right.ValueSet;
end;
end.
The following will now complile, and even work:
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
S: MyRecord;
begin
R.Value := value1;
S := [value1,value2,value3];
Button1.Caption := BoolToStr(R In S,true);
end;
Which, I'm sure we will all agree, is much more elegant than 'BoolToStr(R.Value in S)'.
However the following will also compile, but give the wrong result:
procedure TForm1.Button1Click(Sender: TObject);
var
R: MyRecord;
S: MyRecord;
begin
R.Value := value1;
S := [value1,value2,value3];
Button1.Caption := BoolToStr(S In R,true);
end;
So, as Dorin commented, better to just have dull, staid old 'BoolToStr(R.Value in S)'. Unless of course you are being paid per line of code. And a bonus for bug-fixing.