Terminology - Does a nested loop have to be in another loop? - nested

Typically, when someone refers to a nested loop, I think of a loop inside a loop. Same for a nested if statement - an if inside an if.
But does it have to refer to that? I mean, would you consider a loop inside an if statement a nested loop? Or an if inside a loop a nested if?
Basically, to be a nested x, does the thing that it is nested inside of have to be another x?
Note: Hopefully obvious, but I'm not asking if it's possible to do these things. Of course it's possible. I'm asking about terminology - "would it make sense to refer to these things this way", not "is it possible to do this thing I'm describing".

Yes, I would say that for a loop to be called nested that it is inside of another loop. This distinction may seem trivial in everyday discussion, but when it comes to analyzing the Big-O runtime of code it makes a huge difference for a "nested" loop to actually be inside of another loop and not an if block.

You would refer to loops nested in if statements or vice versa as nested code blocks or nested statements.
Nested loops must be nested in other loops and nested if statements must be nested in other if statements.

Related

How to represent a method call in a loop in a sequence diagram?

I know that one use a box with "loop" in the corner, when we have a loop which uses several objects. Is it the same with just one object?
Yes. You can place a loop fragment over a self-call and that simply means a repetitive call. A guard placed in square brackets (top left of the fragment) tells when the loop will end.
However, graphical programming isn't the best idea at all. For such trivial cases some note or pseudo code are better suited. In most cases that info is obvious from the context anyway and should not be presented graphically. Don't underestimate the programmers doing the coding in the end.

Ensure variable is a list

I often find myself in a situation where I have a variable that may or may not be a list of items that I want to iterate over. If it's not a list I'll make a list out of it so I can still iterate over it. That way I don't have to write the code inside the loop twice.
def dispatch(stuff):
if type(stuff) is list:
stuff = [stuff]
for item in stuff:
# this could be several lines of code
do_something_with(item)
What I don't like about this is (1) the two extra lines (2) the type checking which is generally discouraged (3) besides I really should be checking if stuff is an iterable because it could as well be a tuple, but then it gets even more complicated. The point is, any robust solution I can think of involves an unpleasant amount of boilerplate code.
You cannot ensure stuff is a list by writing for item in [stuff] because it will make a nested list if stuff is already a list, and not iterate over the items in stuff. And you can't do for item in list(stuff) either because the constructor of list throws an error if stuff is not an iterable.
So the question I'd like to ask: is there anything obvious I've missed to the effect of ensurelist(stuff), and if not, can you think of a reason why such functionality is not made easily accessible by the language?
Edit:
In particular, I wonder why list(x) doesn't allow x to be non-iterable, simply returning a list with x as a single item.
Consider the example of the classes defined in the io module, which provide separate write and writelines methods for writing a single line and writing a list of lines. Provide separate functions that do different things. (One can even use the other.)
def dispatch(stuff):
do_something_with(item)
def dispatch_all(stuff):
for item in stuff:
dispatch(item)
The caller will have an easier time deciding whether dispatch or dispatch_all is the correct function to use than your do-it-all function will have deciding whether it needs to iterate over its argument or not.

Arrays in Haxe with multiple types

In Javascript, it's possible to create an array with nested arrays inside it, in a single line of code. Is it possible to do the equivalent in Haxe?
var a = [
["This is a nested array"],
["This is another nested array"],
"This is not a nested array"
];
Yes, it is exactly the same syntax in this case and a should be typed as Array<Dynamic>.
One other approach for handling mixed-type arrays is to use enums. This will change the run time values, but give the compiler a way to define and handle the types that the array could contain.
https://haxe.org/manual/types-enum-using.html
This approach won't work if you can't control how the arrays are being filled.

Counter++ in Parallel.ForEach

I understand using an iterator++ inside Parallel.ForEach is not a good option but right now i'm forced to use a counter inside a Parallel.ForEach loop, counter is used to pick up column names of a dynamic object at runtime.Any suggestion what would be the best option?.I read somewhere at StackOverflow that using "Interlocked" is again a bad design inside Parallel.ForEach.
If you really need parallel processing, the indices will have to be pre-computed. Something like Enumerable.Range(0, cols.Length).ToArray(). Otherwise, each column will depend on the previous one, which obviously doesn't parallelize.

Why do some programming languages restrict you from editing the array you're looping through?

Pseudo-code:
for each x in someArray {
// possibly add an element to someArray
}
I forget the name of the exception this throws in some languages.
I'm curious to know why some languages prohibit this use case, whereas other languages allow it. Are the allowing languages unsafe -- open to some pitfall? Or are the prohibiting languages simply being overly cautious, or perhaps lazy (they could have implemented the language to gracefully handle this case, but simply didn't bother).
Thanks!
What would you want the behavior to be?
list = [1,2,3,4]
foreach x in list:
print x
if x == 2: list.remove(1)
possible behaviors:
list is some linked-list type iterator, where deletions don't affect your current iterator:
[1,2,3,4]
list is some array, where your iterator iterates via pointer increment:
[1,2,4]
same as before, only the system tries to cache the iteration count
[1,2,4,<segfault>]
The problem is that different collections implementing this enumerable/sequence interface that allows for foreach-looping have different behaviors.
Depending on the language (or platform, as .Net), iteration may be implemented differently.
Typically a foreach creates an Iterator or Enumerator object on the array, which internally keeps its state about the iteration details. If you modify the array (by adding or deleting an element), the iterator state would be inconsistent in regard to the new state of the array.
Platforms such as .Net allow you to define your own enumerators which may not be susceptible to adding/removing elements of the underlying array.
A generic solution to the problem of adding/removing elements while iterating is to collect the elements in a new list/collection/array, and add/remove the collected elements after the enumeration has completed.
Suppose your array has 10 elements. You get to the 7th element, and decide there that you need to add a new element earlier in the array. Uh-oh! That element doesn't get iterated on! for each has the semantics, to me at least, of operating on each and every element of the array, once and only once.
Your pseudo example code would lead to an infinite loop. For each element you look at, you add one to the collection, hence if you have at least 1 element to start with, you will have i (iterative counter) + 1 elements.
Arrays are typically fixed in the number of elements. You get flexible sized widths through wrapped objects (such as List) that allow the flexibility to occur. I suspect that the language may have issues if the mechanism they used created a whole new array to allow for the edit.
Many compiled languages implement "for" loops with the assumption that the number of iterations will be calculated once at loop startup (or better yet, compile time). This means that if you change the value of the "to" variable inside the "for i = 1 to x" loop, it won't change the number of iterations. Doing this allows a legion of loop optimizations, which are very important in speeding up number-crunching applications.
If you don't like that semantics, the idea is that you should use the language's "while" construct instead.
Note that in this view of the world, C and C++ don't have proper "for" loops, just fancy "while" loops.
To implement the lists and enumerators to handle this, would mean a lot of overhead. This overhead would always be there, and it would only be useful in a vast miniority of the cases.
Also, any implementation that were chosen would not always make sense. Take for example the simple case of inserting an item in the list while enumerating it, would the new item always be included in the enumeration, always excluded, or should that depend on where in the list the item was added? If I insert the item at the current position, would that change the value of the Current property of the enumerator, and should it skip the currently current item which is then the next item?
This only happens within foreach blocks. Use a for loop with an index value and you'll be allowed to. Just make sure to iterate backwards so that you can delete items without causing issues.
From the top of my head there could be two scenarios of implementing iteration on a collection.
the iterator iterates over the collection for which it was created
the iterator iterates over a copy of the collection for which it was created
when changes are made to the collection on the fly, the first option should either update its iteration sequence (which could be very hard or even impossible to do reliably) or just deny the possibility (throw an exception). The last of which obviously is the safe option.
In the second option changes can be made upon the original collection without bothering the iteration sequence. But any adjustments will not be seen in the iteration, this might be confusing for users (leaky abstraction).
I could imagine languages/libraries implementing any of these possibilities with equal merit.

Resources