Any mnemonic tip for boolean? - boolean

I guess this is trivial for most of good1 programmers, but I'm so used to programming using true and false2 that when I encounter 0 and 1, I can never remember which one means true and which one means false.
Any suggestions?
1Good: I mean one who knows C, of course :)
2I am a Java developer, as you have guessed ;)

The mnemonic is "how much truth is in this?" Zero integer means zero truth. Anything else is nonzero truth. :)

I have a co-worker who simply has a Post-It note on his wall beside his desk:
False = 0
True != 0

If you are really having that much trouble with it, I would use the language to abstract it away.
e.g. in C
#define TRUE 1
#define FALSE 0
In general I would avoid having constants lying around in code anyways.
Consider,
if(my_var == TRUE)
as opposed to,
if(my_var == 1)
Though, here again you need to make sure you are testing for the right thing,
if(my_var != FALSE)
will catch more cases.
Cheers!
Christian

Haven't you ever noticed that everyday items' power switches use a circle for off, and a line for on?
It's not much of a jump to link them up.
Off = circle = zero = false
On = line = one = true

"Oh No!"
(Oh == 0)

This is complicated by the fact that in the shell (sh, bash) true is 0 and false is 1:
$ true
$ echo $?
0
$ false
$ echo $?
1

Remember "nothing == false", "something == true"

No mnemonic - and it gets even more complex if you come from a hardware background. But for programmers, just ask the question:
Is any bit set?
The answer is either true or false, and is the result. Only 0 (even in signed integers) has no bits set.
-Adam

Map both to On and Off. I think most programmers would map both sets the same way: 1/true both going to 'On', while 0/false both go to 'Off'.

It depends on the language.
C: ( 0 ? "never happens" : "false") and ( 1 ? "true" : "never happens")
Ruby, ELisp: both 0 and 1 are true
bash (or cmd.exe): the true command (from coreutils) exits with a 0 status code and the false command exits with a non-zero status code
Many modern popular programming languages have strong C heritage therefore they consider 0 to be false and 1 (or any non-zero numbers) to be true.
Don't use mnemonics for boolean, use your language's idioms to test trueness.

love c - because you can't multiply lies. :)

Related

Is there an alternative of and() in Matlab that does not check syntax and returns a false as soon as the first false is found?

Is there a convenient alternative of and() in Matlab that does not check existence, number of input or output arugments, and returns a false as soon as the first false is found without evaluating the expressions in subsequent inputs?
For example, I would like
and(0,a),
and(0,error()),
to both return false as opposed to returning error messages. Once an earliest input argument returns false, I have no use of subsequent input arguments and I am happy to ignore syntax errors. But Matlab isn't.
(The more likely scenario for me is that the false case of preceding inputs cover any syntax errors in later inputs.)
Is there a way around this? If I write an alternative of and() with a (Matlab) loop on varargin, will the alternative be slower?
Using the && operator solves your problem,
0 && a
0 && error()
will return
ans =
logical
0
Of course, even when a is undefined.
Caveat: and() can take (syntax checked) array arguments while && cannot. The different answers and comments in this question explain in more details.
The MATLAB interpreter (just like any other interpreter I’ve come across) parses all the input arguments to a function before calling the function. The function is passed the results of evaluating the arguments. Therefore, it is not possible to have a function control which of its input arguments are parsed.
There is no functional equivalent to &&, the short-circuit logical AND. The function and is equivalent to & and does not short-circuit.

How do I translate this `for` loop for the fish shell?

I'm translating a script from Z shell to Fish, and I've got this one part I can't figure out how to translate:
for (( i=0; i < $COLUMNS; i++ )); do
printf $1
done
The only documentation for for loops I can find in Fish is for this kind. How would I do this in Fish?
It appears that the Fish shell does not have that kind of for loop, but instead requires you to take a different approach. (The philosophy is apparently to rely on as few syntactic structures and operators as possible, and do as much with commands as possible.)
Here's how I did it, although I assume there are better ways:
for CHAR in (seq $COLUMNS)
printf $argv[1]
end
This appears inside a function, hence the $argv[1].
I believe the answer from #iconoclast is the correct answer here.
I am here just to give an (not better) alternative.
a brief search in fish shell seems suggest it provides a while-loop in a form of :
while true
echo "Loop forever"
end
As in C/C++ 101, we learned that for loop can be (mostly) translated to a while loop by:
for (A; B; C) {
D;
}
translates to
A;
while (B) {
D;
C;
}
That's what you can consider if the condition and "incrementation" is not a straight-forward one.

Short circuit and giving incorrect results?

I am experiencing strange results with Perl's short circuited and, that is &&.
I am trying to solve a Project Euler problem where I want a certain number to be divisible by a list of numbers.
$b=42;
if($b%21==0 && b%2==0 && b%5==2){print "Why not?"};
Should print "Why not" as far as I can see, but keeps silent.
$b=42;
if($b%21==0 && b%2==0 && b%5==0){print "WTF?"};
Should keep silent, but prints "WTF?".
What gives?
As Rohit answered, the solution is to add the $ before the b. The exact reason it doesn't print "Why not?" but prints "WTF" is this: when you give the b without the $ sign (and without use strict; in force), Perl treats the b as the string "b". Then when you apply the operator % on it, since % is a numerical operator, Perl looks within the string "b" and checks whether it starts with a number. Since it doesn't, Perl takes the numerical value of "b" as 0, and then applies the mod (%) operation. 0%5 is 0 and not 2, so WTF is printed and not "Why not?"
Always use use strict and use warnings.
You are using your last two b's as bareword, which will be shown as warning - "Unquoted string "b" may clash with future reserved word"
You need to change your if to: -
if($b%21==0 && $b%2==0 && $b%5==2){print "Why not?"};
and: -
if($b%21==0 && $b%2==0 && $b%5==0){print "WTF?"};
gives expected results.
if($b%21==0 && $b%2==0 && $b%5==2){print "Why not?"};
works over here, you forgot the $, but apearntly you already found it :)

Hash(m1 xor m2) = Hash(m1) xor Hash (m2) Is this true in case of SHA1

Can anyone shed some knowledge on this?
My answer is no, it is not true, because SHA1 has a strong collision resistant property.
No this isn't true. (And it would only take a few seconds to actually test it yourself.)
No, it is not true. A function would have to go out of its way to have this property. SHA1 incorporates bytes from its stream on block at a time starting with a predefined initial value. At the end it incorporates the length of the byte stream into the byte stream and pads out to the block size.
It makes no attempt to satisfy the property in question (which is a good thing!)
No. To quote from Wikipedia:
Even a small change in the message will, with overwhelming probability, result in a completely different hash due to the avalanche effect.
Here's a counterexample (0xFF xor 0x00 is 0xFF):
$ echo -ne "\xff" > 1
$ echo -ne "\x00" > 2
$ sha1sum *
85e53271e14006f0265921d02d4d736cdc580b0b *1
5ba93c9db0cff93f52b521d7420e43f6eda2784f *2
If your statement were true, the second hash would have to be 00000000..., but it is not.
I'm affraid this will hold only if your hash function is XOR.

What is the best way to log an error when testing in Perl?

What is the best way to log an error when testing in Perl? I prefer a one-liner solution such as
return 0 if $var!=3 and $logger->error("Var is not 3"))
Can something like the example shown be implemented?
You could always do:
$logger->error("Var is not 3") and return 0 if $var != 3
which takes advantage of and's low precedence (and if's even lower precedence).
$logger->error("Var is not 3"), return 0 if $var != 3;
This is taking advantage of Perl's support for the comma operator, which allows you to write an expression where parts to the left are evaluated but their value ignored, with the final value of the expression being the rightmost part.
I prefer using carp/croak/confess if it's just me debugging, but if you're doing it for production code, maybe try Log::Report.
So something like: $var == 3 or confess("var != 3!") is what I'd use if I wanted a one liner that prints an error and a stacktrace.
Log4Perl may do what you'd like. This is the Perl clone of Log4J. It has fine grain dynamic log filtering configuration.
If you're using Test::More, use diag(). This plays better with prove and the like.