What languages don't define execution order for multi-statement for statements? - syntax

Some C-like languages allow multiple statements in the update part of a for statement, e.g.
for (int i = 0; i < limit; i++, butter--, syrup--, pancakesDevoured++)
Java explicitly defines the order for such statements in JLS 14.14.1.2 and 15.8.3 of ECMA-334 (C#) says "the expressions of the for-iterator, if any, are evaluated in
sequence" which I'm reading as left-to-right.
What languages, if any, allow multiple statements in the update part of a for loop but either don't define an ordering for such statements or use an order other than left to right?
edit: removed the C tag since that started a sequence point discussion and there's plenty of that already.

Technically, that's a single expression, not one or more statements, though the distinction isn't super important.
Good old C makes only limited promises about what order expressions like this will be evaluated in. In your example, the order doesn't matter. But consider this expression:
a[i++] = i
If i was 1 before evaluating this expression, should a[1] now equal 1 or 2? As I understand the C specification, the behavior of this expression is undefined, meaning that what you get depends on which compiler you use.
Thanks to #mizo for a readable reference on sequence points, and to #ChrisDodd for pointing out that if you're making simple independent assignments that are separated by the comma operator, C and C++ do fully specify a left-to-right evaluation order.

Related

Is a single constant value considered an expression?

After reading this answer on a CSS question, I wonder:
In Computer Science, is a single, constant value considered an expression?
In other words, is 7px an expression? What about just 7?
Quoting Wikipedia, emphasis mine:
An expression in a programming language is a combination of one or more explicit values, constants, variables, operators, and functions that the programming language interprets [...] and computes to produce [...] another value. This process, as for mathematical expressions, is called evaluation.
Quoting MS Docs, emphasis mine:
An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace. Expressions can consist of a literal value [...].
These both seems to indicate that values are expressions. However, one could argue that a value will not be evaluated, as it is already only a value, and therefore doesn't qualify.
Quoting Techopedia, emphasis mine:
[...] In terms of structure, experts point out that an expression inherently needs at least one 'operand’ or value that is acted on, and must have one or more operators. [...]
This suggests that even x does not qualify as expression as it is lacking one or more operators.
It depends on the exact definition of course, but under most definitions expressions are defined recursively with constants being one of the basis cases. So, yes, literal values are special cases of expressions.
You can look at grammars for various languages such as the one for Python
If you trace through the grammar you see that an expr can be an atom which includes number literals. The fact that number literals are Python expressions is also obvious when you consider productions like:
comparison: expr (comp_op expr)*
This is the production which captures expressions like x < 7, which wouldn't be captured if 7 isn't a valid expression.
In Computer Science, is a single, constant value considered an expression?
It depends entirely on the context. For example, FORTRAN, BASIC, and COBOL all have line numbers. Those are numeric constant values that are not expressions.
In other contexts (even within those languages) a numeric constant may be an expression.

most readable way in XPath to write "is value X a member of sequence S"?

XPath 2.0 has some new functions and syntax, relative to 1.0, that work with sequences. Some of theset don't really add to what the language could already do in 1.0 (with node sets), but they make it easier to express the desired logic in ways that are more readable. This increases the chances of the programmer getting the code correct -- and keeping it that way. For example,
empty(s) is equivalent to not(s), but its intent is much clearer when you want to test whether a sequence is empty.
Correction: the effective boolean value of a sequence is in general more complicated than that. E.g. empty((0)) != not((0)). This applies to exists(s) vs. s in a boolean context as well. However, there are domains of s where empty(s) is equivalent to not(s), so the two could be used interchangeably within those domains. But this goes to show that the use of empty() can make a non-trivial difference in making code easier to understand.
Similarly, exists(s) is equivalent to boolean(s) that already existed in XPath 1.0 (or just s in a boolean context), but again is much clearer about the intent.
Quantified expressions; e.g. "some $x in expression satisfies test($x)" would be equivalent to boolean(expression[test(.)]) (although the new syntax is more flexible, in that you don't need to worry about losing the context item because you have the variable to refer to it by).
Similarly, "every $x in expression satisfies test($x)" would be equivalent to not(expression[not(test(.))]) but is more readable.
These functions and syntax were evidently added at no small cost, solely to serve the goal of writing XPath that is easier to map to how humans think. This implies, as experienced developers know, that understandable code is significantly superior to code that is difficult to understand.
Given all that ... what would be a clear and readable way to write an XPath test expression that asks
Does value X occur in sequence S?
Some ways to do it: (Note: I used X and S notation here to indicate the value and the sequence, but I don't mean to imply that these subexpressions are element name tests, nor that they are simple expressions. They could be complicated.)
X = S: This would be one of the most unreadable, since it requires the reader to
think about which of X and S are sequences vs. single values
understand general comparisons, which are not obvious from the syntax
However, one advantage of this form is that it allows us to put the topic (X) before the comment ("is a member of S"), which, I think, helps in readability.
See also CMS's good point about readability, when the syntax or names make the "cardinality" of X and S obvious.
index-of(S, X): This one is clear about what's intended as a value and what as a sequence (if you remember the order of arguments to index-of()). But it expresses more than we need to: it asks for the index, when all we really want to know is whether X occurs in S. This is somewhat misleading to the reader. An experienced developer will figure out what's intended, with some effort and with understanding of the context. But the more we rely on context to understand the intent of each line, the more understanding the code becomes a circular (spiral) and potentially Sisyphean task! Also, since index-of() is designed to return a list of all the indexes of occurrences of X, it could be more expensive than necessary: a smart processor, in order to evaluate X = S, wouldn't necessarily have to find all the contents of S, nor enumerate them in order; but for index-of(S, X), correct order would have to be determined, and all contents of S must be compared to X. One other drawback of using index-of() is that it's limited to using eq for comparison; you can't, for example, use it to ask whether a node is identical to any node in a given sequence.
Correction: This form, used as a conditional test, can result in a runtime error: Effective boolean value is not defined for a sequence of two or more items starting with a numeric value. (But at least we won't get wrong boolean values, since index-of() can't return a zero.) If S can have multiple instances of X, this is another good reason to prefer form 3 or 6.
exists(index-of(X, S)): makes the intent clearer, and would help the processor eliminate the performance penalty if the processor is smart enough.
some $m in S satisfies $m eq X: This one is very clear, and matches our intent exactly. It seems long-winded compared to 1, and that in itself can reduce readability. But maybe that's an acceptable price for clarity. Keep in mind that X and S could potentially be complex expressions themselves -- they're not necessarily just variable references. An advantage is that since the eq operator is explicit, you can replace it with is or any other comparison operator.
S[. eq X]: clearer than 1, but shares the semantic drawbacks of 2: it computes all members of S that are equal to X. Actually, this could return a false negative (incorrect effective boolean value), if X is falsy. E.g. (0, 1)[. eq 0] returns 0 which is falsy, even though 0 occurs in (0, 1).
exists(S[. eq X]): Clearer than 1, 2, 3, and 5. Not as clear as 4, but shorter. Avoids the drawbacks of 5 (or at least most of them, depending on the processor smarts).
I'm kind of leaning toward the last one, at this point: exists(S[. eq X])
What about you... As a developer coming to a complex, unfamiliar XSLT or XQuery or other program that uses XPath 2.0, and wanting to figure out what that program is doing, which would you find easiest to read?
Apologies for the long question. Thanks for reading this far.
Edit: I changed = to eq wherever possible in the above discussion, to make it easier to see where a "value comparison" (as opposed to a general comparison) was intended.
For what it's worth, if names or context make clear that X is a singleton, I'm happy to use your first form, X = S -- for example when I want to check an attribute value against a set of possible values:
<xsl:when test="#type = ('A', 'A+', 'A-', 'B+')" />
or
<xsl:when test="#type = $magic-types"/>
If I think there is a risk of confusion, then I like your sixth formulation. The less frequently I have to remember the rules for calculating an effective boolean value, the less frequently I make a mistake with them.
I prefer this one:
count(distinct-values($seq)) eq count(distinct-values(($x, $seq)))
When $x is itself a sequence, this expression implements the (value-based) subset of relation between two sets of values, that are represented as sequences. This implementation of subset of has just linear time complexity -- vs many other ways of expressing this, that have O(N^2)) time complexity.
To summarize, the question whether a single value belongs to a set of values is a special case of the question whether one set of values is a subset of another. If we have a good implementation of the latter, we can simply use it for answering the former.
The functx library has a nice implementation of this function, so you can use
functx:is-node-in-sequence($X, $Y)
(this particular function can be found at http://www.xqueryfunctions.com/xq/functx_is-node-in-sequence.html)
The whole functx library is available for both XQuery (http://www.xqueryfunctions.com/) and XSLT (http://www.xsltfunctions.com/)
Marklogic ships the functx library with their core product; other vendors may also.
Another possibility, when you want to know whether node X occurs in sequence S, is
exists((X) intersect S)
I think that's pretty readable, and concise. But it only works when X and the values in S are nodes; if you try to ask
exists(('bob') intersect ('alice', 'bob'))
you'll get a runtime error.
In the program I'm working on now, I need to compare strings, so this isn't an option.
As Dimitri notes, the occurrence of a node in a sequence is a question of identity, not of value comparison.

How to get rid of unnecessary parentheses in mathematical expression

Hi I was wondering if there is any known way to get rid of unnecessary parentheses in mathematical formula. The reason I am asking this question is that I have to minimize such formula length
if((-if(([V].[6432])=0;0;(([V].[6432])-([V].[6445]))*(((([V].[6443]))/1000*([V].[6448])
+(([V].[6443]))*([V].[6449])+([V].[6450]))*(1-([V].[6446])))))=0;([V].[6428])*
((((([V].[6443]))/1000*([V].[6445])*([V].[6448])+(([V].[6443]))*([V].[6445])*
([V].[6449])+([V].[6445])*([V].[6450])))*(1-([V].[6446])));
it is basically part of sql select statement. It cannot surpass 255 characters and I cannot modify the code that produces this formula (basically a black box ;) )
As you see many parentheses are useless. Not mentioning the fact that:
((a) * (b)) + (c) = a * b + c
So I want to keep the order of operations Parenthesis, Multiply/Divide, Add/Subtract.
Im working in VB, but solution in any language will be fine.
Edit
I found an opposite problem (add parentheses to a expression) Question.
I really thought that this could be accomplished without heavy parsing. But it seems that some parser that will go through the expression and save it in a expression tree is unevitable.
If you are interested in remove the non-necessary parenthesis in your expression, the generic solution consists in parsing your text and build the associated expression tree.
Then, from this tree, you can find the corresponding text without non-necessary parenthesis, by applying some rules:
if the node is a "+", no parenthesis are required
if the node is a "*", then parenthesis are required for left(right) child only if the left(right) child is a "+"
the same apply for "/"
But if your problem is just to deal with these 255 characters, you can probably just use intermediate variables to store intermediate results
T1 = (([V].[6432])-([V].[6445]))*(((([V].[6443]))/1000*([V].[6448])+(([V].[6443]))*([V].[6449])+([V].[6450]))*(1-([V].[6446])))))
T2 = etc...
You could strip the simplest cases:
([V].[6432]) and (([V].[6443]))
Becomes
v.[6432]
You shouldn't need the [] around the table name or its alias.
You could shorten it further if you can alias the columns:
select v.[6432] as a, v.[6443] as b, ....
Or even put all the tables being queried into a single subquery - then you wouldn't need the table prefix:
if((-if(a=0;0;(a-b)*((c/1000*d
+c*e+f)*(1-g))))=0;h*
(((c/1000*b*d+c*b*
e+b*f))*(1-g));
select [V].[6432] as a, [V].[6445] as b, [V].[6443] as c, [V].[6448] as d,
[V].[6449] as e, [V].[6450] as f,[V].[6446] as g, [V].[6428] as h ...
Obviously this is all a bit psedo-code, but it should help you simplify the full statement
I know this thread is really old, but as it is searchable from google.
I'm writing a TI-83 plus calculator program that addresses similar issues. In my case, I'm trying to actually solve the equation for a specific variable in number, but it may still relate to your problem, although I'm using an array, so it might be easier for me to pick out specific values...
It's not quite done, but it does get rid of the vast majority of parentheses with (I think), a somewhat elegant solution.
What I do is scan through the equation/function/whatever, keeping track of each opening parenthese "(" until I find a closing parenthese ")", at which point I can be assured that I won't run into any more deeply nested parenthese.
y=((3x + (2))) would show the (2) first, and then the (3x + (2)), and then the ((3x + 2))).
What it does then is checks the values immediately before and after each parenthese. In the case above, it would return + and ). Each of these is assigned a number value. Between the two of them, the higher is used. If no operators are found (*,/,+,^, or -) I default to a value of 0.
Next I scan through the inside of the parentheses. I use a similar numbering system, although in this case I use the lowest value found, not the highest. I default to a value of 5 if nothing is found, as would be in the case above.
The idea is that you can assign a number to the importance of the parentheses by subtracting the two values. If you have something like a ^ on the outside of the parentheses
(2+3)^5
those parentheses are potentially very important, and would be given a high value, (in my program I use 5 for ^).
It is possible however that the inside operators would render the parentheses very unimportant,
(2)^5
where nothing is found. In that case the inside would be assigned a value of 5. By subtracting the two values, you can then determine whether or not a set of parentheses is neccessary simply by checking whether the resulting number is greater than 0. In the case of (2+3)^5, a ^ would give a value of 5, and a + would give a value of 1. The resulting number would be 4, which would indicate that the parentheses are in fact needed.
In the case of (2)^5 you would have an inner value of 5 and an outer value of 5, resulting
in a final value of 0, showing that the parentheses are unimportant, and can be removed.
The downside to this is that, (at least on the TI-83) scanning through the equation so many times is ridiculously slow. But if speed isn't an issue...
Don't know if that will help at all, I might be completely off topic. Hope you got everything up and working.
I'm pretty sure that in order to determine what parentheses are unnecessary, you have to evaluate the expressions within them. Because you can nest parentheses, this is is the sort of recursive problem that a regular expression can only address in a shallow manner, and most likely to incorrect results. If you're already evaluating the expression, maybe you'd like to simplify the formula if possible. This also gets kind of tricky, and in some approaches uses techniques that that are also seen in machine learning, such as you might see in the following paper: http://portal.acm.org/citation.cfm?id=1005298
If your variable names don't change significantly from 1 query to the next, you could try a series of replace() commands. i.e.
X=replace([QryString],"(([V].[6443]))","[V].[6443]")
Also, why can't it surpass 255 characters? If you are storing this as a string field in an Access table, then you could try putting half the expression in 1 field and the second half in another.
You could also try parsing your expression using ANTLR, yacc or similar and create a parse tree. These trees usually optimize parentheses away. Then you would just have to create expression back from tree (without parentheses obviously).
It might take you more than a few hours to get this working though. But expression parsing is usually the first example on generic parsing, so you might be able to take a sample and modify it to your needs.

Why is short-circuiting not the default behavior in VB?

VB has operators AndAlso and OrElse, that perform short-circuiting logical conjunction.
Why is this not the default behavior of And and Or expressions since short-circuiting is useful in every case.
Strangely, this is contrary to most languages where && and || perform short-circuiting.
Because the VB team had to maintain backward-compatibility with older code (and programmers!)
If short-circuiting was the default behavior, bitwise operations would get incorrectly interpreted by the compiler.
The Ballad of AndAlso and OrElse by Panopticon Central
Our first thought was that logical operations are much more common than bitwise operations, so we should make And and Or be logical operators and add new bitwise operators named BitAnd, BitOr, BitXor and BitNot (the last two being for completeness). However, during one of the betas it became obvious that this was a pretty bad idea. A VB user who forgets that the new operators exist and uses And when he means BitAnd and Or when he means BitOr would get code that compiles but produces "bad" results.
I do not find short-circuiting to be useful in every case. I use it only when required. For instance, when checking two different and unconnected variables, it would not be required:
If x > y And y > z Then
End If
As the article by Paul Vick illustrates (see link provided by Ken Browning above), the perfect scenario in which short-circuiting is useful is when an object has be checked for existence first and then one of its properties is to be evaluated.
If x IsNot Nothing AndAlso x.Someproperty > 0 Then
End If
So, in my opinion both syntactical options are very much required.
Explicit short-circuit makes sure that the left operand is evaluated first.
In some languages other than VB, logical operators may perform an implicit short circuit but may evaluate the right operator first (depending for instance on the complexity of the expressions at left and at right of the logical operator).

What is the operator precedence order in Visual Basic 6.0?

What is the operator precedence order in Visual Basic 6.0 (VB6)?
In particular, for the logical operators.
Arithmetic Operation Precedence Order
^
- (unary negation)
*, /
\
Mod
+, - (binary addition/subtraction)
&
Comparison Operation Precedence Order
=
<>
<
>
<=
>=
Like, Is
Logical Operation Precedence Order
Not
And
Or
Xor
Eqv
Imp
Source: Sams Teach Yourself Visual Basic 6 in 24 Hours — Appendix A: Operator Precedence
It depends on whether or not you're in the debugger. Really. Well, sort of.
Parentheses come first, of course. Then arithmateic (+,-,*,/, etc). Then comparisons (>, <, =, etc). Then the logical operators. The trick is the order of execution within a given precedence level is not defined. Given the following expression:
If A < B And B < C Then
you are guaranteed the < inequality operators will both be evaluated before the logical And comparison. But you are not guaranteed which inequality comparison will be executed first.
IIRC, the debugger executes left to right, but the compiled application executes right to left. I could have them backwards (it's been a long time), but the important thing is they're different. The actual precedence doesn't change, but the order of execution might.
Use parentheses
EDIT: That's my advice for new code! But Oscar is reading someone else's code, so must figure it out somehow. I suggest the VBA manual topic Operator Precedence. VBA is 99% equivalent to VB6 - and expression evaluation is 100% equivalent. I have pasted the logical operator information here.
Logical operators are evaluated in the following order of precedence:
Not
And
Or
Xor
Eqv
Imp
The topic also explains precedence for comparison and arithmetic operators.
I would suggest once you have figured out the precendence, you put in parentheses unless there is some good reason not to edit the code.

Resources