Computing && and || - scala

I have a value in Scala defined as
val x = SomeClassInstance()
val someBooleanValue = x.precomputedValue || functionReturningBoolean(x)
functionReturningBoolean has a long runtime and to avoid recomputing functionReturningBoolean(x), I am storing it in x.precomputedValue.
My question is: if x.precomputedValue is true, will functionReturningBoolean(x) ever be computed?
More Generally: as soon as the compiler sees a value of true in an "OR" statement, will it even look at the second condition in the statement?
Similarly, in an "AND" statement, such as a && b, will b ever be looked at if a is false?

My question is: if x.precomputedValue is true, will functionReturningBoolean(x) ever be computed?
No. && and || in Scala short-circuit. You can tell from the documentation:
This method uses 'short-circuit' evaluation and behaves as if it was declared as def ||(x: => Boolean): Boolean. If a evaluates to true, true is returned without evaluating b.
More Generally: as soon as the compiler sees a value of true in an "OR" statement, will it even look at the second condition in the statement? Similarly, in an "AND" statement, such as a && b, will b ever be looked at if a is false?
Yes. All expressions in Scala must be well-typed statically, whether they will be executed at runtime or not.

Related

DART, How to perform "Greaterthan and No Equal" together?

I am new to dart,
I was doing experiment with dart and suddenly got a problem,
I am using this logic to obtain it, correct me if i am wrong.
int a = 8;
int b = 7;
if (!(a <= b)){
print("A is Less");
}else{
print("B is Less");
}
Comments on your question recommend ">" which is correct, but I thought I could help you understand your sample if construct and why it prints the opposite of what is accurate.
Any conditions inside an if must evaluate to a single boolean: true or false. In your if you test "a is less than or equal to b", which will yield 'true' or 'false', then you invert that boolean value with the boolean "!" not operator. Boolean 'not' changes true to false, and false to true.
Given the values you set for a and b, your if statement therefore checks if a is less than or equal to b, which is "false", then inverts that "false" to "true" using "!" not, and therefore prints "A is Less", which is an incorrect statement.
FWIW, your logic will also print "B is less" when a = b;

Julia: Immutable composite types

I am still totally new to julia and very irritated by the following behaviour:
immutable X
x::ASCIIString
end
"Foo" == "Foo"
true
X("Foo") == X("Foo")
false
but with Int instead of ASCIIString
immutable Y
y::Int
end
3 == 3
true
Y(3) == Y(3)
true
I had expected X("Foo") == X("Foo") to be true. Can anyone clarify why it is not?
Thank you.
Julia have two types of equality comparison:
If you want to check that x and y are identical, in the sense that no program could distinguish them. Then the right choice is to use is(x,y) function, and the equivalent operator to do this type of comparison is === operator. The tricky part is that two mutable objects is equal if their memory addresses are identical, but when you compare two immutable objects is returns true if contents are the same at the bit level.
2 === 2 #=> true, because numbers are immutable
"Foo" === "Foo" #=> false
== operator or it's equivalent isequal(x,y) function that is called generic comparison and returns true if, firstly suitable method for this type of argument exists, and secondly that method returns true. so what if that method isn't listed? then == call === operator.
Now for the above case, you have an immutable type that do not have == operator, so you really call === operator, and it checks if two objects are identical in contents at bit level, and they are not because they refer to different string objects and "Foo" !== "Foo"
Check source Base.operators.jl.
Read documentation
EDIT:
as #Andrew mentioned, refer to Julia documentation, Strings are of immutable data types, so why "test"!=="true" #=> true? If you look down into structure of a String data type e.g by xdump("test") #=> ASCIIString data: Array(UInt8,(4,)) UInt8[0x74,0x65,0x73,0x74], you find that Strings are of composite data types with an important data field. Julia Strings are mainly a sequence of bytes that stores in data field of String type. and isimmutable("test".data) #=> false

MATLAB logical operators: && vs &

If I want to ensure that an if statement only executes if BOTH of two conditions are true, should I be using & or && between the clauses of the statement?
For example, should I use
if a == 5 & b == 4
or
if a == 5 && b == 4
I understand that the former is elementwise and the latter is capable of short-circuiting but am not clear on what this means.
For a scalar boolean condition I'd recommend you use &&. Short-circuiting means the second condition isn't evaluated if the first is false, but then you know the result is false anyway. Either & or && one will be true only if both sides of the expression are true, but & can return a matrix result if one of the operands is a matrix.
Also, I believe in Matlab comparisons should be done with ==, not with = (assignment).

Unable to add a condition to a while loop in Matlab

I have a while loop which looks like this:
while ((min_t_border>0) && (colided_border_num > 0) && (~(min_t>0)))
...
end
I want to add to it another condition: (exit_border_point ~= false) or (exit_border_point)
when I put ether of the conditions above in an if statement it works. But when I try to add it as an additional condition to the while, or even when I try to add another condition to the if, for example I've tried if ((exit_border_point ~= false) && (true)) it tells me:
"Operands to the || and && operators must be convertible to logical scalar values."
What am I doing wrong?
*exit_border_point gets ether a (3x1) vector or false
Since exit_border_point can be a vector, try using the any or all functions, like this:
if (~any(exit_border_point))
As you can probably guess, any returns true if anything in the array evaluates to true and all returns true if everything in the array is true. They're kind of like vector equivalents to || and &&.
For the condition to make sense in the context of an if or while statement, it should evaluate to a scalar.
Thus, you should write
all(exit_border_point)
(which is equivalent to all(exit_border_point == true)), if you want true if all are true. Replace all with any if you want to exit the while-loop as soon as any exit_border_point is true.
Note that && and || only work for scalars. They're short-cut operators in that the second statement won't be evaluated if the first one determines the outcome (e.g. evaluates to false in case of &&. If you want to element-wise compare arrays, use & and |.
If exit_border_point is a 3x1 vector then (exit_border_point ~= false) also returns a 3x1 vector, hence the error. Use this condition instead:
~isequal(exit_border_point, false)

Is it Pythonic to use bools as ints?

False is equivalent to 0 and True is equivalent 1 so it's possible to do something like this:
def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
Notice how value is bool but is used as an int.
Is this this kind of use Pythonic or should it be avoided?
I'll be the odd voice out (since all answers are decrying the use of the fact that False == 0 and True == 1, as the language guarantees) as I claim that the use of this fact to simplify your code is perfectly fine.
Historically, logical true/false operations tended to simply use 0 for false and 1 for true; in the course of Python 2.2's life-cycle, Guido noticed that too many modules started with assignments such as false = 0; true = 1 and this produced boilerplate and useless variation (the latter because the capitalization of true and false was all over the place -- some used all-caps, some all-lowercase, some cap-initial) and so introduced the bool subclass of int and its True and False constants.
There was quite some pushback at the time since many of us feared that the new type and constants would be used by Python newbies to restrict the language's abilities, but Guido was adamant that we were just being pessimistic: nobody would ever understand Python so badly, for example, as to avoid the perfectly natural use of False and True as list indices, or in a summation, or other such perfectly clear and useful idioms.
The answers to this thread prove we were right: as we feared, a total misunderstanding of the roles of this type and constants has emerged, and people are avoiding, and, worse!, urging others to avoid, perfectly natural Python constructs in favor of useless gyrations.
Fighting against the tide of such misunderstanding, I urge everybody to use Python as Python, not trying to force it into the mold of other languages whose functionality and preferred style are quite different. In Python, True and False are 99.9% like 1 and 0, differing exclusively in their str(...) (and thereby repr(...)) form -- for every other operation except stringification, just feel free to use them without contortions. That goes for indexing, arithmetic, bit operations, etc, etc, etc.
I'm with Alex. False==0 and True==1, and there's nothing wrong with that.
Still, in Python 2.5 and later I'd write the answer to this particular question using Python's conditional expression:
def bool_to_str(value):
return 'Yes' if value else 'No'
That way there's no requirement that the argument is actually a bool -- just as if x: ... accepts any type for x, the bool_to_str() function should do the right thing when it is passed None, a string, a list, or 3.14.
surely:
def bool_to_str(value):
"value should be a bool"
return 'Yes' if value else 'No'
is more readable.
Your code seems inaccurate in some cases:
>>> def bool_to_str(value):
... """value should be a bool"""
... return ['No', 'Yes'][value]
...
>>> bool_to_str(-2)
'No'
And I recommend you to use just the conditional operator for readability:
def bool_to_str(value):
"""value should be a bool"""
return "Yes" if value else "No"
It is actually a feature of the language that False == 0 and True == 1 (it does not depend on the implementation): Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
However, I do agree with most of the other answers: there are more readable ways of obtaining the same result as ['No', 'Yes'][value], through the use of the … if value else … or of a dictionary, which have the respective advantages of hinting and stating that value is a boolean.
Plus, the … if value else … follows the usual convention that non-0 is True: it also works even when value == -2 (value is True), as hinted by dahlia. The list and dict approaches are not as robust, in this case, so I would not recommend them.
Using a bool as an int is quite OK because bool is s subclass of int.
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
About your code: Putting it in a one-line function like that is over the top. Readers need to find your function source or docs and read it (the name of the function doesn't tell you much). This interrupts the flow. Just put it inline and don't use a list (built at run time), use a tuple (built at compile time if the values are constants). Example:
print foo, bar, num_things, ("OK", "Too many!)[num_things > max_things]
Personally I think it depends on how do you want to use this fact, here are two examples
Just simply use boolean as conditional statement is fine. People do this all the time.
a = 0
if a:
do something
However say you want to count how many items has succeed, the code maybe not very friendly for other people to read.
def succeed(val):
if do_something(val):
return True
else:
return False
count = 0
values = [some values to process]
for val in values:
count += succeed(val)
But I do see the production code look like this.
all_successful = all([succeed(val) for val in values])
at_least_one_successful = any([succeed(val) for val in values])
total_number_of_successful = sum([succeed(val) for val in values])