How to suppress VB's "Iteration variable shouldn't been used in lambda expression" - vb.net

I'm working with LINQ in VB.NET and sometimes I get to a query like
For i = 0 To 10
Dim num = (From n In numbers Where n Mod i = 0 Select n).First()
Next
and then it comes the warning "Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable."
I know it's not a good practice to use the iteration variable in the lambda expression, because lambda expressions are evaluated only when needed. (This question is about that)
Now my question is, how to suppress this warning in cases where the expression is evaluated in-place, with constructions like First(), Single(), ToList(), etc. (It's only a warning, but i like my code clean.)
(Declaring a local variable and passing the iteration variable to it is an option, but I'm looking for a clean solution.)

In this particular case where the lambda is evaluated immediately, then you can safely eliminate the warning by moving the declaration of the iteration variable outside the for loop.
Dim i = 0
For i = 0 To 10
...
I do want to stress though that this only works if the lambda does not escape the for loop (true for your scenario).
Also here is a detailed link to an article I wrote on this warning (why it exists, how to avoid it, etc ...)
http://blogs.msdn.com/b/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx

Related

Cannot assign an if statement to a variable

The problem here is that I do not understand well the difference between statements and blocks in control flow.
Looking the ternary operator I can use it to assign a variable. But this is an operator, so it is like applying a function--isn't it?
> my $variable = True ?? 34 !! 42;
34
since in the raku documentation says:
if documentation
if
To conditionally run a block of code, use an if followed by a
condition. The condition, an expression, will be evaluated immediately
after the statement before the if finishes. The block attached to the
condition will only be evaluated if the condition means True when
coerced to Bool. Unlike some languages the condition does not have to
be parenthesized, instead the { and } around the block are mandatory:
do documentation
do
The simplest way to run a block where it cannot be a stand-alone statement is by writing do before it:
so this should work in both cases:
> my $variable = do {34};
34
> my $variable = if True {34;} else {43;}
===SORRY!===
Word 'if' interpreted as a listop; please use 'do if' to introduce the statement control word
------> my $variable = if⏏ True {34;} else {43;}
Unexpected block in infix position (two terms in a row)
------> my $variable = if True⏏ {34;} else {43;}
as said in the error I need to add the do:
> my $variable = do if True {34;} else {43;}
34
So the if really does not run the block...or what is the real problem here?
TL;DR: The actual difference is between statement and expression, not statement and block. do is a statement prefix that creates expressions.
if actually creates a statement (anything that is run in Raku is), however, what it's not is an expression. do is a statement prefix, and what it does is turn statements into expressions.
However, if is not really a first-class function that you can assign to a variable or handle around. Whenever you find pieces of syntax such as that one (or for, for instance), you need to prefix them with do to "expressionify" them.
say &say.^name;# OUTPUT: «Sub␤» say &do.^name; # OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Undeclared routine:␤...
say &if.^name; # OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Undeclared routine:␤ if used at line 1␤␤»
So if, by itself, does not create a block, it does not create an expression, it simply creates a statement. You need to precede it with do if you want it to actually turn it into a expression. It does run the block that's behind it, however.
Let's go back to the original question, statements and blocks. Blocks are objects, first-class citizens. You can use them, apply them, pass them around.
my &ifs = { if $_ {34} else {43}};
ifs(True).say; # OUTPUT: «34␤»
Statements are throwaway blocks you simply run. In some cases, they are also expressions: they yield a result which, then, you can assign.
my &ifs = { if $_ {34} else {43}};
my $result = ifs(True).say; # OUTPUT: «34␤»
say $result; # OUTPUT: «True␤»
The ifs(True).say statement prints to output, it also produces a result that can be assigned. All three lines are also statements, and as a matter of fact, expressions too.
Some control structures, however, do not create expressions.
Some others do; for creates a expression; while does not.
if is an example of this. They don't produce a result. You use them for the side effects: running a statement (if true) or another (if not). You might turn them into a block, as above, and pass them around. Or you can just precede them with do and make them produce a throwaway result, which you can then use.
So it will very much depend on your actual use case. You can surround the if statement with curly braces and create a block; or you can simply use the result creating an expression. Or you might want to use it just for the side effects, doing nothing.

String replacement with .subst in a for loop

I'd like to make a string substitution in a for block using a named capture. I've expected to get the numbers 1,2,3 as output. But it is Nil for the first run, and then 1 and 2 for the 2nd and 3rd run. How do I use the .subst correctly in the loop construct? I see the same behavior when using a map construct instead the for loop. It does work as expected, if I replace with a fixed string value.
for <a1 b2 c3> -> $var {
say $var;
say $var.subst(/.$<nr>=(\d)/, $<nr>); #.subst(/.$<nr>=(\d)/, 'X'); #OK
}
#`[
This is Rakudo version 2019.11 built on MoarVM version 2019.11
Output:
a1
Use of Nil in string context
in block at test3.pl6 line 3
b2
1
c3
2
]
TL;DR Defer evaluation of $<nr> until after evaluation of the regex. #JoKing++ suggests one way. Another is to just wrap the replacement with braces ({$<nr>}).
What happens when your original code calls subst
Before Raku attempts to call the subst routine, it puts together a list of arguments to pass to it.
There are two values. The first is a regex. It does not run. The second value is $<nr>. It evaluates to Nil because, at the start of a program, the current match object variable is bound to something that claims its value is Nil and any attempt to access the value of a key within it -- $<nr> -- also returns Nil. So things have already gone wrong at this point, before subst ever runs.
Once Raku has assembled this list of arguments, it attempts to call subst. It succeeds, and subst runs.
To get the next match, subst runs the regex. This updates the current match object variable $/. But it's too late to make any difference to the substitution value that has already been passed to subst.
With match in hand, subst next looks at the substitution argument. It finds it's Nil and acts accordingly.
For the second call of subst, $<nr> has taken on the value from the first call of subst. And so on.
Two ways to defer evaluation of $<nr>
#JoKing suggests considering use of S///. This construct evaluates the regex (between the first pair of /s) first, then the replacement (between the last pair of /s). (The same principle applies if you use other valid S syntaxes like S[...] = ....)
If you use subst, then, as explained in the previous section, Raku puts together the argument list for it before calling it. It finds a regex (which it does not run) and a closure (which it does not run either). It then attempts to call subst with those arguments and succeeds in doing so.
Next, subst starts running. It has received code for both the match (a regex) and the substitution (a closure).
It runs the regex as the matching operation. If the regex returns a match then subst runs the closure and uses the value it returns as the substitution.
Thus, because we switched from passing $<nr> as a naked value, which meant it got frozen into Nil, to passing it wrapped in a closure, which deferred its evaluation until $/ had been set to a match with a populated <nr> entry, we solved the problem.
Note that this only works because whoever designed/implemented subst was smart/nice enough to allow both the match and substitution arguments to be forms of Code (a regex for the match and ordinary closure for the substitution) if a user wants that. It then runs the match first and only then runs the substitution closure if it's been passed one, using the result of that latter call as the final substitution. Similarly, S/// works because that has been designed to only evaluate the replacement after it's first evaluated the substitution.

Evaluating Variables in Load Script

Is there any reason that this syntax shouldn't work in Qlikview load script??
Let v_myNumber = year(today());
Let v_myString = '2017-08';
If left($(v_myString),4) = text($(v_myNumber)) Then
'do something
Else
'do something else
End If;
I've tried both ways where I convert variable string to number and evaluate against the number variable directly and this way. They won't evaluate to equivalence when they should..
Left function is expecting a string as is getting something else as a parameter. As you are currently doing, the function will be called as Left(2017-08, 4) which is unhandle by QlikView.
If you use Left('$(v_myString)',4), it will evaluate as Left('2017-08', 4) as work as expected. Just adding quotes around the variable it should work.
Although QlikView calls them variables, they should really be seen as "stuff to replaced (at sometimes evaluated) at runtime", which is slightly different from a standard "variable" behaviour.
Dollar sign expansion is a big subject, but in short:
if you are setting a variable - no need for $().
if you are using a variable - you can use $(). depends on its context.
if you are using a variable that needs to be evaluated - you have to use $().
for example in a load script: let var1 = 'if(a=1,1,2)' - here later on the script you will probably want to use this variable as $(var1) so it will be evaluated on the fly...
I hope its a little more clear now. variable can be used in many ways at even can take parameters!
for example:
var2 = $1*$2
and then you can use like this: $(var2(2,3)) which will yield 6
For further exploration of this, I would suggest reading this

Is it possible to make Stata throw an error by default when a global macro is not defined, instead of a missing string?

A feature of Stata that is sometimes inconvenient is that calling a non-defined macro returns the missing value . [edit: Stata actually returns a missing string "", not a numerical missing value], instead of throwing an error.
A piece of code, whose correct execution requires the definition of the macro, may just run giving incorrect results if the macro name is misspelled.
E.g.: having defined
global $options = , vce(robust), when
afterwards one writes reg y x $opt instead of reg y x $options the program runs anyway and it may be difficult to realise that the vce() option was not considered.
Is there any way to force Stata to issue an error in this case or is there some useful trick/best practice that can be used to reduce the risk of incurring this sort of mistake?
The feature is described incorrectly. A macro that is undefined is evaluated as an empty string, conventionally written "", i.e. the delimiters " " contain nothing, or -- if you prefer -- nothing is contained between them.
A macro that is undefined is not ever evaluated as numeric system missing, written as a period . (call it dot or stop if you want).
You would see system missing if the macro were set to contain something else that was system missing, which is entirely different. Saved results from programs, for example, might be system missing.
One way to understand this is that macros in Stata contain strings, not numeric values; the fact that some macros have a numeric interpretation is something else. So, an undefined macro is evaluated as an empty string.
Stata programmers learn to use this feature constructively as a way of allowing defaults when macros are undefined and other choices when they are defined.
You are correct that the feature is a source of bugs, as when a spelling mistake leads Stata to see a name that isn't defined and just ignores the reference. The bug is still the programmer's bug, not Stata's.
So, what can you do, apart from check your code as usual? You can always check whether a macro is defined, as in
if "$options" == "" {
* do something
}
else {
* do something else
}
Conversely,
if "$options" != ""
is a test for content.
Alternatively, you could use string scalars. Here is an experiment:
. sysuse auto, clear
(1978 Automobile Data)
. scalar foo = ", meanonly"
. summarize mpg `=scalar(foo)'
. ret li
scalars:
r(N) = 74
r(sum_w) = 74
r(sum) = 1576
r(mean) = 21.2972972972973
r(min) = 12
r(max) = 41
. summarize mpg `=scalar(bar)'
bar not found
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
mpg | 74 21.2973 5.785503 12 41
In this case, there was an error message when an undefined scalar was referred to, but the command was executed any way.
Personally, as a long-term (1991- ) and high intensity Stata user, I just use macros routinely and regard being occasionally bitten by bugs of this kind as a very small price to pay for that. I have not ever used string scalars in this sense before trying to answer this question.
It's a different argument, but I regard using global macros in this way as poor programming style. There are general arguments across programming for minimizing the use of globally declared entities. Local macros are the beasts of choice.

When does = perform comparison instead of assignment?

In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable:
Private Function foo() As Boolean
Dim bar As Integer = 1
Return bar = 2
End Function
Returns: False
OK, but what's the value of bar?
Private Function foo() As KeyValuePair(Of Boolean, Integer)
Dim bar As Integer = 1
Return New KeyValuePair(Of Boolean, Integer)(bar = 2, bar)
End Function
Returns: False, 1
It looks like = will perform a comparison when the statement context demands it, but is this guaranteed? That is, can I be sure that bar will never be set to 2 in this situation?
Also, I know that VB.NET doesn't allow chained inline assignments, which may be for the best. Does this odd = behavior cause any other quirks I should be aware of?
You cannot do in-line assignments in VB, Assignment is an explicit statement:
[Let] <<target-reference>> = <<value-expression>>
The Let is optional and implicit, and hardly ever used anymore. The general rule that you can use to distinguish the [Let] command from equality testing is that for Let, no other keyword may come before the target-reference in the statement. AFAIK, in all cases of = as equality testing, there is one or more other keywords that precede it in the statement.
In your first example, the keyword Return precedes your =, so it's an equality test, and not an assignment.
In your first example you can do either:
Return 2
or
bar = 2
Return bar
As for your question "OK, but what's the value of bar?", bar still equals one.
= in VB cause no quirks. It works exactly as documented, and it always has (including its predecessor, BASIC back to 1968).
If you are starting to code in VB (coming from a language like C#), you should start getting used to the peculiar VB way of doing things; which is based on the idea: as simple and intuitive for the programmer as possible. "If assignation and comparison happen always in different contexts, why not using the same operator and let the context define its exact meaning?" -> VB-way of seeing things. "No, different realities have to be accounted for by different operators. End of the discussion" -> C#-way. :)
Is this reliable? Can you blindly trust on these not-always-clear-for-a-programmer bits? Sure, VB.NET peculiarities are highly-reliable and trustworthy. You can always use = (or Is on some contexts, but VS would tell you) and be completely sure that the code will do what is expected. But the question is: are you sure that you write exactly what you want?
This last question is what, perhaps, is more criticable of VB and what might give some problems to programmers from other languages: the higher the flexibility, the more likely is that you make an error; mainly if you are used to a different format.
Regarding the chained inline assignments, I honestly don't see its true utility (and never use them in C#). Regarding other differences with respect to C#, there are plenty of them; in some cases, I think that the C# approach is better; other times, the VB.NET one. On readability/length of code, I can refer to the With Statement I have always found somehow useful which is not present in C#.
One way to have 100% sure that the expression will be evaluated as an boolean expression is to use ()
e.g
Dim a = 2
Return (a = 1)
Since you cannot set a value to a variable wihtin the parenthesis.
What i want to say is: on an return statament for example you cant assing a value to a variable so, even if you use
a = 1
The compilator knows that this expression only can be an boolean expression.
The same to the if statament and so on..
Heh back in QB45 days we used to exploit the fact that "True" was the numeric value -1. So you would see code like x = 1 - x * (x < 6) (translation: increment x, but reset to 1 when it gets to 6)