Recent

Author Topic: order of evaluation of overloaded functions  (Read 1571 times)

srvaldez

  • New Member
  • *
  • Posts: 47
order of evaluation of overloaded functions
« on: September 10, 2024, 03:28:26 pm »
hello all
I ran into this problem using FreeBasic where I had written the overloaded functions and operators, but I have the same symptom when using FreePascal, and here my only contribution is this tiny test, I had nothing to do with the GMP bindings, they came with the FPC distribution
Code: [Select]
{$mode objfpc}{$H+}

program my_example2;

uses
    sysutils, math, gmp;
 
var
    c: MPInteger;

function calc(N: MPInteger): MPInteger;

begin
    c+=1;
    calc:=N*c;
end;

var
    n: MPInteger;

begin
    n:=calc(2)+calc(3)+calc(4);
    writeln(format('calculation = %s', [string(n)]));
    writeln('should equal 20 if calculated from left to right');
end.
Quote
calculation = 16
should equal 20 if calculated from left to right
the order that this expression is evaluated is from right to left; n:=calc(2)+calc(3)+calc(4);
c=1, calc(4) -> 4
c=2, calc(3) -> 6
c=3, calc(2) -> 6; the total is 16 but if evaluated from left to right should equal 20
« Last Edit: September 10, 2024, 03:42:05 pm by srvaldez »

Kays

  • Hero Member
  • *****
  • Posts: 604
  • Whasup!?
    • KaiBurghardt.de
Re: order of evaluation of overloaded functions
« Reply #1 on: September 10, 2024, 05:15:41 pm »
Evaluation order is not related to operator precedence. Indeed summation operators are left‑associative, but this does not determine the evaluation order.
Quote
The order of evaluation of the operands of an operator is implementation‑dependent. A standard program must not make any assumption about this order. The left operand might be evaluated before or after the right operand, or they might be evaluated in parallel. In fact, sometimes one operand might not be evaluated at all for some values of the other operand. […]
Kathleen Jensen, Niklaus Wirth: Pascal – user manual and report (4th revised ed.). p. 166. DOI 10.1007/978‑1‑4612‑4450‑9. ISBN 978‑0‑387‑97649‑5.

Yours Sincerely
Kai Burghardt

BrunoK

  • Hero Member
  • *****
  • Posts: 570
  • Retired programmer
Re: order of evaluation of overloaded functions
« Reply #2 on: September 10, 2024, 05:38:23 pm »
As far as my limited mathematical knowledge goes, addition is commutable, thus there is no reason to expect, from a  compiler,  any order in an addition.

If a involved function has a side effect  (modifies a variable) involving the result, it is the problem of the programmer.

Khrys

  • Jr. Member
  • **
  • Posts: 90
Re: order of evaluation of overloaded functions
« Reply #3 on: September 11, 2024, 07:36:01 am »
FPC makes no guarantees on this (taken from the reference guide):

Quote from: https://www.freepascal.org/docs-html/3.2.0/ref/refch12.html
Remark The order in which expressions of the same precedence are evaluated is not guaranteed to be left-to-right. In general, no assumptions on which subexpression is evaluated first should be made in such a case.

The compiler will decide which subexpression to evaluate first based on optimization rules. Thus, in the following expression:

  a := g(3) + f(2);

f(2)  may be executed before  g(3). This behavior is distinctly different from Delphi or Turbo Pascal.

If one expression must be executed before the other, it is necessary to split up the statement using temporary results:

  e1 := g(3); 
  a  := e1 + f(2);

Recently there was a similiar discussion on this forum about the order of parameter evaluation (it too is under the compiler's discretion, unlike Delphi)

Thaddy

  • Hero Member
  • *****
  • Posts: 15641
  • Censorship about opinions does not belong here.
Re: order of evaluation of overloaded functions
« Reply #4 on: September 11, 2024, 09:43:05 am »
The order of Pascal evaluation is a mathematical fallacy and very easy to get trapped by it. It does not adhere to the basics of +, -, * and /. In Pascal multiplication comes before addition or substraction:
1+2 * 3 should be 9, not 7....(go figure my lost time over the years..) >:D O:-)
I wonder where most CS got their silly ideas from..
If I smell bad code it usually is bad code and that includes my own code.

bytebites

  • Hero Member
  • *****
  • Posts: 672
Re: order of evaluation of overloaded functions
« Reply #5 on: September 11, 2024, 10:14:08 am »
Random evaluation order is not optimization.

Thaddy

  • Hero Member
  • *****
  • Posts: 15641
  • Censorship about opinions does not belong here.
Re: order of evaluation of overloaded functions
« Reply #6 on: September 11, 2024, 10:30:30 am »
It is not random, alas, but then again I started to understand math when logic got involved.
I never paided much attention during math lessons. please ignore.
I used my time to throw a yellow fish in the teachers drinking glass and started fishing with a small rod.

The fish was from expanding paper, not a living creature. This happened in 1970.
The rod was taken from my parents bakery, used for marsipan gnomes.
« Last Edit: September 11, 2024, 11:06:04 am by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

PascalDragon

  • Hero Member
  • *****
  • Posts: 5672
  • Compiler Developer
Re: order of evaluation of overloaded functions
« Reply #7 on: September 19, 2024, 09:52:07 pm »
The order of Pascal evaluation is a mathematical fallacy and very easy to get trapped by it. It does not adhere to the basics of +, -, * and /. In Pascal multiplication comes before addition or substraction:
1+2 * 3 should be 9, not 7....(go figure my lost time over the years..) >:D O:-)
I wonder where most CS got their silly ideas from..

I don't know what kind of Math you learned, but in good, old Algebra multiplication has higher precedence than addition, and thus 1 + 2 * 3 is 7, not 9 and any good compiler as well as calculator will return the same here.

ccrause

  • Hero Member
  • *****
  • Posts: 942
Re: order of evaluation of overloaded functions
« Reply #8 on: September 20, 2024, 07:15:51 am »
The order of Pascal evaluation is a mathematical fallacy and very easy to get trapped by it. It does not adhere to the basics of +, -, * and /. In Pascal multiplication comes before addition or substraction:
1+2 * 3 should be 9, not 7....(go figure my lost time over the years..) >:D O:-)
I wonder where most CS got their silly ideas from..
Interestingly this exact example is discussed in order of operations with the answer of 7.

MarkMLl

  • Hero Member
  • *****
  • Posts: 7622
Re: order of evaluation of overloaded functions
« Reply #9 on: September 20, 2024, 09:52:28 am »
Leaving aside Thaddy's tenebrations which I feel aren't helpful, I think the issue is this.

If we replace OP's original function calc() with three identical functions calcA() through calcC() for ease of discussion:

Code: Pascal  [Select][+][-]
  1. n := calcA(2) + calcB(3) + calcC(4);
  2.  

Even if the precedence and ordering of the arithmetic additions are universally agreed, there is no guarantee that the three functions calcA() through calcC() which comprise the operands are evaluated in any specified sequence.

This could possibly be viewed as an unspoken extension of the "short circuiting" of Boolean expressions:

Code: Pascal  [Select][+][-]
  1. b := boolA(2) and boolB(3) and boolC(4);
  2.  

the expression will proceed from left to right in all cases, but assuming that boolA() has evaluated true then if boolB() evaluates false then either boolC() will never be evaluated, or boolC()'s result (and in theory at least) all side effects will be discarded as a casualty of speculative execution.

Interestingly, I was reading about a Pascal implementation a couple of days ago where for..do was parallelised, which resulted in the controlled statements being evaluated in arbitrary order hence as a matter of course the control variable having no defined value on completion. This sort of thing might not be done as routine (as of this year at least), but I think it's important to bear the possibility in mind as a matter of style.

MarkMLl
« Last Edit: September 20, 2024, 11:23:10 am by MarkMLl »
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

440bx

  • Hero Member
  • *****
  • Posts: 4531
Re: order of evaluation of overloaded functions
« Reply #10 on: September 20, 2024, 01:10:10 pm »
The evaluation order will usually respect operator precedence as established and accepted in mathematics.

Within that, there are two things (that come to mind) that can affect the order in which equal precedence operations are carried out and those are, the way the expression is parsed (often but, not always recursive) and re-arrangement due to optimizations.

In an expression where the operators have equal precedence, as the one presented by the OP, it will be the parsing algorithm and the optimizer that will determine the evaluation sequence.

That's quite likely why most compilers documentation simply state that the order of evaluation is not guaranteed (it's much easier to say that than to go into all the evaluation details resulting from parsing algorithms that may change and the optimizer's abilities which may also change in subsequent releases.)

Ultimately, mathematical operator precedence is (at least in the majority of cases) respected.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

MarkMLl

  • Hero Member
  • *****
  • Posts: 7622
Re: order of evaluation of overloaded functions
« Reply #11 on: September 20, 2024, 02:04:09 pm »
The evaluation order will usually respect operator precedence as established and accepted in mathematics.

Since when has "this program will usually give the correct result" been acceptable performance?

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

Warfley

  • Hero Member
  • *****
  • Posts: 1573
Re: order of evaluation of overloaded functions
« Reply #12 on: September 20, 2024, 02:05:12 pm »
Note the term to describe this is operator associativity. The right most associativity displayed here makes sense considering that the FPC is an recursive descent LL(1) parser, so it will look at the first + and then recursively descent into the left hand side of the expression creating a rightmost evaluation order.

There also seems to be no documentation stating associativity of the operator. That said, it's a bit odd, because other languages do this. For example the C and C++ standards specifically define the arithmetic operators to be left associative, which is also the common definition in mathematics (but for example do not specify the order of operations for function parameters). In other languages like Haskell you can when defining your own operators even say if they are left or right associative.

So it makes technical sense to be implemented that way, but mathematically it's a bit odd especially when compared with other languages.

440bx

  • Hero Member
  • *****
  • Posts: 4531
Re: order of evaluation of overloaded functions
« Reply #13 on: September 20, 2024, 02:31:24 pm »
The evaluation order will usually respect operator precedence as established and accepted in mathematics.

Since when has "this program will usually give the correct result" been acceptable performance?

MarkMLl
I'm not sure when it happened but, I've seen "unusual" behavior claimed as being right too many times.  As a result. now I have a tendency to "guard" my statements.

You don't have to go far to find such statements, just a few posts above this one, "someone" claimed that 1 + 2 * 3 should equal 9 instead of 7. 

Another instance that comes to mind but, I don't remember the details involved MS Excel, there was situation where it broke mathematical rules and MS implied that what Excel was doing was right (why would anyone care what Gauss or Euler may think ?)

This is age of covfefe ;)
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

MarkMLl

  • Hero Member
  • *****
  • Posts: 7622
Re: order of evaluation of overloaded functions
« Reply #14 on: September 20, 2024, 02:42:14 pm »
You don't have to go far to find such statements, just a few posts above this one, "someone" claimed that 1 + 2 * 3 should equal 9 instead of 7. 

Yes, I saw it. And I remember a thread a few days ago where somebody else was totally unable to grasp the idea that the language explicitly said that certain behaviour was undefined (which I alluded to in my earlier post).

I'd like to think that some of us are made of sterner stuff.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

 

TinyPortal © 2005-2018