How would I modify the definition of the operators "&&" and "||" so that they do not use short circuit evaluation? - programming-languages

How would I modify the definition of the operators "&&" and "||" so that they do not use short circuit evaluation? Please show the new semantic rule.
I tried the following:
"AND (&&): It returns expression #1 if it can be converted to false - if else it returns expression #2. Therefore, when used with the Boolean value, it returns true if both operands can be converted to true; otherwise, it returns false.
OR (||): it returns expression #1 if it can be converted to true – if-else, it returns expression #2. Therefore, when used with Boolean values, || returns true if either operand can be converted to true - if both can be converted to false, it returns false. "
However, apparently, that's still using short-circuit evaluation.

Short-circuit evaluation means that you stop immediately whenever you encounter a value of false for AND and a value of true for OR. This is because the value of the entire expression will always be that no matter what the second term is.
Your AND description is wrong because if expression #1 evaluates to false, expression #2 is not evaluated at all. Same thing with OR.
What you want to do is to evaluate both expressions before manipulating either values.

Related

element => command in Terraform

I see a code as below in https://github.com/terraform-aws-modules/terraform-aws-efs/blob/master/examples/complete/main.tf#L58
# Mount targets / security group
mount_targets = { for k, v in toset(range(length(local.azs))) :
element(local.azs, k) => { subnet_id = element(module.vpc.private_subnets, k) }
}
I am trying to understand what => means here. Also this command with for loop, element and =>.
Could anyone explain here please?
In this case the => symbol isn't an independent language feature but is instead just one part of the for expression syntax when the result will be a mapping.
A for expression which produces a sequence (a tuple, to be specific) has the following general shape:
[
for KEY_SYMBOL, VALUE_SYMBOL in SOURCE_COLLECTION : RESULT
if CONDITION
]
(The KEY_SYMBOL, portion and the if CONDITION portion are both optional.)
The result is a sequence of values that resulted from evaluating RESULT (an expression) for each element of SOURCE_COLLECTION for which CONDITION (another expression) evaluated to true.
When the result is a sequence we only need to specify one result expression, but when the result is a mapping (specifically an object) we need to specify both the keys and the values, and so the mapping form has that additional portion including the => symbol you're asking about:
{
for KEY_SYMBOL, VALUE_SYMBOL in SOURCE_COLLECTION : KEY_RESULT => VALUE_RESULT
if CONDITION
}
The principle is the same here except that for each source element Terraform will evaluate both KEY_RESULT and VALUE_RESULT in order to produce a key/value pair to insert into the resulting mapping.
The => marker here is just some punctuation so that Terraform can unambiguously recognize where the KEY_RESULT ends and where the VALUE_RESULT begins. It has no special meaning aside from being a delimiter inside a mapping-result for expression. You could think of it as serving a similar purpose as the comma between KEY_SYMBOL and VALUE_SYMBOL; it has no meaning of its own, and is only there to mark the boundary between two clauses of the overall expression.
When I read a for expression out loud, I typically pronounce => as "maps to". So with my example above, I might pronounce it as "for each key and value in source collection, key result maps to value result if the condition is true".
Lambda expressions use the operator symbol =, which reads as "goes to." Input parameters are specified on the operator's left side, and statement/expressions are specified on the right. Generally, lambda expressions are not directly used in query syntax but are often used in method calls. Query expressions may contain method calls.
Lambda expression syntax features are as follows:
It is a function without a name.
There are no modifiers, such as overloads and overrides.
The body of the function should contain an expression, rather than a statement.
May contain a call to a function procedure but cannot contain a call to a subprocedure.
The return statement does not exist.
The value returned by the function is only the value of the expression contained in the function body.
The End function statement does not exist.
The parameters must have specified data types or be inferred.
Does not allow generic parameters.
Does not allow optional and ParamArray parameters.
Lambda expressions provide shorthand for the compiler, allowing it to emit methods assigned to delegates.
The compiler performs automatic type inference on the lambda arguments, which is a key advantage.

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.

can someone further explain this C# code

I am using the PredicateBuilder class from http://www.albahari.com/nutshell/predicatebuilder.aspx
public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
}
this extension method is chaining Predicates with the OR operator. on the page, the explanation says
We start by invoking the second expression with the first expression’s parameters. An Invoke expression calls another lambda expression using the given expressions as arguments. We can create the conditional expression from the body of the first expression and the invoked version of the second. The final step is to wrap this in a new lambda expression.
so if for example i have
Predicate<Book> p1 = b => b.Title.Contains("economy");
Predicate<Book> p2 = b=>b.PublicationYear>2001;
Predicate chain = p1.And(p2);
I didn't quite get the exlanation. can someone please explain how the code of the extension method above is working?
thanks
Let's rewrite the method body like this:
return Expression.Lambda<Func<T, bool>>(
Expression.OrElse(
expr1.Body,
Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>())
),
expr1.Parameters);
We should also keep in mind that expr1 is your existing expression that takes a T and returns a bool. Additionally, while the expression trees we are working with do not actually do anything (they represent something instead), I am going to use "do" henceforth because it makes for much easier reading. Technically for an expression tree to actually do something you have to compile it first and then invoke the resulting delegate.
Ok, so what do we have here? This is a lambda expression that takes whatever parameters expr1 takes (see last line) and whose body, as per the documentation, is
a BinaryExpression that represents a conditional OR operation that
evaluates the second operand only if the first operand evaluates to
false.
The first operand is expr1.Body, which means the resulting function (not actually a function, see note above) evaluates expr1. If the result is true it returns true on the spot. Otherwise, it invokes expr2 with the same parameters as those passed to expr1 (this means the single T parameter) and returns the result of that.

PredicateBuilder And or Or

In all the examples I've seen for predicate builder it shows a starting expression with PredicateBuilder.True if you are building an "and" expression criteria and PredicateBuilder.False if you are building an "or" expression criteria.
My questions is, is this always the case, and if so why couldn't this be simply inferred. I suspect there must be cases where you are be building an "and" expression and want to start with a false. And the opposite for an "or"
Can anyone explain this to me?
In the expression A and B and C and D, if any of the conditions (A, B, C, or D) are False, the entire expression is False. So if you start an "and" expression with False, no matter what else you AND to it, the entire expression will be False.
Same with an "or" expression. In the expression A or B or C or D, if any of the conditions (A, B, C, or D) are True, the entire expression is True. So if you start an "or" expression with True, no matter what else you OR to it, the entire expression will be True.
As for why you need to start a PredicateBuilder with the literal True or False, I believe this was simply a convention to make using PredicateBuilder easier. Your expressions always start with a (boolean) condition, followed by 0 or more "And/Or condition" parts. So you can have "A", or "A and B", or "A and B and C". You never start with "and A". The .And(condition) of PredicateBuilder adds "and condition" to the expression, so you can't start with it. There could have been a constructor that let your create your Expression and start it with an initial condition (new Expression<...>(A)? I haven't actually checked... is there one?) but then you'd have to treat your first condition (you're probably looping over some collection of things and adding to your Expression) differently (calling a constructor) than you do your 2nd and subsequent conditions (calling .And(...) or .Or(...)). The .True<...>() and .False<...>() methods of PredicateBuilder handle creating your Expression as well as adding the first (generic) condition so that you can handle adding your 1st and all subsequent conditions in your loop the same (by calling .And(...) or .Or(...)).

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