inactive ? #"inactive": #"active" syntax? - objective-c

Can someone explain the inactive ? #"inactive": #"active"?
The ? : is a boolean conditional structure (wrong term) it seems but I'm not quite getting it. Don't know what it is called so can't look it up.
Seems something like:
someBooleanValue ? if it is false use what is before colon : else use
what is after
I get that it is being used to determine which string to use as the format token (in the code below). I just don't know what this ? : bit is called and what limitations/cautions/abuses there may be with it.
(and isn't ObjC like rilly hard to format in a civilized way)
UIAlertView* av = [[UIAlertView alloc] initWithTitle:#"Hey"
message:[NSString
stringWithFormat:#"While %#, I received a local notification: %#",
inactive ? #"inactive": #"active", n.alertBody]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];

This ?: thing is called a conditional operator or a ternary operator.
It's represents a simple condition
if ( CONDITION )
x = a;
else
x = b;
that can be translated to
x = CONDITION ? a : b
From that you can probably derive the functionality you're trying to accomplish/understand. Keep in mind that, although you could probably use it as a substitute to the normal if/else-if/else structure, it is considered bad programming the usage of the ternary operator out of any "assignment related action".
In the wikipedia page for it you can find a great variety of examples of the conditional operators used in different programming languages. Check this one too, the ternary operator page.
Obs: turns out that a ternary operator is not necessarily a conditional expression, but rather any operator that takes three arguments. Since for most of the programming languages the only ternary operator is the inline-if... well, that's what it's usually called.

It is called conditional operator, a kind of ternary operator (as opposed to more familiar binary a+b or unary !flag operators).
Conditional operator takes a condition, evaluates it, and returns its second or third operand depending on that result.

You can read more information here.
The use of this operator can greatly reduce code length when a lot of simple ifs are involved.

It's a ternary operator, but you have it backwards -- if the boolean is true, then do the thing before the colon, otherwise, the one after.

This is called the ternary operator and it works exactly the way you described it:
expression ? value if true : value if false;
For instance, you could use it for something like this to avoid a if - else:
int maxValue = a > b ? a : b;
Edit: #dasblinkenlight is correct, the operator you're talking about is actually called a conditional operator, which is a kind of ternary operator.

Related

Any practical differences in between "==" vs "in" or "if in" when checking string index?

Are there any practical differences between examples below and is better use one than others?
s = 'this#mail.is'
for i in range(len(email)):
print('#' in email[i])
#vs
for i in range(len(email)):
print(email[i] == '#')
#or
if '#' in email:
There is no practical difference... for your example here...
In essence, (as explained here and here), with in, python calls the underlying __contains__ function.
Thus, in your example. It makes no difference.
On the other hand, one could create a module and define a differente behavior for the __contains__ function.
I guess this would be done more for of an academic purpose, but it could still be made.
in checks for substrings
"a" in "apple" > True
== checks if it is exactly the same
b=10;
if(b==10)

What is the “and” and “or” Operator in Kotlin?

I used an || operator within the Kotlin IDEA but was throwing an error. This confused me, one of the first queries when searching google was a closed stack overflow thread with a snarky "answer" comment which wasn't helpful.
The first query in google hit is some function "or" gibberish.
My code:
if(inputAmount >= 0 || inputAmount = -99)
I understand what is "wrong". there was some logic errors the second part of the "if" statement should have been inputAmount == -99. In my case, the code needed to further be adjusted because of the actual type that was being used.
if(inputAmount >= 0.0 || inputAmount.toInt() == -99)
This appears to be different then other languages in that other languages just simply allow you to have your "logic" error with the "inputAmount = -99". So the '||' operator is allowed and is similar to most other languages.
So first step if encounter this error is to make sure your logic is correct. (check)
infix functions > sense according to the documentation "or" and "and" are infix functions that don't use the short circuit, is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'?
when referring to the infix 'or' how do people refer to that in Kotlin?
in boolean logic takes statements. A=b is a statement that is always true
No, it isn't. In C, C++ and Java it's an expression, and its value is the value of b. If b is false, it's false, if b is 10, it's 10. And you really don't want to confuse "statements" in programming languages with "statements" in logic; they are entirely different things.
Separately, C and C++ (but not Java) allow || to work on all integral types, and not just booleans (because they didn't originally have booleans as a separate type).
when referring to the infix function 'or' how do Kotlin folk typically refer to that?
Bitwise or for integral types, and I've never actually seen anyone use non-short-circuiting or on booleans, but if I had to I'd call it... well, non-short-circuiting or.
is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'
Both || and or (on booleans) are "logical 'or'" and I don't see any problem with calling them simply 'or'. If you need to distinguish use short-circuiting vs non-short-circuiting. But again, I've never actually ran into a use of the non-short-circuiting version.

Objective C : Ternary operator with multiple statements

As the title says i was wondering if there is a way to use ternary operators with multiple statements in Objective C.
I know it can be easily done in some other languages like javascript, php, C etc but i couldn't find a solution for Objective C.
I want to implement something like this:
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
Basically i just want to avoid a lot of if-else blocks to maintain better code readability.
Please also suggest if using ternary operators instead of if-else blocks can harm app performance to a noticeable extent.
The Conditional operator ?: is not a replacement for an if/else block. I'm sure you could tweak the logic to make it work, but that would only obscure the meaning more.
My question is, "what are you saving?"
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
if (a > b) { statement1; statement2; statement3; } else { statement1; statement2; }
The if/else block is a grand total of 7 characters longer.
An even bigger question is, "Can the logic be composed in a better way?"
Look to see if the flow can be done differently with fewer ifs.
Look for places to create sub-routines.
You can easily do this; just be aware that the ternary operator can only include expressions, including comma expressions. So your statements can only be expressions, assignments, method calls etc. but no if / return / while and so on. And the ternary operator wants a result, so the last expressions in each group must have the same type; you can just add (void) 0 at the end of each list.
That said, you are most definitely not making your code more readable. Everyone reading it will start swearing at you and doubt your mental sanity. So don't do it.
The solution for your question (#user3752049) is:
a > b ? ^{ statement1; statement2; statement3;}() : ^{statement1; statement2;}();
Thanks

Perform an assignment and an operation using a ternary operator + && in Objective-C?

In the name of ternary bliss (and for a disdain of the verbose)... I am hoping, and am somewhat surprised that....
BOOL isItOpen = YES;
isItOpen = (isItOpen ? YES : NO); // yes, dumbie, it's open.
works fine… but that…
isItOpen = (isItOpen ? [it close] && NO : [it open] && YES);
results in Invalid operands to binary expression ('void' and 'int')
I can't seem to track down a simple yes or no as to whether one can conditionally chain operations with && (or ||), like one does in say, BASH or PHP. I tried various combinations of & and && arrangements, to no avail.. as I am a C idiot... but if this "way of doing it" is NOT possible, linguistically… is there another - that is as concise? (ie, no ifs involed?)
The C (and by extension, C++ and Objective-C1) operators form expressions; they're designed to evaluate to a value, rather than control program flow.
So whilst ?:, && and || all offer short-circuit evaluation of their arguments, you can't use them to conditionally call arbitrary functions;2 you should use traditional control-flow constructs (i.e. if) for that.
You could use the little-known comma operator to achieve this, but I strongly recommend that you don't, because it's highly unidiomatic, and difficult to read. e.g.:
isItOpen = condition ? (func1(), NO) : (func2(), YES);
Actually, I don't know Objective-C. For all know, it might be possible!
And by "arbitrary", I mean functions that return void, or a type that's not implicitly convertible to bool in the case of && and ||, or a non-matching type in the case of ?:.
The difference you are experiencing is due to Objective-C having:
(a) true procedures (void functions/methods) which return no value; and
(b) a stronger type system than PHP
In your example the primary problem is (a) - you are calling methods which return nothing, and nothing is not a boolean value.
In PHP functions always return something, a function defined as returning void is actually defined as returning a "useless" value. However PHP will convert just about anything to anything (and does so inconsistently, for added "fun"), so a "useless" value has a boolean value - though what that is probably depends on the phase of the moon ;-) This feature does mean that you can reliably chain a "void" function after one which returns a value - <expr convertible to boolean> && <"void" function> will work in PHP (but the resulting boolean value is arbitrary). The same thing will not work in Objective-C (do not try to fix it with the comma operator, there are hidden traps with that operator).
So provided you stick with functions/methods which return either a boolean, or a type implicitly or explicitly convertible to boolean (e.g. for pointer types nil is false, other values true; for integral types 0 is false, everything else true) you can "conditionally chain" operations. Whether you should do this is a different question...
P.S. If you want to be confusing, this is short:
(isItOpen = !isItOpen) ? [it open] : [it close];
which will make most folks do a double-take ;-)
Your code would work fine as long as the close and open methods you are executing on it return boolean values. Otherwise, no cigar.
If you want to use the ternary operator, you can do like this:
isItOpen ? ([it close], isItOpen = NO) : ([it open], isItOpen = YES);
Or:
isItOpen ? [it close] : [it open];
isItOpen = !isItOpen;
But this is not a good programming style and you should avoid it.
The following code is much more readable (at least by a C/C++/Objective-C programmer):
if (isItOpen)
[it close];
else
[it open];
isItOpen = !isItOpen;
In order of preference, I recommend you use the third version of the code, then the second, then the first.

What advantages are there to using either AND or &&?

Currently, I'm using && and || instead of AND and OR because that's how I was taught. In most languages, however, both are valid syntax. Are there any advantages to one or the other in any language?
I did try to search for this question, but it's a bit hard. It doesn't interpret my input correctly.
You ask “Are there any advantages to one or the other in any language?” This is, of course, dependent on the programming language.
Languages that implement both and and && (and correspondingly or and ||) will do it one of two ways:
Both behave exactly the same way. In which case, there is no advantage provided by the language in using one over the other.
Each behaves differently. In which case, the advantage is that you can get different behaviour by using one or the other.
That all sounds a bit facetious, but it's really as specific as one can get without talking about a specific language. Your question explicitly wants to know about all languages, but it's a question that needs to be answered per language.
Perl has all four of {&& || and or} but they differ in their precedence. "and" and "or" have really low precedence so you can do things like "complex-function-call-here or die $!" and you won't accidentally have "or" slurp up something on its left side that you didn't want it to.
it depends on the language, but on PHP, I'd be careful about using && versus "and". The ones i often use are "&&" and "||"
http://us3.php.net/manual/en/language.operators.logical.php
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
In some languages && will have a higher operator precedence than AND.
If both works fine, then I would say it's really personal preference, in most cases, they are compiled into same binary code like this : 11100010001000101001001010 [not real code, just an example].
&& = two keystrokes of the same key.
AND = three keystrokes of different keys.
I'm not sure what language you are using, but some languages differentiate between a normal boolean operator and a short-circuit operator. For example, the following are normal boolean operators in MATLAB:
C = or(A,B);
C = A | B; % Exactly the same as above
However, this is a short-circuit operator:
C = A || B;
The short-circuit syntax will evaluate the first argument and then, depending on the value, will potentially skip over evaluating the second argument. For example, if A is already true, B doesn't have to be evaluated for an OR operation, since the result is guaranteed to be true. This is helpful when B is replaced with a logical operation that involves some kind of expensive computation.
Here's a wikipedia link discussing short-circuit operators and their syntax for a few languages.
Unless there aren't any precedence issues, I'd say there are differences in readability. Consider the following:
if (&x == &y && &y == &z) {
// ..
}
#define AND &&
if (&x == &y AND &y == &z) {
// ..
}