Match two strings with && but getting match on either/or - string

I'm trying to take a number of input strings and have a
do {
} while
loop matching the strings with
while (!sqlw.equals(w) && !sqlc.equals(c));
However this returns positive match if either one or the other is matched, rather than both. Any ideas? I guess it is something simple.

So, the thing is, in this line:
while (!sqlw.equals(w) && !sqlc.equals(c));
the expression becomes false if either sqlw.equals(w) is true (making !sqlw.equals(w) false) or !sqlc.equals(c) is true (making !sqlc.equals(c) false).
Try replacing && with || like so
while (!sqlw.equals(w) || !sqlc.equals(c));
That way, the expression is false only if !sqlw.equals(w) and !sqlc.equals(c) are both false (i.e. when both match).
EDIT: You could also change it to
while (!(sqlw.equals(w) && sqlc.equals(c)));
which does the same thing but is perhaps a little more faithful to what you wanted (loop while we haven't matched both).

The equals method returns a boolean value. Try sqlw.equals('w') == false.
Also make sure your data types are the same in both cases. One might be a string and the other an array object of some sort.

Related

how does && work when both the variables are the same?

I'm learning groovy to work on smartthings and found a relatively common command among the various examples and existing code (see below).
Reading the function of the && operator I would think the "&& cmd.previousMeterValue" is superfluous. Or is there some code shortcut I'm missing?
Thanks
John
if (cmd.previousMeterValue && cmd.previousMeterValue != cmd.meterValue) {
do something
}
Not knowing what type previousMeterValue has, this answer is somewhat generic.
Groovy follows common operator precedence, i.e. != is evaluated before &&.
To show it explicitly, the full expression is the same as:
(cmd.previousMeterValue) && (cmd.previousMeterValue != cmd.meterValue)
cmd.previousMeterValue is testing the value for the Groovy-Truth.
Depending on value type, the following might be applicable:
Non-null object references are coerced to true.
Non-zero numbers are true.
So if the value is null or 0, the expression is false.
If the first part of the expression evaluated to false, then the second part is skipped.
The logical && operator: if the left operand is false, it knows that the result will be false in any case, so it won’t evaluate the right operand. The right operand will be evaluated only if the left operand is true.
If the first part of the expression evaluated to true, then cmd.previousMeterValue != cmd.meterValue is evaluated, using the following rule:
In Groovy == translates to a.compareTo(b)==0, if they are Comparable, and a.equals(b) otherwise.
So if value is a number object, then it is evaluated as:
cmd.previousMeterValue.compareTo(cmd.meterValue) != 0
This means that BigDecimal values are compared by value, ignoring specific scale.

Shouldn't Empty Strings Implicitly Convert to false

Why does
if (x) {
f();
}
call f() if x is an empty string ""?
Shouldn't empty strings in D implicitly convert to bool false like they do in Python and when empty arrays does it (in D)?
Update: I fixed the question. I had incorrectly reversed the reasoning logic. Luckily, the bright D minds understood what I meant anyway ;)
Conditions and if statements and loops are cast to bool by the compiler. So,
if(x) {...}
becomes
if(cast(bool)x) {...}
and in the case of arrays, casting to bool is equivalent to testing whether its ptr property is not null. So, it becomes
if(x.ptr !is null) {...}
In the case of arrays, this is actually a really bad test, because null arrays are considered to be the same as empty arrays. So, in most cases, you don't care whether an array is null or not. An array is essentially a struct that looks like
struct Array(T)
{
T* ptr;
size_t length;
}
The == operator will check whether all of the elements referred to by ptr are equal, but if length is 0 for both arrays, it doesn't care what the value of ptr is. That means that "" and null are equal (as are [] and null). However, the is operator explicitly checks the ptr properties for equality, so "" and null won't be the same according to the is operator, and whether a particular array which is empty has a null ptr depends on how its value was set. So, the fact that an array is empty really says nothing about whether it's null or not. You have to check with the is operator to know for sure.
The result of all this is that it's generally bad practice to put an array (or string) directly in a condition like you're doing with
if(x) {...}
Rather, you should be clear about what you're checking. Do you care whether it's empty? In that case, you should check either
if(x.empty) {...}
or
if(x.length == 0} {...}
Or do you really care that it's null? In that case, use the is operator:
if(x is null) {...}
The behavior of arrays in conditions is consistent with the rest of the language (e.g. pointer and reference types are checked to see whether they're null or not), but unfortunately, in practice, such behavior for arrays is quite bug-prone. So, I'd advise that you just don't ever put an array by itself in the condition of an if statement or loop.
the default conversion of arrays looks at the .ptr, which means only the default initialized arrays (or explicitly set to null) evaluate to false
as an added effect string literals in D are \0 terminated which means ("")[0] == '\0' and as such ("").ptr can't be null (which would lead to a segfault)
IMO it should look at the length and you can use the ptr when you need to
It does when I try it...
void main() {
import std.stdio;
string s = "";
if(s)
writeln("true"); // triggered
}
If it was "string s = null;" (which is the default initialization), it doesn't, because the null converts to false, but "" is ok on my computer. Are you sure it isn't null?
BTW, if you want to test for (non-)emptiness, the way I prefer to do it is if(x.length) and if(x.length == 0). Those work consistently for both "" and null, then if you specifically want null, do if(x is null). It is just a little more clear, especially since "" and null are interchangeable in a lot of other contexts in D.

Why is Matlab is not reading an empty cell while running an if statement?

I am using the loop below to isolate instances where data was recorded versus those with no data. The data set is very large (varying from 1000-6000 depending on the column) and of mixed data types, so the only practical solution I can think of is using loops.
I can't get the if or while statement to accurately read a blank space. It runs without any errors if I use a for loop, but it never enters the first half of the if-meaning I end up copying, not separating my data. The varying sizes of data make a for loop undesirable.
while (isempty(andover_all{j,1})==1)
if andover_all{h,33}=='';
current_data{k,4}= formated_date{j};
k=k+1;
else
current_data{i,1}=formated_date{j};
current_data{i,2}=andover_data{33}(j);
i=i+1;
end
h=h+1;
end
Andover_all is an array of strings, current_data and andover_data are cell arrays with mixed data types. I have tried using isempty, [], cellfun(#isempty,andover_data), and a function eq.m that allows me to compare cell elements-none of them work. I also don't want to remove empty cells from the data, just skip over them.
Please let me know if you have any ideas
The empties are indeed something to get used to. It's like working with inf or NaN; what should things like NaN==NaN or 1/0==inf return? There's special rules for these guys. Simple ones, but you have to get to know them. To make all the special rules for these guys less of a burden, more intuitive and more readable, MATLAB has special functions for them: isinf (to detect inf), isnan (to detect NaN) and isfinite (to detect either inf or NaN).
The empties also have special behavior and special rules that require some getting used to. If you think about it, it all makes sense in the end: What should []==[] return? or 1==''?
Empty, of course. And even if []==false is empty, [] is false when evaluated by an if. Easy right? :)
Unfortunately, there is no equivalent of isinf or isnan to detect empties of a specific type (there is no isemptycell or isemptychar etc.) There is an equivalent of isfinite for empties (which is isempty), which catches either '', {}, or [].
But sometimes it is desirable to have checks for specific empties, as in your case. The empties preserve their class. This means, {} is really a cell, and [] really an array of doubles.
Therefore, to detect empty cells:
>> a = {};
>> iscell(a) && isempty(a)
ans =
1
to detect empty strings:
>> a = '';
>> ischar(a) && isempty(a)
ans =
1
and to detect empty arrays:
>> a = [];
>> isnumeric(a) && isempty(a)
ans =
1

Coffeescript - how do I check string equality when passing string through a splat?

I'm having trouble checking whether two strings are equal when one of them was passed through a splat argument. Because coffeescript uses strict comparisons, and because it makes a copy of the arguments when they go through a splat, I can't get the strings to compare properly without resorting to backticks. Is there a better way? Here's a minimal piece of code that demonstrates the problem:
check=(arg) ->
if arg == 'foo' then "'#{arg}'=='foo'" else "'#{arg}'!='foo'"
emit=(args...) ->
check(args)
console.log(emit('foo'))
console.log(check('foo'))
The output from this will be as follows:
> coffee mincase.coffee
'foo'!='foo'
'foo'=='foo'
EDIT:
mu is too short gave me the key, so the revised working code looks like this (everything is the same except emit)
emit=(args...)->
check.apply(null,args)
When you use a splat, the splat puts the splatted arguments into an array. For example:
f = (x...) -> console.log(x instanceof Array)
f(6)
will give you a true in the console. The fine manual isn't so fine in this case, it doesn't exactly spell it out, it assumes that you understand how JavaScript's arguments object works and leaves out the explicit splat puts your arguments into an array part.
So you end up passing an array to check and an array compared with a string using CoffeeScript's == (or JavaScript's ===) will never be true.
If you want emit to check the first argument, then you need to say so:
emit = (args...) -> check(args[0])
Demo: http://jsfiddle.net/ambiguous/TBndM/

Haskell IF statements

I'm pretty new to haskell, but if you make an if statement:
function a b c
| (a+b == 0) = True
| --etc.
| otherwise = False
Is the second if statement the same as an else if in other languages, or is it just another if. I assume its the former as you can only have one output, but I just want to make sure.
The construct you used is called a guard. Haskell checks the given alternatives one after another until one condition yields True. It then evaluates the right hand side of that equation.
You could pretty well write
function n
| n == 1 = ...
| n == 2 = ...
| n >= 3 = ...
thus the guard kinds of represents an if/elseif construct from other languages. As otherwise is simply defined as True, the last
| otherwise =
will always be true and therefore represents a catch-all else clause.
Nontheless, Haskell has a usual a = if foo then 23 else 42 statement.
What you have here is not really an if statement, but rather a guard. But you are right that the second case gets "executed" only if the previous cases (by cases here I mean the expressions between the | and =) did not match (evaluate to True). otherwise is just a synonyme to True (that way it always "matches").
It must be like an else if.
The bottom pattern otherwise is really just True, so if the first match didn't win, you would always get the more specific value and the otherwise value.
Correct. Though you've used guards, the way you've expressed it is more or less identical to using an if-statement. The flow of testing the conditional to yield a result will fall through the guard you've written in the order they were listed in your guard.
(a+b == 0)
Will be checked first
etc.
Will be checked second and so forth, provided no preceding conditional is true.
otherwise
Will be checked last, provided no preceding conditional is true.

Resources