How to make TComparer work with Proc or Pointer?

How to make TComparer work with Proc or Pointer?

TComparer.Construct(
function(const Left, Right: TProc): Integer
begin
Result := TComparer.Default.Compare(Integer(@Left), Integer(@Right));
end);

https://gist.github.com/dipold/99e47c218f3986fd5c2e71bc4fadecd8
https://gist.github.com/dipold/99e47c218f3986fd5c2e71bc4fadecd8

Comments

  1. That code is just wrong. Per definition TArray.BinarySearch only works on a sorted list. And your list is not sorted.

    I suggest to use a TList and just call Remove there and be done.

    Anyway. TComparer.Default is enough - this would be used by the TList internally to find the correct index in the backing array to remove.

    I posted working code to your gist.

    ReplyDelete
  2. TProc is an interface. Your code compares the address of the variables holding references to that interface, with some 32 bit pointer truncation thrown in to the mix.

    What's wrong with: TComparer.Default?

    {$APPTYPE CONSOLE}

    uses
    System.SysUtils, System.Generics.Defaults;

    var
    Proc1, Proc2, Proc3: TProc;
    Comparer: IComparer;

    begin
    Proc1 := procedure begin end;
    Proc2 := procedure begin end;
    Proc3 := Proc1;
    Comparer := TComparer.Default;
    Writeln(IntToStr(Comparer.Compare(Proc1, Proc2)));
    Writeln(IntToStr(Comparer.Compare(Proc1, Proc3)));
    Readln;
    end.


    Your gist does binary search which obviously is only applicable on an ordered list. You did not order your list. So that's not going to work. Perhaps you need to step back and get more on top of the basics here since you seem to be writing code on very shaky foundations.

    ReplyDelete
  3. Sorry.. when copying the code, I forgot the line for sort:
    TArray.Sort(ArrayProcs);

    The TComparer.Default; works fine... I can not believe I have not tried default comparator before asking ...

    Thank you guys..

    ReplyDelete
  4. Rafael Dipold If you do a sort the array your output will not be as you expect. I am not sure if due to the way anonymous methods are implemented this is deterministic but I would not count on it. In my test after a sort the order of the anonymous methods in the array was C, B, A. After removing B that you now can properly find the output will be C, A and not A, C as you wrote in your comment.

    If you only have a few elements a binary search does not have any benefit over a linear search anyway.

    ReplyDelete
  5. Yes, I see, but the order does not matter for my case. I just kidding with the possibility to use a Observer pattern with anonymous methods:

    https://gist.github.com/dipold/ceb079d1b1e78f3edcda6214cf970251

    Thanks

    ReplyDelete
  6. Well, you can do as you wish but typically in an observer I expect the notifiers to be notified in the order I added them or at least a deterministic one but not in some random order that results from their memory location.

    ReplyDelete

Post a Comment