Overloaded operators: Difference between revisions

Added Algol 68
m (→‎{{header|Phix}}: added an opinion, and concatenation of integers and floats)
(Added Algol 68)
Line 17:
LDA ($80),y ;use the values stored at $80 and $81 as a 16-bit memory address to load from. Load from that address + y.</lang>
 
=={{header|ALGOL 68}}==
This overrides the standard integer + operator and provides an overloaded TOSTRING operator.
Also, the + operator is overloaded to operate on an INT left-hand operand and a BOOL right-hand operand.
<lang algol68>BEGIN
# Algol 68 allows operator overloading, both of existing operators and new ones #
# Programmer defined operators can be a "bold word" (uppercase word) or a symbol #
# Symbolic operators can be one or two characters, optionally followed by := or #
# =:, =: can also be defined as an operator (Allowed in Algol 68G, possibly not #
# in other implementations) #
# the characters allowed in a symbolic operator depends on the implementation #
# but would include +, -, *, /, <, =, > #
 
# define a new TOSTRING operator and overload it #
OP TOSTRING = ( INT n )STRING: whole( n, 0 ); # returns a string representation of n in the minimum width #
OP TOSTRING = ( BOOL b )STRING: IF b THEN "true" ELSE "false" FI;
# overide a standard operator #
INT a = 10, b = 11, c = 21;
BEGIN
OP + = ( INT a, INT b )INT: a - b;
# + between strings is a standard operator that does string concation #
print( ( TOSTRING a + " ""+"" " + TOSTRING b + " = " + TOSTRING ( a + b ) + " = " + TOSTRING c + "? " + TOSTRING ( ( a + b ) = c )
, newline
)
)
END;
# same print, with the stndard + #
print( ( TOSTRING a + " + " + TOSTRING b + " = " + TOSTRING ( a + b ) + " = " + TOSTRING c + "? " + TOSTRING ( ( a + b ) = c )
, newline
)
);
# overload + to allow a BOOL to be added to an INT #
OP + = ( INT a, BOOL b )INT: IF b THEN a + 1 ELSE a FI;
print( ( TOSTRING a + " ""+"" " + TOSTRING ( a = 10 ) + " = " + TOSTRING ( a + ( a = 10 ) ), newline ) )
END</lang>
{{out}}
<pre>
10 "+" 11 = -1 = 21? false
10 + 11 = 21 = 21? true
10 "+" true = 11
</pre>
 
=={{header|F_Sharp|F#}}==
3,038

edits