Remembering the Ternary Operator Syntax - ternary-operator

Anyone have a good trick to remember the standard ternary syntax?
Specifically whether the '?' or ':' comes first. I have consistently gotten this backwards over the years.

The condition you are checking is kind of like a question, so the question mark comes first.
x > 0 ? 1 : 0
Think of this statement as three English sentences: "Is x greater than 0? Then 1. Else, 0." You have one sentence for each clause in the statement.
The predicate:
x > 0 ? /* Is x greater than 0? */
The "true" branch:
1 /* Then 1. */
The "false" branch:
: 0 /* Else, 0. */

As far as remembering which symbol comes first, I just think of the fact that the first part is a question, "Is it true or not?", so the question mark goes first.
I think of the syntax in this manner
Question ? Yes : No

in python I read it as a normal English sentence:
a equals b if condition is true else c

Think of it this way: a ternary statement consists of three parts: the question, the code to execute if the answer to the question is "yes" and the code if the answer is "no". The "?" comes after the question like it does in English sentences.

"?" is a question mark so it means "if".
A colon means, "now it comes", "then do".
The good thing about the ternary operator is that you are not forced to use it, especially if you are having problems remembering the syntax. Just use an if-statement which is more readable most times.
And no - the ternary has no better performace then an if-statement.

It goes like this:
myVariable = this.testMethod() ? 'value for true case' : 'value for false case'

The syntax of ternary operators is <condition> ? <if-true> : <if-false>
? means if.
But if you put ? in front of an expression like if, the syntax becomes ? <condition> <if-true> : <if-false>.
<condition> <if-true> is hard to distinguish, so you have to add other symbols to split it, which defeats the purpose of the ternary operator to simplify the syntax.
So we have to put ? comes after it to solve this problem, so it is an inverted setting, which can be seen as (<condition> ?) <if-true> : <if-false>.
which reads: If <condition> then <if-true>, otherwise <if-false>.

If you're unit tests still pass when you get it wrong, then either it doesn't matter or your tests aren't covering enough of the paths through the code. If there's too long a gap between typing it and getting a pass/fail from the tests, that's another issue. Very few little syntax nits matter in the presence of good, fast tests.

Related

J string manipulation using only builtins

You are given a string like ))()(())(, and you wish to remove all instances of () from the string, which in this case means these two instances:
))()(())(
^^ ^^
leaving only ))()(.
I know you can use the library function stringreplace, or you could load up a regex library, but I want to know is if there is a concise way of accomplishing this the the J builtin operators exclusively?
I should clarify that my own solution was:
#~(-.#+._1&|.)#('()'&E.)
which I consider verbose -- so any similar solutions would not qualify as "concise" in my book. I'm really asking if there is a way to use a builtin (or maybe a simple combination of 2) to solve this directly. I expect this answer is no.
I think you are right that there is no ultra-concise way of expressing the operation you want to perform using just J primitives. The version I came up was very much like the one Dan, suggested above.
However given that a built in library verb rplc (based on stringreplace) performs exactly the operation you are after, I'm not sure why it would be better to replace it with a primitive.
'))()(())(' rplc '()';''
))()(
Having said that, if you can come up with a compelling case, then there is probably no reason it couldn't be added.
Not sure how concise it is, but I think that this will work:
deparen=. (-.#:(+/)#:(_1&|. ,: ])#:E. # ])
'()' deparen '))()(())('
))()(
Essentially the work is done by -. #: (+/) #: (_1&|. ,: ] )#:E. to create a bit string that removes the '()' instances using # (Copy) on the right argument.
E. identifies the positions of '()' using a bit string. Shift and laminate to get positions of '(' and ')', add them together to have 1 1 in the string where ever there is a '()' and then negate so these positions become 0 0 and are removed using Copy

Can I check strings equality in lua?

Just a straight forward beginner question, I am coding Lua stuff for Garrys Mod, learning by reading wiki and other codings.
if (self.Owner:SteamID( ) == "STEAM_0:1:44037488" ) then
the above is the code I want to use, to check to see if the STEAM ID (which I believe is a string) is equal to my exact string.
Is this viable? Or is there another way I should do it?
This should work exactly as you expect it to. In lua '==' for string will return true if contents of the strings are equal.
As it was pointed out in the comments, lua strings are interned, which means that any two strings that have the same value are actually the same string.
One thing to consider while learning Lua (from www.lua.org/source/5.2/lstring.h.html):
/*
** as all string are internalized, string equality becomes
** pointer equality
*/
#define eqstr(a,b) ((a) == (b))
String comparison in Lua is cheap, string creation may be not.
According to http://wiki.garrysmod.com/page/Player/SteamID, SteamID() returns a string so you should be able to write
if self.Owner:SteamID() == "STEAM_0:1:44037488" then
...do stuff...
end
If you ever need to confirm the type of an object, use type and print, like in this case print('type is', type(self.Owner:SteamID())) should print 'type is string'.
In lua, as answered above, '==' checks for equality.
Not saying you did this, because you didnt, but a common mistake is thinking that '=' is equality. '=' is assignment, '==' is equality.

Ternary operator should not be used on a single line in Node.js. Why?

Consider the following sample codes:
1.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)
? 'yes'
: 'no';
console.log(IsAdminUser);
2.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)?'yes': 'no';
console.log(IsAdminUser);
The 2nd sample I am very comfortable with & I code in that style, but it was told that its wrong way of doing without any supportive reasons.
Why is it recommended not to use a single line ternary operator in Node.js?
Can anyone put some light on the reason why it is so?
Advance Thanks for great help.
With all coding standards, they are generally for readability and maintainability. My guess is the author finds it more readable on separate lines. The compiler / interpreter for your language will handle it all the same. As long as you / your project have a set standard and stick to it, you'll be fine. I recommend that the standards be worked on or at least reviewed by everyone on the project before casting them in stone. I think that if you're breaking it up on separate lines like that, you may as well define an if/else conditional block and use that.
Be wary of coding standards rules that do not have a justification.
Personally, I do not like the ternary operator as it feels unnatural to me and I always have to read the line a few times to understand what it's doing. I find separate if/else blocks easier for me to read. Personal preference of course.
It is in fact wrong to put the ? on a new line; even though it doesn’t hurt in practice.
The reason is a JS feature called “Automatic Semicolon Insertion”. When a var statement ends with a newline (without a trailing comma, which would indicate that more declarations are to follow), your JS interpreter should automatically insert a semicolon.
This semicolon would have the effect that IsAdminUser is assigned a boolean value (namely the result of User.Privileges == AdminPrivileges). After that, a new (invalid) expression would start with the question mark of what you think is a ternary operator.
As mentioned, most JS interpreters are smart enough to recognize that you have a newline where you shouldn’t have one, and implicitely fix your ternary operator. And, when minifying your script, the newline is removed anyway.
So, no problem in practice, but you’re relying on an implicit fix of common JS engines. It’s better to write the ternary operator like this:
var foo = bar ? "yes" : "no";
Or, for larger expressions:
var foo = bar ?
"The operation was successful" : "The operation has failed.";
Or even:
var foo = bar ?
"Congratulations, the operation was a total success!" :
"Oh, no! The operation has horribly failed!";
I completely disagree with the person who made this recommendation. The ternary operator is a standard feature of all 'C' style languages (C,C++,Java,C#,Javascript etc.), and most developers who code in these languages are completely comfortable with the single line version.
The first version just looks weird to me. If I was maintaining code and saw this, I would correct it back to a single line.
If you want verbose, use if-else. If you want neat and compact use a ternary.
My guess is the person who made this recommendation simply wasn't very familiar with the operator, so found it confusing.
Because it's easier on the eye and easier to read. It's much easier to see what your first snippet is doing at a glance - I don't even have to read to the end of a line. I can simply look at one spot and immediately know what values IsAdminUser will have for what conditions. Much the same reason as why you wouldn't write an entire if/else block on one line.
Remember that these are style conventions and are not necessarily backed up by objective (or technical) reasoning.
The reason for having ? and : on separate lines is so that it's easier to figure out what changed if your source control has a line-by-line comparison.
If you've just changed the stuff between the ? and : and everything is on a single line, the entire line can be marked as changed (based on your comparison tool).

lexer/parser ambiguity

How does a lexer solve this ambiguity?
/*/*/
How is it that it doesn't just say, oh yeah, that's the begining of a multi-line comment, followed by another multi-line comment.
Wouldn't a greedy lexer just return the following tokens?
/*
/*
/
I'm in the midst of writing a shift-reduce parser for CSS and yet this simple comment thing is in my way. You can read this question if you wan't some more background information.
UPDATE
Sorry for leaving this out in the first place. I'm planning to add extensions to the CSS language in this form /* # func ( args, ... ) */ but I don't want to confuse an editor which understands CSS but not this extension comment of mine. That's why the lexer just can't ignore comments.
One way to do it is for the lexer to enter a different internal state on encountering the first /*. For example, flex calls these "start conditions" (matching C-style comments is one of the examples on that page).
The simplest way would probably be to lex the comment as one single token - that is, don't emit a "START COMMENT" token, but instead continue reading in input until you can emit a "COMMENT BLOCK" token that includes the entire /*(anything)*/ bit.
Since comments are not relevant to the actual parsing of executable code, it's fine for them to basically be stripped out by the lexer (or at least, clumped into a single token). You don't care about token matches within a comment.
In most languages, this is not ambiguous: the first slash and asterix are consumed to produce the "start of multi-line comment" token. It is followed by a slash which is plain "content" within the comment and finally the last two characters are the "end of multi-line comment" token.
Since the first 2 characters are consumed, the first asterix cannot also be used to produce an end of comment token. I just noted that it could produce a second "start of comment" token... oops, that could be a problem, depending on the amount of context is available for the parser.
I speak here of tokens, assuming a parser-level handling of the comments. But the same applies to a lexer, whereby the underlying rule is to start with '/*' and then not stop till '*/' is found. Effectively, a lexer-level handling of the whole comment wouldn't be confused by the second "start of comment".
Since CSS does not support nested comments, your example would typically parse into a single token, COMMENT.
That is, the lexer would see /* as a start-comment marker and then consume everything up to and including a */ sequence.
Use the regexp's algorithm, search from the beginning of the string working way back to the current location.
if (chars[currentLocation] == '/' and chars[currentLocation - 1] == '*') {
for (int i = currentLocation - 2; i >= 0; i --) {
if (chars[i] == '/' && chars[i + 1] == '*') {
// .......
}
}
}
It's like applying the regexp /\*([^\*]|\*[^\/])\*/ greedy and bottom-up.
One way to solve this would be to have your lexer return:
/
*
/
*
/
And have your parser deal with it from there. That's what I'd probably do for most programming languages, as the /'s and *'s can also be used for multiplication and other such things, which are all too complicated for the lexer to worry about. The lexer should really just be returning elementary symbols.
If what the token is starts to depend too much on context, what you're looking for may very well be a simpler token.
That being said, CSS is not a programming language so /'s and *'s can't be overloaded. Really afaik they can't be used for anything else other than comments. So I'd be very tempted to just pass the whole thing as a comment token unless you have a good reason not to: /\*.*\*/

What languages have a while-else type control structure, and how does it work?

A long time ago, I thought I saw a proposal to add an else clause to for or while loops in C or C++... or something like that. I don't remember how it was supposed to work -- did the else clause run if the loop exited normally but not via a break statement?
Anyway, this is tough to search for, so I thought maybe I could get some CW answers here for various languages.
What languages support adding an else clause to something other than an if statement? What is the meaning of that clause? One language per answer please.
Python.
Example use:
for element in container:
if element == target:
break
else:
# this will not be executed if the loop is quit with break.
raise ElementNotFoundError()
From the Python docs:
it is executed when the loop
terminates through exhaustion of the
list (with for) or when the condition
becomes false (with while), but not
when the loop is terminated by a break
statement.
There is so-called "Dijkstra's Loop" (also called "Dijkstra's Guarded Loop"). It was defined in The Guarded Command Language (GCL). You can find some information about it syntax and semantic in the above Wikipedia article at the section 6 Repetition: do.
Nowadays I actually know one programming language which supports this control struture directly. It is Oberon-07 (PDF, 70 KB). And it supports "Dijkstra's Loop" in thу form of while statement. Take a look at section 9.6. While statements in the above PDF.
WHILE m > n DO m := m – n
ELSIF n > m DO n := n – m
END
Interestingly, neither the Python or the Oberon construct are the one I've been searching for. In C, I frequently find myself often wanting an 'otherwise' or 'elsewhile' construct that is executed only if the loop was never taken. Perhaps this is the construction you are looking for as well?
So instead of:
if (condition) {
do {
condition = update(something);
} while (condition);
} else {
loop_never_taken(something);
}
I could write:
while (condition) {
condition = update(something);
} otherwhile {
loop_never_taken(something);
}
It's definitely shorter, and I would find it much clearer to read. It even translates easily into (pseudo) assembly:
while: test condition
bz elsewhile
loop: push something
call update
test: test condition
bnz loop
jmp done
elsewhile: push something
call loop_never_taken
done: ...
I feel like it's a basic enough structure that it deserves a little more sugar. But apparently there haven't been any successful language designers who rely on this structure as much as I do. I wonder how much I should read into that!

Resources