Mutable reference to immutable data - scala

I often time hear the term "Mutable reference to immutable data". In my case this was for Scala.
If you have a mutable reference, wouldn't this imply that the immutable data is mutable? I am having hard time understanding the theory and practical aspect of it. Example would be great.

It means you can mutate the reference (change what it refers to) but not mutate the data (change what's behind the reference). The difference matters as soon as there are multiple references to the data, which happens all the time in a language like Scala (assignment, parameter passing, adding to collections, etc.). For example:
var x = List(1);
var y = x;
x = List(2);
// y.head == 1
// x.head == 2
Note that this distinction applies even to Java:
String x = "foo";
String y = x;
x = "bar";
// y.equals("foo")
// x.equals("bar")
Note that in both examples, we mutated the references x and y, but we didn't (and in fact couldn't) mutate the objects they refer to.

Related

What is the difference between constant variable which is type of list and constant list

This is a basic question, but can't find elsewhere.
In dart we can declare a constant variable as
const foo = [1,2,3];
or
var foo = const [1,2,3];
Is there any performance related change if we use either any one.
When you do
const foo = [1, 2, 3];
It means foo will always be equal to [1, 2, 3] independently of the previously executed code and won't change its value later.
When you do
var foo = const [1, 2, 3];
It means that you are declaring a variable foo (and not a constant) which equals at this moment to the constant [1, 2, 3] (it is not dependant on the previously executed code). But the value foo can change and you could do later:
foo = const [1, 2];
which will be legit since foo is a variable. You couldn't do that with foo as a constant (since it is constant)
Therefore, it is better when you can to write
const foo = [1, 2, 3];
because it indicates to the compiler that foo will never change its value.
If constants are called literals and literals are data represented directly in the code, how can constants be considered as literals?
The article from which you drew the quote is defining the word "constant" to be a synonym of "literal". The latter is the C++ standard's term for what it is describing. The former is what the C standard uses for the same concept.
I mean variables preceded with the const keyword are constants, but they are not literals, so how can you say that constants are literals?
And there you are providing an alternative definition for the term "constant", which, you are right, is inconsistent with the other. That's all. TP is using a different definition of the term than the one you are used to.
In truth, although the noun usage of "constant" appears in a couple of places in the C++ standard outside the defined term "null pointer constant", apparently with the meaning you propose here, I do not find an actual definition of that term, and especially not one matching yours. In truth, your definition is less plausible than TutorialPoint's, because an expression having const-qualified type can nevertheless designate an object that is modifiable (via a different expression).
const int MEANING = 42;
the value MEANING is a constant, 42 is a literal. There is no real relationship between the two terms, as can be seen here:
int n = 42;
where n is not a constant, but 42 is still a literal.
The major difference is that a constant may have an address in memory (if you write some code that needs such an address), whereas a literal never has an address.

Are Scala closures as flexible as C++ lambdas?

I know the question seems a bit heretical. Indeed, having much appreciated lambdas in C++11, I was quite thrilled to learn a language which was built to support them from the beginning rather than as a contrived addition.
However, I cannot figure out how to do with Scala all I can do with C++11 lambdas.
Suppose I want to make a function which adds to a number passed as a parameter some value contained in a variable a. In C++, I can do both
int a = 5;
auto lambdaVal = [ a](int par) { return par + a; };
auto lambdaRef = [&a](int par) { return par + a; };
Now, if I change a, the second version will change its behavior; but the first will keep adding 5.
In Scala, if I do this
var a = 5
val lambdaOnly = (par:Int) => par + a
I essentially get the lambdaRef model: changing a will immediately change what the function does.
(which seems somewhat specious to me given that this time a isn't even mentioned in the declaration of the lambda, only in its code. But let it be)
Am I missing the way to obtain lambdaVal? Or do I have to first copy a to a val to be free to modify it afterwards without side effects?
The a in the function definition refers the variable a. If you want to use the current value of a when the lambda has been created, you have to copy the value like this:
val lambdaConst = {
val aNow = a
(par:Int) => par + aNow
}

Does Swift have quadratic string concatenation when using var?

In the Swift Language Reference, under String Mutability it says:
You indicate whether a particular String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), or to a constant (in which case it cannot be modified)
It's unclear to me if the "it" that is mutable is the variable or the value.
For example, if I write:
var s = ""
for i in 0...100 {
s += "a"
}
Is it akin to creating an NSMutableString and calling appendString 100 times (i.e. linear cost)?
Or is it akin to creating a series of ever-larger NSString instances and combining them with stringByAppendingString (i.e. quadratic cost)?
Or perhaps it creates some kind of rope structure behind the scenes, so it's immutable and linear in aggregate?
Appending to a collection like this (while String is not itself a collection, you're essentially appending to its characters view with that code) is linear, not quadratic. A string in Swift has an internal buffer whose size is doubled whenever it fills up, which means you will see fewer and fewer reallocations as you repeatedly append. The documentation describes appending in this way as an "amortized" O(1) operation: most of the time appending is O(1), but occasionally it will need to reallocate the string's storage.
Arrays, sets, and dictionaries have the same behavior, although you can also reserve a specific capacity for an array (using reserveCapacity(_:)) if you know you'll be appending many times.
All these collections use "copy-on-write" to guarantee value semantics. Here, x and y share a buffer:
let x = "a"
let y = x
If you mutate x, it gets a new, unique copy of the buffer:
x += "b"
// x == "ab"
// y == "a"
After that, x has its own buffer, so subsequent mutations won't require a copy.
x += "c" // no copy unless buffer is full

scala assignment of value vs. reference types

I thought I had a firm grasp of Scala's treatment of reference types (i.e., those derived from AnyRef), but now I am not so sure.
If I create a simple class like this
class C(var x: Int = 0) {}
and define a few instances
var a = new C
var b = new C(1)
var c = new C(2)
and then I assign
a = b
I do not get a (shallow) copy, but rather the original reference to the instance to a is lost forever, and a and b are essentially "aliases" for the same object. (This can be seen by looking at the addresses of these items.) This is fine and sensible. It is also clear that these are references (as opposed to values), since I can do
c = null
and this does not generate an error.
Now, suppose I do this
import scala.math.BigInt
var x = BigInt("12345678987654321")
var y = BigInt("98765432123456789")
var z = x + y
This creates three BigInts, with x, y and z, as, I suppose, references to these. In fact, I can do
z = null
and again get no error. However,
y = x
x += 1
does not cause y to change, i.e., it appears that in this case assignment did not simply create another "name" for the object referred to by x, but made a copy of it.
Why does this happen? I cannot find any mechanism (e.g., akin to the "copy constructor" of C++) that would be silently invoked by (what appears to be) straightforward reference assignment.
Any explanation would be greatly appreciated, as two days of web search has proved fruitless.
x += 1 will be expanded into x = x + 1 so it's not only assignment.
If you will look at the source of bigInt you'll see that + creates new instance:
def + (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
in fact it uses java's BigInteger underneath whose add operations leaves both arguments untouched.
So what basically happens at the end of the day is reference reassignment of result of copy constructor of immutable addition
y = x
x += 1
BigInt is immutable so +1 creates new BigInt that's why y does not change. y still points to previous object while x points to new BigInt object.
I suppose its related to the immutability of BigInt and similar classes, you always get a new immutable object.

F#: How do I declare and use ByRef semantics on parameters?

I am wraping some SQL Stored Procs with in/out parameters. This of course means I have to do ugly stuff like declare my parameters as by reference and use mutables.
How would I do this in F#?
F# does indeed have a byref parameter. Here's an example from the MSDN page:
type Incrementor(z) =
member this.Increment(i : int byref) =
i <- i + z
Mutable variables also exist (though there's an important difference between using ref and mutable variables, either of which can be used for many of the same purposes). The MSDN page on this subject is very informative - including a discussion of when to use which keyword/construct.
Example of reference variables:
// Declare a reference.
let refVar = ref 6
// Change the value referred to by the reference.
refVar := 50
Example of mutable variables:
// Declare a reference.
let mutable refVar = 6
// Change the value referred to by the reference.
refVar <- 50
As you can see, the syntax for assignment (as well as retrieval) differs between the two constructs, too.