How to make Scala's immutable collections hold immutable objects - scala

I'm evaluating Scala and am having a problem with its immutable collections.
I want to make immutable collections, which are completely immutable, right down through all the contained objects, the objects they reference, ad infinitum.
Is there a simple way to do this?
The code on http://www.finalcog.com/immutable-containers-scala illustrates what I'm trying to achieve, and a nasty work around (ImmutablePoint).
The problem with the workaround is that every time I want to change an object I have to manually make a new copy. I understand that the runtime will have to implement copy-on-write, but can this be made transparent to the developer?
I suppose I'm looking to make Immutable Objects, where methods change the current object state, but all other 'val' (and all immutable container) references to the object retain the 'old' state.

This is not possible out-of-the-box with scala via some specific language construct unless you have followed the idiom that all of your objects are immutable, in which case this behaviour comes for free!
With 2.8, named parameters have made "copy constructors" quite nice to use, from a readability perspective. But you are correct, this works as copy-on-write. The behaviour you are asking for, where the "current" object is the only one mutated goes completely against the way the JVM works, unfortunately (for you)!
Actually the phrase "the current object" makes no sense; really you mean "the current reference"! All other references (outside the current lexical scope) which point to the same object, erm, point to the same object! There is only one object!
Hence it's just not possible for this object to appear to be mutable from the perspective of the current lexical scope but immutable for others

If you're interested in some more general theory on how to handle updates to immutable data structures efficiently,
http://en.wikipedia.org/wiki/Zipper_%28data_structure%29
might prove interesting.

Related

What is the benefit of defining enumerators as a DUT?

The main goal of defining enumerators is to assign a variable to some numbers and their equal strings as I understand.
We can define var a as an enum everywhere in the initializing section of our Program or Function Block like this:
a:(start,stop,operate);
tough I don't know why we can't see that in tabular view but there there is a big question that:
What is the benefit of defining enumerators as a DUT?
There are 3 main benefits for me:
You can use the same enum in multiples function blocks
You can use TO_STRING on enums declared as DUTs (After enabling it with {attribute 'to_string'} Infosys
You can use refactoring on names of each component, which is impossible with local enums
When defining an enum as a DUT it is available everywhere in your code (global scope).
This is helpful in many cases, but in general it is not good programming practice to have a lot of stuff available in the global scope.
Here is a bit elaboration on the topic.
In addition to the above, one benefit is that if you are using an enumeration for something like FB states, you will be able to see the descriptive status name when the program is running (READING, WRITING, WAITING, ERROR, etc.).
You can see it in the variable declarations section, in-line with your code, or in the watch window. You don’t have to remember what status number was defined in your state machine.
This benefit comes with local enumerations or DUT (global) enumerations.
In addition to other good points already made, there is another big advantage to enumerations : you can use the enumeration as the type of a variable, and when you do that, the compiler will (if {attribute 'strict'} is used in the enumeration declaration, which it probably should) refuse an assignment to that variable of a value that is not allowed by the enumeration.
In other words, you get rid of a whole class of failure modes where the variable ends up having an invalid value due to some coding mistake the compiler cannot catch.
It takes a trivial amount of time to create an enumeration, and it has benefits on many levels. I would say the real question is why not use them whenever a fixed list of meaningful values needs to be expressed.

How to check if a variable is val or var programmatically?

In scala, we can define variable like:
val a=10 or var a=10.
Is there anyway we can check if a is a val or var programmatically?
Scala is an object-oriented language. This means, in particular, that you can only manipulate objects.
Variables are not objects in Scala (like pretty much every programming language), therefore there is no way that you could, for example, call a method on a variable to ask it whether it is a var or a val (because you can only call methods on objects, and variables aren't objects), and there is no way to pass a variable to a method to ask the method whether the variable is a val or a var (because you can only pass objects as arguments, and variables aren't objects).
Again, this is not really specific to Scala, this applies to the overwhelming majority of programming languages. Even in programming languages like Ruby with very powerful dynamic meta programming capabilities, variables aren't objects and cannot be reflected upon.
But wait, you might say, classes aren't objects in Scala either, but I can get a runtime representation of a class using scala.Predef.classof[T]! Indeed you can, but there is a fundamental difference between classes and variables: classes are runtime entities, so even if they don't exist as objects, they do at least exist at runtime. Variables are a pure compile time construct, they do not exist at runtime.
So, the only way you can get at a variable at all is using compile-time reflection. Which, very likely, is complete overkill for whatever it is that you want to do.
So, to answer your question:
Is there anyway we can check if a is a val or var programmatically?
Extremely short answer: No.
Very short answer: You shouldn't use var anyway. If you follow that advice, the question becomes moot.
Short answer: If your local variable scopes are so big and convoluted that you cannot even figure out whether a variable is a var or a val you have much bigger problems.
Simple answer: No.
Slightly more elaborate answer: No, not at runtime.
Very complex answer: It is probably possible using Compile-Time Reflection.

Can creating a list in Lisp be called 'change of state'?

For the sake of argument can we say that when we create lists in Lisp, it is a change of state? Now that can be using cons, list or any other list creation functions.
Consider a filter function which filters odd number from list and keeps only even numbers. Now it does that by creating new lists and using recursion. Can we say there is change of state in the program? Assuming we already know interpreter's perspective.
Considering lists are objects and and when old objects are dropped in favour of new objects then it is change of state right?
Also how valid would it be to say that from technical point of view. I mean from Lisp interpreter perspective.
It all comes down to how you define "change of state", or better yet, the thing whose state we are talking about. States are properties of things, so to answer your question, we have to ask "the state of what exactly?"
Let's look at a couple of possible candidates:
In your filtering example, we have a list A. Filter constructs a new list B with only the even numbers.
The state of A is definitely not changed. That's the point of constructing a new list.
The state of B is definitely changed. Prior to the run of filter, it did not exist, now it does.
The state of the runtime environment also contains all the variables and as we added a new symbol with the filtered list, its state has certainly changed.
So, to answer your question: Yes. But keep in mind that state is a property of something and to really answer it correctly, you have to tell us whose state you are interested in.

What are the differences betwen immutable and mutable classes?

i studing about c# and i think that the diference betwen mutable & inmutable class , (un c# for example), are that the definitión of the variables cant change. The string still string, or may be that the value of the types cant change : string = "Hola" still "Hola". and the mutable can change.
well i am right or what is the real diference?
thank you
An immutable object is an object that can't change it's property values after it's created (actually its state, but to simplify, let's just assume that a different state implies different property/variable values). Any properties are usually asigned values in the constructor (it may not have any properties at all, just methods).
An immutable object can have internal variables that might change values, as long as they don't affect the state of that object from a public/external point of view.
A string in C# is immutable... if you try to assign a string variable a different value, a new string is created.
You can find more information about immutability in OOP on the Wikipedia
PS: it's a bit more complicated than this, but I don't want to confuse you... there are different levels of what can be considered "immutable", but if you want to research further, apart from the Wikipedia article (which doesn't mention C#), there's this post by Eric Lippert which explains the different types way better than I could ever do.

MATLAB weak references to handle class objects

While thinking about the possibility of a handle class based ORM in MATLAB, the issue of caching instances came up. I could not immediately think of a way to make weak references or a weak map, though I'm guessing that something could be contrived with event listeners. Any ideas?
More Info
In MATLAB, a handle class (as opposed to a value class) has reference semantics. An example included with MATLAB is the containers.Map class. If you instantiate one and pass it to a function, any modifications the function makes to the object will be visible via the original reference. That is, it works like a Java or Python object reference.
Like Java and Python, MATLAB keeps track in one way or another of how many things are referencing each object of a handle class. When there aren't any more, MATLAB knows it is safe to delete the object.
A weak reference is one that refers to the object but does not count as a reference for purposes of garbage collection. So if the only remaining references to the object are weak, then it can be thrown away. Generally an event or callback can be supplied to the weak reference - when the object is thrown away, the weak references to it will be notified, allowing cleanup code to run.
For instance, a weak value map is like a normal map, except that the values (as opposed to the keys) are implemented as weak references. The weak map class can arrange a callback or event on each of these weak references so that when the referenced object is deleted, the key/value entry in the map is removed, keeping the map nice and tidy.
These special reference types are really a language-level feature, something you need the VM and GC to do. Trying to implement it in user code will likely end in tears, especially if you lean on undocumented behavior. (Sorry to be a stick in the mud.)
There's a couple ways you could do something similar. These are just ideas, not endorsements; I haven't actually done them.
Perhaps instead of caching Matlab object instances per se, you could cache expensive computational results using a real Java weak ref map in the JVM embedded inside Matlab. If you can convert your Matlab values to and from Java relatively quickly, this could be a win. If it's relatively flat numeric data, primitives like double[] or double[][] convert quickly using Matlab's implicit conversion.
Or you could make a regular LRU object cache in the Matlab level (maybe using a containers.Map keyed by hashcodes) that explicitly removes the objects inside it when new ones are added. Either use it directly, or add an onCleanup() behavior to your objects that has them automatically add a copy of themselves to a global "recently deleted objects" LRU cache of fixed size, keyed by an externally meaningful id, and mark the instances in the cache so your onCleanup() method doesn't try to re-add them when they're deleted due to expiration from the cache. Then you could have a factory method or other lookup method "resurrect" instances from the cache instead of constructing brand new ones the expensive way. This sounds like a lot of work, though, and really not idiomatic Matlab.
This is not an answer to your question but just my 2 cents.
Weak reference is a feature of garbage collector. In Java and .NET garbage collector is being called when the pressure on memory is high and is therefore indeterministic.
This MATLAB Digest post says that MATLAB is not using a (indeterministic) garbage collector. In MATLAB references are being deleted from memory (deterministically) on each stack pop i.e. on leaving each function.
Thus I do not think that weak references belongs to the MATLAB reference handling concept. But MATLAB has always had tons of undocumented features so I can not exclude that it is buried somewhere.
In this SO post I asked about MATLAB garbage collector implementation and got no real answer. One MathWorks stuff member instead of answering my question has accused me of trying to construct a Python vs. MATLAB argument. Another MathWorks stuff member wrote something looking reasonable but in substance a clever deception - purposeful distraction from the problem I asked about. And the best answer has been:
if you ask this question then MATLAB
is not the right language for you!