+ 1
How to create my own operator(something like +) in any programming language?
2 Answers
+ 3
Kotlin code:
// Provide this[index] access to the list for read access.
operator fun get(index: Int) = list[index]
// Provide this[index] access to the list for write access.
operator fun set(index: Int, value: Int) {
list[index] = value
}
C++ code:
// Provide this[index] access for read/write.
int& operator[](const int index) {
Ā Ā Ā Ā return list[index];
}
Python code:
// Provide this[index] access to the list for read access.
def __getitem__(self, index):
return self.list[index]
// Provide this[index] access to the list for write access.
def __setitem__(self, index, value):
self.list[index] = value
+ 2
Ideally you'd use functions. i.e, to cube a number:
function cbrt(num){
return Math.pow(num, 3);
}
console.log(cbrt(5));
//prints 125 to the console
As for actual operators such as + or -, I don't think this is possible.