Overloaded operators

From Rosetta Code
Revision as of 21:51, 13 September 2021 by PureFox (talk | contribs) (Added Wren)
Overloaded operators is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

An overloaded operator can be used on more than one data type, or represents a different action depending on the context. For example, if your language lets you use "+" for adding numbers and concatenating strings, then one would say that the "+" operator is overloaded.

Task

Demonstrate overloaded operators in your language, by showing the different types of data they can or cannot operate on, and the results of each operation.



6502 Assembly

Many commands have multiple addressing modes, which alter the way a command is executed. On the 6502 most of these are in fact different opcodes, using the same mnemonic. <lang 6502asm>LDA #$80 ;load the value 0x80 (decimal 128) into the accumulator. LDA $80 ;load the value stored at zero page memory address $80 LDA $2080 ;load the value stored at absolute memory address $2080. LDA $80,x ;load the value stored at memory address ($80+x). LDA ($80,x) ;use the values stored at $80+x and $81+x as a 16-bit memory address to load from. 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>

Wren

Library: Wren-date


All of Wren's operators can be overloaded except: &&, ||, ?: and =. It is not posssible to create new operators from scratch.

When an operator is overloaded it retains the same arity, precedence and associativity as it has when used in its 'natural' sense.

The standard library contains several instances of overloading the + and * operators which are demonstrated below.

Otherwise, operator overloading can be used without restriction in user defined classes.

However, whilst it is very useful for classes representing mathematical objects, it should be used sparingly otherwise as code can become unreadable if it is used inappropriately. <lang ecmascript>import "/date" for Date

var s1 = "Rosetta " var s2 = "code" var s3 = s1 + s2 // + operator used to concatenate two strings System.print("s3 = %(s3)")

var s4 = "a" * 20 // * operator used to provide string repetition System.print("s4 = %(s4)")

var l1 = [1, 2, 3] + [4] // + operator used to concatenate two lists System.print("l1 = %(l1)")

var l2 = ["a"] * 8 // * operator used to create a new list by repeating another System.print("l2 = %(l2)")

// the user defined class Date overloads the - operator to provide the interval between two dates var d1 = Date.new(2021, 9, 11) var d2 = Date.new(2021, 9, 13) var i1 = (d2 - d1).days System.print("i1 = %(i1) days")</lang>

Output:
s3 = Rosetta code
s4 = aaaaaaaaaaaaaaaaaaaa
l1 = [1, 2, 3, 4]
l2 = [a, a, a, a, a, a, a, a]
i1 = 2 days