4
votes

In my program I have a need to get percent often in code. For now i have this function to solve it

function percent(whole, part: double):double;
 begin
      percent:= whole * part / 100;
 end;

I was wondering is there any way I could make new operator so I can write only something like: a:=100%20, and get wanted result. It would also should be able to be used as: c:=b/a; or : c:=c/a;

3
Note that the % operator is used for mod in many languages, and many people would think that your new operator means exactly that, i.e. that a := 100%20; is equivalent to a := 100 mod 20;. In other words, the big problem with self-made operators is that they can easily be misunderstood. - Rudy Velthuis

3 Answers

3
votes

You can define operators in pascal, but only on record type. It is called operator overloading and you can read up here. What you do is define your own record type data, and then overload standard operators such as = < > % etc to do what you want them to do. Here is a simple example:

Interface

Type
  TMyFloatType = record
    value: Extended;

    class operator Implicit(n: Extended): TMyFloatType;
    class operator Explicit(n: Extended): TMyFloatType;
    class operator Equal(a, b: TMyFloatType): Boolean;
    class operator GreaterThan(a, b: TMyFloatType): Boolean;
  end;


Implementation


class operator TMyFloatType.Implicit(n: Extended): TMyFloatType;
begin
 result.value := n;
end;

class operator TMyFloatType.Explicit(n: Extended): TMyFloatType;
begin
 result.value := n;
end;

class operator TMyFloatType.Equal(a, b: TMyFloatType): Boolean;
begin
  result := (a.value = b.value);
end;

class operator TMyFloatType.GreaterThan(a, b: TMyFloatType): Boolean;
begin
  result := (a.value > b.value);
end;

You can then use that like regular variables:

procedure Test;
var
  a, b: TMyFloatType;
Begin
  // first assign some values to a and b
  a := 3.14;
  b := 2.7;      

  if a > b then
  Begin
    // Do something
  End;
End;

Operators that you can overload do include math operators too, like + - / * mod div etc.

Now, having said that, I do believe it wouldn't be very convenient to actually implement this to avoid a simple function, but hey, your choice.

Point here is that you can overload an operator to do your bidding. I believe to do a calculation like percentage := a % 20; you need to overload the Modulus operator.

0
votes

There's no way to do this. You can only use the function

0
votes

I would just use a function. By the way, your function

function percent(whole, part: double):double; begin percent:= whole * part / 100; end;

is incorrect. It should be

percent := 100.0 * part / whole;