The simplest way to solve precedence of operator? - operator-precedence

The simplest way to solve precedence of operator?
for example
1+2*3/4%5
I need simplest and logical way to solve it?
"i dont want to use parentheses"

You may need to know operator precedence first, and thier associativity as well.
Here, *, / and % have same precedence but have higher precedence than +.
Since they all are lef-to-right associative, grouping them results in
1+(((2*3)/4)%5)
If they were right-to-left associative, it would have been
1+(2*(3/(4%5)))
If you don't want to use parenthesis, just make sure you write them in order like:
1+2*3/4%5
-> 1+6/4%5
-> 1+1%5
-> 1+1
-> 2
I hope you understand.

Related

Jekyll/Liquid complex expressions

How do do formulate in Jekyll/Liquid language the following expression:
if (A and B) or (not C)
What are the rules globally (precedence, left,right) ?
Parentheses won't work, all precedence rules are detailed here:
https://shopify.dev/docs/themes/liquid/reference/tags/control-flow-tags#multiple-conditions-and-or

Erlang pattern matching with functions

As Erlang is an almost pure functional programming language, I'd imagine this was possible:
case X of
foo(Z) -> ...
end.
where foo(Z) is a decidable-invertible pure (side-effect free) bijective function, e.g.:
foo(input) -> output.
Then, in the case that X = output, Z would match as input.
Is it possible to use such semantics, with or without other syntax than my example, in Erlang?
No, what you want is not possible.
To do something like this you would need to be able to find the inverse of any bijective function, which is obviously undecidable.
I guess the reason why that is not allowed is that you want to guarantee the lack of side effects. Given the following structure:
case Expr of
Pattern1 [when GuardSeq1] ->
Body1;
...;
PatternN [when GuardSeqN] ->
BodyN
end
After you evaluate Expr, the patterns are sequentially matched against the result of Expr. Imagine your foo/1 function contains a side effect (e.g. it sends a message):
foo(input) ->
some_process ! some_msg,
output.
Even if the first pattern wouldn't match, you would have sent the message anyway and you couldn't recover from that situation.
No, Erlang only supports literal patterns!
And your original request is not an easy one. Just because there is a an inverse doesn't mean that it is easy to find. Practically it would that the compiler would have to make two versions of functions.
What you can do is:
Y = foo(Z),
case X of
Y -> ...
end.

why can't conditional operator be used as a statement

Why can't the conditional operator be used as a statement?
I would like to do something like:
boolean isXyz = ...;
...
isXyz ? doXyz() : doAbc();
where doXyz and doAbc are return void.
Note that this is not the same as other operators, for example doXyz() + doAbc() intrinsically needs that doXyz and doAbc return a number-like something to operate (or strings to concatenate, or whatever, but the point is that + actually needs values to operate on).
Is there something deep or is it just an arbitrary decision.
Note: I come from the Java world, but I would like to know if this is possible in your favourite programming language.
C and C++ do allow such constructs. As long as doXyz() and doAbc() return the same type. Including void.
What would be the point? Why not just use an if statement (which, in my opinion, looks cleaner)?
Because it would reduce readability and introduce a potential for errors.
Languages offer means of doing what you wish by using the keyword "if".
// Is not much longer than the line below
// but significantly more transparent
if (isXyz) doXyz() else doAbc();
isXyz ? doXyz() : doAbc();
A statement is supposed to just perform some operations.
A conditional operator is meant to return a value.
As a novelty, mIRCscripting allows you to do this
alias canI? {
$iif($1 == 1,doThis,doThat)
}
alias doThis echo -a this can.
alias doThat echo -a that can.
calling it with /canI? 1 will echo this can.
calling it with /canI? 2 will echo that can.
Wouldn't this be exactly the same as the if statement?
if (isXyz) doXyz(); else doAbc();
Some languages do allow you to use the conditional operator as a statement. Perl comes to mind.
An expression, including a conditional expression, may be used on its own as a statement in Java and many other languages (I'd go as far as to say most currently-popular languages).
It's specifically ‘void-returning’ in Java that's the issue here, not anything to do with conditionals. It's sometimes considered bad taste to hide active (non-idempotent; with side-effects) code inside an expression, and active functions often return void. So because Java is a prescriptive language, it disallows using a void function in an expression. Many other languages are more permissive and will allow it.
You could get around it by having doAbc and doXyz return something — zero, a boolean, anything: it doesn't matter as long as they're the same type for both, the result will be thrown away in an ExpressionStatement. But I don't really know why you'd want to; as others have said, this is indeed a case where doing it in an expression is in poor taste and largely pointless.
I think your question is the wrong way round.... the conditional operator was added because the "IF THEN" statement couldn't be used as an evaluation statement.
In my option you should only use the conditional operator when conditionally evaluating as it is inherently less clear than using "IF THEN" constructs when purely implementing a condition.
Conditional operators cannot typically contain blocks of multiple instructions on each condition result, "IF THEN" can.

Verb for what you do when you have A and do A AND B

Ok, this may seem like a silly question, but it is seriously bugging me. Hoping some fellow programmer has a good word for it!
Thing is, I am making an ExpressionBuilder class to help me build up expressions to use with LinqToSQL. And my problem is about how word myself when describing what two methods. And it kind of is a problem in general for me too when talking about it. Here is the issue:
You have an Expression<Func<T, bool>>, A. Later you get another one, B. You are now going to combine that B with A using && / AndAlso or || / OrElse. So for example like this:
A = A && B;
Alright. So, what did you just do there? What is the verb for what you did with B to A? If you think in a series of this stuff, like A = A && B && C && D && E && ..., you could sort of say that you then "add" F to that series. But that wouldn't really be correct either I feel...
What I feed would be most "correct" would be that you take B and you "and" it to/with A. You take B and you "or" it to/with A. But can "and" and "or" be used as a verb?? Is that considered ok? Feels like incredibly bad English... but maybe it is ok in a programming environment? Or?
If I was speaking to a mathematician, I would probably use terms like "perform a logical conjunction" (or disjunction).
If I was speaking to a fellow programmer, I would use "and" and "or" as verbs directly.
If I was speaking with my mom, I would probably just find pen and paper and start drawing Venn diagrams.
In logic AND is the conjunction operator, so you are conjoining A and B. OR is disjoining.
I think it is perfectly ok to use "and" as a verb in this case. You and'd A and B. It just seems bad due to the words AND and OR themselves. If you talk about it with XOR though, it doesn't sound so bad to say you XOR'd something yet you're effectively saying the same thing.
Compound?
Naming is always one of the hardest things.
If you are adding (e.g. numbers, or items to a set/list) then I'd say "Add"
If you are concatenating (e.g. strings) then I'd say "Append"
Alternatively... if you are just "adding" another item to a list... "Push" works too
Does the output of A feed into the input of B?
If so I'd use 'chain', or 'compose' in the sense of functional composition
Otherwise, if they're independant functions which are being combined, then maybe 'cat' as shorthand for concatenate.
In general, this is composition of functions. Since these functions are all predicates, you're putting them together with the various logical operations, so the specific composition would be conjunction, disjunction, etc. All the basic set theory terms I forgot since college!
How about logically connect?
-- http://en.wikipedia.org/wiki/Logical_connective
I'd go with Set Notation (Venn Diagrams) when explaining it.
AND: A intersected with B
OR: A unioned with B
http://www.purplemath.com/modules/venndiag2.htm

How do you write a (simple) variable "toggle"?

Given the following idioms:
1)
variable = value1
if condition
variable = value2
2)
variable = value2
if not condition
variable = value1
3)
if condition
variable = value2
else
variable = value1
4)
if not condition
variable = value1
else
variable = value2
Which do you prefer, and why?
We assume the most common execution path to be that of condition being false.
I tend to learn towards using 1), although I'm not exactly sure why I like it more.
Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.
variable = condition ? value2 : value1
...
variable = value2 if condition else value1
In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention.
I prefer method 3 because it is more concise and a logical unit. It sets the value only once, it can be moved around as a block, and it's not that error-prone (which happens, esp. in method 1 if setting-to-value1 and checking-and-optionally-setting-to-value2 are separated by other statements)
3) is the clearest expression of what you want to happen. I think all the others require some extra thinking to determine which value is going to end up in the variable.
In practice, I would use the ternary operator (?:) if I was using a language that supported it. I prefer to write in functional or declarative style over imperative whenever I can.
I tend to use #1 alot myself. if condition reads easier than if !condition, especially if you acidentally miss the '!', atleast to my mind atleast.
Most coding I do is in C#, but I still tend to steer clear of the terniary operator, unless I'm working with (mostly) local variables. Lines tend to get long VERY quickly in a ternary operator if you're calling three layers deep into some structure, which quickly decreases the readability again.
Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax
This is no argument for not using them in languages that do provide such a syntax. Incidentally, that includes all current mainstream languages after my last count.
and they are not suitable for extending the variable assignment to include more than one statement in the future.
This is true. However, it's often certain that such an extension will absolutely never take place because the condition will always yield one of two possible cases.
In such situations I will always prefer the expression variant over the statement variant because it reduces syntactic clutter and improves expressiveness. In other situations I tend to go with the switch statement mentioned before – if the language allows this usage. If not, fall-back to generic if.
switch statement also works. If it's simple and more than 2 or 3 options, that's what I use.
In a situation where the condition might not happen. I would go with 1 or 2. Otherwise its just based on what i want the code to do. (ie. i agree with cruizer)
I tend to use if not...return.
But that's if you are looking to return a variable. Getting disqualifiers out of the way first tends to make it more readable. It really depends on the context of the statement and also the language. A case statement might work better and be readable most of the time, but performance suffers under VB so a series of if/else statements makes more sense in that specific case.
Method 1 or method 3 for me. Method 1 can avoid an extra scope entrance/exit, but method 3 avoids an extra assignment. I'd tend to avoid Method 2 as I try to keep condition logic as simple as possible (in this case, the ! is extraneous as it could be rewritten as method 1 without it) and the same reason applies for method 4.
It depends on what the condition is I'm testing.
If it's an error flag condition then I'll use 1) setting the Error flag to catch the error and then if the condition is successfull clear the error flag. That way there's no chance of missing an error condition.
For everything else I'd use 3)
The NOT logic just adds to confusion when reading the code - well in my head, can't speak for eveyone else :-)
If the variable has a natural default value I would go with #1. If either value is equally (in)appropriate for a default then I would go with #2.
It depends. I like the ternary operators, but sometimes it's clearer if you use an 'if' statement. Which of the four alternatives you choose depends on the context, but I tend to go for whichever makes the code's function clearer, and that varies from situation to situation.