Code Thoughts: A Contradiction Operator
There is a word in Spanish that is used to affirmatively negate or contradict a previous declaration: "sino". For example, in English I might say "I don't like cats, but dogs." In Spanish, this would be "No me gustan los gatos, sino los perros." In this example, sino is used in place of the English "but", which would in Spanish normally be "pero". But in this case, since we are directly contradicting a previous declaration while retaining some of its qualities, we use sino. The part we are inverting with sino is "I don't like cats"; we are taking the quality of "not liking something" from the first section and replacing it with something we do like in the next section.
I started imagining what this would look in a programming language. The key quality of the word sino is contradiction. A simple construction in code would be something like "Set variable a equal to not b, but c," meaning that if a equals b, then set it to c instead. Here it is handled with an if statement and a ternary operator.
// if statement
if (a == b) {
a = c;
}
// ternary
a = a == b ? c : a;
Using the example earlier, this could be something like this:
var likedAnimal = "cat";
// if statement
if (likedAnimal == "cat") {
likedAnimal = "dog";
}
// ternary
likedAnimal = likedAnimal == "cat" ? "dog" : likedAnimal;
If there were a sino operator in code, what would it look like? A sino operator would be able to handle either case above in the exact same way. A proper syntactic sugar would be able to do it in fewer terms than other solutions, and the if statement above is clearly the longer form of the two. To handle this shorter than what could be done with a ternary operator, here's what I propose:
a = b ? c;
It uses the single question mark from the ternary operator, but omits the colon. What it is doing is setting a equal c if it is equal to b. If not, nothing happens. It just removes parts of the ternary operator, further shortening the statement. The lack of a colon would indicate to the interpreter or compiler that the statement is a sino statement. Since the statement is a sino statement, a is checked to see if it is equal to be, and if so, set it to c instead. It could be used to make sure some value is always transformed into another, or possibly for quick state flipping. In practice, it would look something like:
likedAnimal = "cat" ? "dog";
Is it pointless? Most likely. Ternary operators already exist, and they are short and easy to use. But PHP added the null coalescing operator recently, which looks very similar, so there is always a slight chance things as simple as this are found useful. Either way, it's fun to imagine what turning parts of an actual language into code would look like.
Comments:
Leave a Comment
Submit