Updating an immutable sequence - ceylon

I have a sequence in Ceylon and I want to make a new sequence with one of the elements replaced with something else according an index:
[String*] strings = ["zero", "one", "two"];
value index = 1;
value newElement= "uno";
[String*]? newStrings = ???; // should be ["zero", "uno", "two"]
In Scala, this is called update.

There are several ways to solve this problem, and I do like the solution by Quintesse above, using Array. That is, perhaps, what I would do in practice. However, there is one possibly-important downside of the Array solution: it allocates memory twice.
So let me just suggest a couple of different options, for the sake of completeness:
Using stream operations
This works, but is a bit verbose:
[String*] strings = ["zero", "one", "two"];
value index = 1;
value newElement= "uno";
[String*] newStrings =
strings.take(index)
.chain(strings.skip(index+1).follow(newElement))
.sequence();
Note that here we are using the lazy stream operations take(), skip(), chain() and follow() to create a lazy stream of elements, and then the sequence() operation to take a copy into a new sequence. It allocates just once, in the call to sequence().
Using patch()
This also works:
[String*] strings = ["zero", "one", "two"];
value index = 1;
value newElement= "uno";
[String*] newStrings =
strings.patch([newElement], index, 1)
.sequence();
Note that if it's good enough to get back an immutable List, you could drop the call to sequence(), resulting in:
[String*] strings = ["zero", "one", "two"];
value index = 1;
value newElement= "uno";
[String*] newStrings =
strings.patch([newElement], index, 1);
And in this case there's no allocation at all (except for one trivial instance of List.Patch).
See the docs for List.patch().

You could do it with a comprehension:
[String*] newStrings = [for (i->e in strings.indexed) i==index then newElement else e];
Try online

Another way would be to copy it to an Array, which is mutable, and then back:
[String*] strings = ["zero", "one", "two"];
value index = 1;
value newElement= "uno";
value array = Array(strings);
array.set(index, newElement);
[String*] newStrings = array.sequence();

Related

Can I use a value stored in a table as a key in another table?

I'm new to LUA and I still haven't gotten the hang of how classes work in LUA, so my question
probably has a very simple answer. I'm trying to make a function that takes a CSV file and turns it into a lua table.
The input file would be something like this
PropertyKey1,Propertykey2,Propertykey3
object1property1,object1property2,object1property3
object2property1,object2property2,object2property3
object3property1,object3property2,object3property3
and I want the resulting lua table to look something like this
objects = {
{
PropertyKey1 = object1property1
PropertyKey2 = object1property2
PropertyKey3 = object1property3
}
{
PropertyKey1 = object2property1
PropertyKey2 = object2property2
PropertyKey3 = object2property3
}
{
PropertyKey1 = object3property1
PropertyKey2 = object3property2
PropertyKey3 = object3property3
}
}
this is what I have thus far
function loadcsv(path)
local OutTable = {}
local file = io.open(path, "r")
local linecount = 0
for line in file:lines() do
local data = {}
local headers = {}
local headerkey = 1
if linecount < 1 then
for val in line:gmatch("([^,]+),?") do
table.insert(headers, val)
end
else
for word in line:gmatch("([^,]+),?") do
key = headers[headerkey]
data[headerkey] = word
headerkey = headerkey + 1
table.insert(OutTable, data)
end
end
linecount = linecount + 1
end
file:close()
return OutTable
end
The above code does not run. When I try to print any of the values, they come as nil.
The problem is this bit
key = headers[headerkey]
data[headerkey] = word
I wanted to use the values I stored in one table as keys on the second table, but it looks like since LUA only passes the references, that doesn't work.
I did a quick experiment to confirm it. I first set up 2 tables.
test = {}
test2 = {}
test[1]={"index"}
key = test[1]
key2 = "index"
First I tried assigning the value directly form the table
test2[test[1]] = "text"
print(test2.index) --This did not work
then I tried going trough another variable
test2[key] = "texto"
print(test2.index) --This did not work
I even tried using tostring()
key = tostring(test[1])
test2[key] = "texto"
print(test2.index) --This did not work
I wrote the string directly in the variable "key2" to confirm that I was using the right notation.
test2[key2] = "text"
print(test2.index) --This one worked
I read a bit on metatables, but I'm not fully clear on those. Would that be the simplest way to do what I'm trying to do, or is my approach flawed in some other way?
key = headers[headerkey]
key is not used so why assign a value to it?
data[headerkey] = word
headerkey is a numeric key. You start at 1 for each line and add 1 for each word in a line. So you end up with
data = {
[1] = "object1property1",
[2] = "object1property2",
[3] = "object1property3"
}
Instead of the intended
data = {
PropertyKey1 = "object1property1",
PropertyKey2 = "object1property2",
PropertyKey3 = "object1property3"
}
So you probably meant to write
local key = headers[headerkey]
data[key] = word
But you have to move headers out of the loop. Otherwise you'll end up with an empty table for line 1 resulting in key being nil which would cause Lua errors for using a nil table index.
The following line is called for every word
table.insert(OutTable, data)
You need to do this for every line!
Your code basically produces this output:
local tableA = {"object1property1", "object1property2", "object1property3"}
local tableB = {"object2property1", "object2property2", "object2property3"}
local tableC = {"object3property1", "object3property2", "object3property3"}
OutTable = {
tableA, tableA, tableA, tableB, tableB, tableB, tableC, tableC, tableC
}
I suggest you formulate your program in your first language and then translate it into Lua. This helps to avoid such errors.
Your problem is not related to metatables, classes or anything else mentioned. You simply used the wrong variable and messed up your inner loop.

Initialising Sequential values with for loop?

Is there any way to initialize a Sequential value not in one fellow swoop?
Like, can I declare it, then use a for loop to populate it, step by step?
As this could all happen inside a class body, the true immutability of the Sequential value could then kick in once the class instance construction phase has been completed.
Example:
Sequential<String> strSeq;
for (i in span(0,10)) {
strSeq[i] = "hello";
}
This code doesn't work, as I get this error:
Error:(12, 9) ceylon: illegal receiving type for index expression:
'Sequential' is not a subtype of 'KeyedCorrespondenceMutator' or
'IndexedCorrespondenceMutator'
So what I can conclude is that sequences must be assigned in one statement, right?
Yes, several language guarantees hinge on the immutability of sequential objects, so that immutability must be guaranteed by the language – it can’t just trust you that you won’t mutate it after the initialization is done :)
Typically, what you do in this situation is construct some sort of collection (e. g. an ArrayList from ceylon.collection), mutate it however you want, and then take its .sequence() when you’re done.
Your specific case can also be written as a comprehension in a sequential literal:
String[] strSeq = [for (i in 0..10) "hello"];
The square brackets used to create a sequence literal accept not only a comma-separated list of values, but also a for-comprehension:
String[] strSeq = [for (i in 0..10) "hello"];
You can also do both at the same time, as long as the for-comprehension comes last:
String[] strSeq = ["hello", "hello", for (i in 0..8) "hello"];
In this specific case, you could also do this:
String[] strSeq = ["hello"].repeat(11);
You can also get a sequence of sequences via nesting:
String[][] strSeqSeq = [for (i in 0..2) [for (j in 0..2) "hello"]];
And you can do the cartesian product (notice that the nested for-comprehension here isn't in square brackets):
[Integer, Character][] pairs = [for (i in 0..2) for (j in "abc") [i, j]];
Foo[] is an abbreviation for Sequential<Foo>, and x..y translates to span(x, y).
If you know upfront the size of the sequence you want to create, then a very efficient way is to use an Array:
value array = Array.ofSize(11, "");
for (i in 0:11) {
array[i] = "hello";
}
String[] strSeq = array.sequence();
On the other hand, if you don't know the size upfront, then, as described by Lucas, you need to use either:
a comprehension, or
some sort of growable array, like ArrayList.

Couchbase rereduce questions

Here is coding from Couchbase Document and I dont understand it
function(key, values, rereduce) {
var result = {total: 0, count: 0};
for(i=0; i < values.length; i++) {
if(rereduce) {
result.total = result.total + values[i].total;
result.count = result.count + values[i].count;
} else {
result.total = sum(values);
result.count = values.length;
}
}
return(result);
}
rereduce means the current function call has already done the reduce or not. right?
the first argument of the reduce function, key, when will it be used? I saw a numbers of examples, key seems to be unused
When does rereduce return true and the array size is more than 1?
Again, When does rereduce return is false and the array size is more than 1?
Rereduce means that the reduce function is called before and now it is called again with params that were returnd as a result in first reduce call. So if we devide it into two functions it will look like:
function reduce(k,v){
// ... doing something with map results
// instead of returning result we must call rereduce function)
rereduce(null, result)
}
function rereduce(k,v){
// do something with first reduce result
}
In most cases rereduce will happen when you have 2 or more servers in cluster or you have a lot of items in your database and the calculation is done on multiple "nodes" of the B*Tree. Example with 2 servers will be easier to understand:
Let's imagine that your map function returned pairs: [key1-1, key2-2, key6-6] from 1st server and [key5-5,key7-7] from 2nd. You'll get 2 reduce function calls with:
reduce([key1,key2,key6],[1,2,6],false) and reduce([key5,key7],[5,7],false). Then if we just return values (do nothing in reduce, just return values), the reduce function will be called with such params: reduce(null, [[1,2,6],[5,7]], true). Here values will be an array of results that came from first reduce calls.
On rereduce key will be null. Values will be an array of values as returned by a previous reduce() function.
Array size depends only on your data. It not depends on rereduce variable. Same answer for 4th question.
You can just try to run examples from Views basics and Views with reduce. I.e. you can modify reduce function to see what it returns on each step:
function reduce(k,v,r){
if (!r){
// let reduce function return only one value:
return 1;
} else {
// and lets see what values have came in "rereduce"
return v;
}
}
I am also confused by the example from the official couchbase website as well, and below is what i thought.
confusion: the reduce method signature
1) its written as
function (keys, values, rereduce)
2) its written as function(key, values, rereduce)
What exactly is the first param, key or keys
For all my understand from my previous exp on the map/reduce, the key the key that emit from the map function and there is a hidden shuffle method that will aggregate the value into a value list for the same key.
So the key param can be an array under the circumstances that you emit an array as key (which you can use group by level control the level of aggregation)
So i am not agree with the example that given by #m03geek, it should not be a list of different keys, correct me if i am wrong.
My assumption:
Both reduce and rereduce work on the SAME key only.
eg:
reduce is like:
1)reduce(keyA, [1,2,3]) this is precalculated, and stored in Btree structure
2) rereduce(keyA, [6, reduce(keyA, [4,5,6])]), 6 is the sum of [1,2,3] from the first reduce method, then we add a new doc into couchbase, which will trigger the reduce method again, instead of calculating the whole thing again as the original map/reduce will do, couchbase get the precalculated data out from the btree which is 6, and run reduce from the key-value pairs from the map method (which is triggered by adding a new doc), then run re-reduce on the precalculated value + new value.

as3 dictionary of arrays

My code:
var dict = new Dictionary();
dict[[1, 2]] = 1;
var dbg = dict[[1, 2]];
trace(dbg);
Output:
undefined
Why?
How can I get
set<pair<int, int> >
from C++?
Note: I would not call [1,2] "pair of int", it is "array with 2 elements". { item1:1, item2:2 } would look more like pair to me.
According to documentation Dictionary uses strict equals (===) to compare keys, so passing new array as key every time will not work for indexing (arrays are strictly equal only when it is exactly the same array, not an array with the same content).
Depending on your needs converting key to a string maybe good option:
var keyPair = [1,2];
var key = keyPair[0] + "_" + keyPair[1];

ActionScript: Is there ever a good reason to use 'as' casting?

From what I understand of ActionScript, there are two kinds of casts:
var bar0:Bar = someObj as Bar; // "as" casting
var bar1:Bar = Bar(someObj); // "class name" casting (for want of a better name)
Also, and please correct me if I'm wrong here, as casting will either return an instance of the class or null, while "class name" casting will either return an instance of the class or raise an exception if the cast is impossible – other than this, they are identical.
Given this, though, as casting seems to be a massive violation of the fail-fast-fail-early principle... And I'm having trouble imagining a situation where it would be preferable to use an as cast rather than a class name cast (with, possibly, an instanceof thrown in there).
So, my question is: under what circumstances would it be preferable to use as casting?
There are a couple of points in this discussion worth noting.
There is a major difference in how the two work, Class() will attempt to cast the object to the specified Class, but on failure to do so will (sometimes, depends on datatype) throw a runtime error. On the other hand using object as Class will preform a type check first, and if the specified object cannot be cast to the indicated Class a null value is returned instead.
This is a very important difference, and is a useful tool in development. It allows us to do the following:
var o:MyClass = myArray[i] as MyClass;
if(o)
{
//do stuff
}
I think the usefulness of that is pretty obvious.
"as" is also more consistent with the rest of the language (ie: "myObject is MyClass").
The MyClass() method has additional benefits when working with simple data types (int, Number, uint, string) Some examples of this are:
var s:String = "89567";
var s2:String = "89 cat";
var n:Number = 1.9897;
var i:int = int(s); // i is = 89567, cast works
var i2:int = int(s2); //Can't convert so i2 is set to 0
var i3:int = int(n); // i = 1
var n2:Number = Number(s2); // fails, n2 = NaN
//when used in equations you'll get very different results
var result:int = int(n) * 10; //result is 10
var result:int = n * 10; //result is 19.89700
var result:int = int(s2) * 10; //result is 0
trace(s2 as Number); //outputs null
trace(s2 as int); //outputs null
trace(Number(s2)); //outputs NaN
This is a good and important topic, as a general rule I use "as" when working with Objects and Cast() when using simpler data types, but that's just how I like to structure my code.
You need to use as to cast in two scenarios: casting to a Date, and casting to an Array.
For dates, a call to Date(xxx) behaves the same as new Date().toString().
For arrays, a call to Array(xxx) will create an Array with one element: xxx.
The Class() casting method has been shown to be faster than as casting, so it may be preferable to as when efficiency matters (and when not working with Dates and Arrays).
import flash.utils.*;
var d = Date( 1 );
trace( "'" + d, "'is type of: ",getQualifiedClassName( d ) );
var a:Array = Array( d );
trace( "'" + a, "' is type of: ", getQualifiedClassName( a ) );
//OUTPUT
//'Mon Jun 15 12:12:14 GMT-0400 2009 'is type of: String
//'Mon Jun 15 12:12:14 GMT-0400 2009 ' is type of: Array
//COMPILER ERRORS/WARNINGS:
//Warning: 3575: Date(x) behaves the same as new Date().toString().
//To cast a value to type Date use "x as Date" instead of Date(x).
//Warning: 1112: Array(x) behaves the same as new Array(x).
//To cast a value to type Array use the expression x as Array instead of Array(x).
`
They actually do different things...when you say
myvar as ClassName
You are really just letting the compiler know that this object is either a ClassName or a subclass of ClassName
when you say:
ClassName(myvar)
It actually tries to convert it to that type of object.
so if your object is a or a descent of the class and you do not need to convert it you would use as
examples:
var myvar:String = '<data/>';
var othervar:XML = XML(myvar); //right
var myvar:String = '<data/>';
var othervar:XML = (myvar as XML); //wrong
var myvar:XML = <data/>;
var othervar:XML = myvar as XML; // right
Use 'as' with arrays.
var badArray:Array;
badArray = Array(obj);
Will yield an array of length one with the original array in the first element. If you use 'as' as follows, you get the exptected result.
var goodArray:Array;
goodArray = obj as Array;
Generally, 'as' is preferable to 'Class()' in ActionScript as it behaves more like casting in other languages.
I use it when I have an ArrayCollection of objects and need to enumerate through them, or use a selector function.
e.g.
var abc:mytype = mycollection.getItemAt(i) as mytype