Turn for in Loops Local Variables into Mutable Variables

turn for in loops local variables into mutable variables

You can make city mutable by adding var to its declaration:

for (country, var city) in countries {

Unfortunately, changing it won't affect your countries Dictionary, because you're getting a copy of each sub-Dictionary. To do what you want, you'll need to loop through the keys of countries and change things from there:

for country in countries.keys {
if countries[country]!["London"] != nil {
countries[country]!["London"]! = "Picadilly Circus"
}
}

Ruby loop local variables and inmutability

each loops often mutate the object. Each has to do something.
Because each doesn't return anything useful - it returns the array itself, It won't mutate the object if it sends every element somewhere, like to be printed on screen.

foo.each do |bar|
# do something with element like
# print it, change it, save it
end

Functional alterantive is map

foo.map { |bar| bar.something }

It returns new array which is original array processed in immutable way. Obviously you have to be careful to use immutable methods. This would not be immutable:

foo.map { |bar| bar.something! } 

Here something! does something destructive to the element of array.
However I have never seen map used like that. Use each for something destructive.

JS closure for mutable variables

Object assignment does not make copy of the objects, the same object is referenced by all the three variables. So, even changing the value inside the loop will update the same location for different object.

The value in the object is set as 3 in the last iteration of the loop and when retrieving the value after for loop, the value 3 is returned for all the variables.

When you create objects

var a1 = a2 = a3 = {};

all the three variables refer to the same object.

Solution to the problem can be declaring the object individually.





var a1 = {},

a2 = {},

a3 = {};


for (var i = 1; i < 4; i++) {

(function(j) {

console.log(j);

window['a' + j].fu = function() {

console.log('fu:', j);

};

})(i);

}


a1.fu(); // returns "fu:,3" - why not 1?


a2.fu(); // returns "fu:,3" - why not 2?


a3.fu(); // returns "fu:,3"

In a for loop in python 3.x are objects changed to immutable?

Python has no assignment! data = value is strictly a binding operation, not an assignment. This is really different then in eg C++

A Python variable is like a label, or a yellow sticky note: you can put it on something or move it to something else; it does not (never) change the thing (object) it is one.
The =-operator does move the label; it "binds" it. Although we usually say assign, it is really not the assign of C. (Where it is basically is a memory address)

To change a value is Python, you need a method: aLabel.do_update(), will (typically) change self, the object itself.
Note aList[....] is a method!

So, to change you data: change it (sec). Do not put a other label on it, nor put the existing label on other data!

Hope this explains you question

Java - Access variable inside and outside of for-loop

You're close. You need to change the first line to

String playerlist = "";

In Java it's illegal to use a variable before it's initialized, and the line

playerlist += p.getDisplayName() + ", ";

desugars(*) to

String temp = playerlist;
playerlist = temp + (p.getDisplayName() + ", ");

Once you initialize playerlist, you are able to read off its contents into the temporary variable, and then update playerlist.

There are two higher-level suggestions, though.

  1. If you have a join method available, as some libraries provide (as do the the .NET and Python platforms), you can just use a join, which is easier to read.
  2. However, if you don't have a join method available (AFAIK, the Java standard library provides no such thing), you should use a StringBuilder, consistent with @anubhava's suggestion. You'll get better performance on large numbers of strings, and the code is easier to understand, which is a win-win.

EDIT: As @edalorzo rightly mentions in the comments, you will only get an error for not initializing a local variable, and both static and instance fields are automatically initialized. Specifically, numeric types (int, long, double, etc.) are initialized to 0, booleans are initialized to false, and reference types are initialized to null.

The spec explicitly describes the automatic initialization of fields, so you can rely on it, but it's rarely what you want. Normally, you will want a non-default value of the field when you use it later, since null isn't terribly useful (and many languages, particularly functional languages like Standard ML, go without null altogether). So I would recommend initializing all the fields of your objects in the constructor.


(*): The "desugaring" I show above is almost accurate: in truth, playerlist is evaluated only once, which doesn't affect the behavior of this particular program.

Swift for in - get entries as reference

So the basic answer for your original for loop question is: no. The for...in is designed to give you copies of value types. It's a forced-functional programming style as you said yourself in the comments.

To mutate an array you must say array[index] in some fashion or another and now you're referring to the original value and can mutate it. The trick is finding an expressive way that prevents common errors. The four techniques I'm advocating below are:

  1. Make a powerful abstraction as an extension so you DRY throughout the code
  2. Use indices not a manual range which is also error prone (... vs. ..<)
  3. Avoid ugly throwbacks to C-language constructs like & (see #1)
  4. Consider keeping around the mutating version and the non-mutating version

This is probably most in keeping with the spirit of Swift, that is, quirky, verbose, and more nettlesome than you'd want, but ultimately very expressive and powerful with the proper layers in place:

import Foundation
import CoreGraphics

protocol Pointy {
var x: CGFloat { get set }
var y: CGFloat { get set }
func adjustBy(amount: CGFloat) -> CGPoint
mutating func adjustInPlace(amount: CGFloat) -> Void
}

extension CGPoint: Pointy {
func adjustBy(amount: CGFloat) -> CGPoint {
return CGPoint(x: self.x + amount, y: self.y + amount)
}

mutating func adjustInPlace(amount: CGFloat) -> Void {
x += amount
y += amount
}
}

extension Array where Element: Pointy {
func adjustBy(amount: CGFloat) -> Array<Pointy> {
return self.map { $0.adjustBy(amount: amount) }
}

mutating func adjustInPlace(amount: CGFloat) {
for index in self.indices {
// mysterious chunk of type calculus: need "as! Element" -- https://forums.developer.apple.com/thread/62164
self[index].adjustInPlace(amount: amount) // or self[index] = (self[index].adjustBy(amount: amount)) as! Element
}
}
}


// Hide the above in a Util.swift that noone ever sees.

// AND NOW the true power shows
var points = [ CGPoint(x: 3.0, y: 4.0) ]
points.adjustInPlace(amount: 7.5)
points.forEach { print($0) }
// outputs (10.5, 11.5)
let adjustedPoints = points.adjustBy(amount: 7.5) // Original unchanged

Does declaring a variable inside a loop body have any disadvantages?

Conceptually that variable is constructed and destructed on each iteration.

But does it affect performance? Well, you can check your case right here. Delete int on line 7 to switch between the loop-local and function-local variables.

Conclusion: no difference whatsoever. The assembly is the same!

So, just use what makes sense in your code. If you need one object per iteration, make one object per. The optimizer is smarter than you think. If that wasn't enough, you'd come back to it with profiling data and careful tweaking, not broad guidelines.

Use local function variable inside loop

I think you've gotten confused between scope outside of a function and inside of it.

d = 1
def a():
d = 0 # this is a different d from line 1
for x in range(12):
d += 1 # this is the same d as line 3
print(d) # same d as line 3
print(d) # same d as line 1

You probably read about locally scoped variables but have gotten confused. Indenting your line does not create a "new local scope". The only time that happens is within functions.



Related Topics



Leave a reply



Submit