The peculiar case of disappearing data - d

I am trying following code:
import std.stdio;
import std.range;
void main(){
auto data = [[1,2,3], [4,5,6]]; // putting auto instead of int[][] here makes no difference;
auto coldata = data.transposed;
writeln("coldata: ", coldata); // prints ok;
writeln("transposed data: ", coldata); // Empty list is printed. Data disappears/evaporates!
}
The output is:
$ rdmd evapor.d
coldata: [[1, 4], [2, 5], [3, 6]]
transposed data: []
In the second call, an empty list is printed. The data seems to just disappear/evaporate!
Why the data is not priting on second call?
Edit: Empty list is printed even if I call transpose each time:
writeln("coldata: ", data.transposed); // prints ok;
writeln("transposed data: ", data.transposed); // data disappears / evaporates!
Also, using coldata.dup does not work. I produces following error:
soq_evapor.d(10): Error: template object.dup cannot deduce function from argument types !()(Transposed!(int[][], cast(TransverseOptions)0)), candidates are:
/usr/include/dmd/druntime/import/object.d(3169): object.dup(T : V[K], K, V)(T aa)
/usr/include/dmd/druntime/import/object.d(3206): object.dup(T : V[K], K, V)(T* aa)
/usr/include/dmd/druntime/import/object.d(4482): object.dup(T)(T[] a) if (!is(const(T) : T))
/usr/include/dmd/druntime/import/object.d(4508): object.dup(T)(const(T)[] a) if (is(const(T) : T))
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_evapor.d", "-I."]

The range is being "consumed". If you need to reuse it like you have, you will need to make sure to call save before you use it.
https://forum.dlang.org/post/migwtldccpwryusyolkq#forum.dlang.org
https://forum.dlang.org/post/n2m1jl$2dqf$1#digitalmars.com
You can find more info about this here: https://forum.dlang.org/thread/plsuntcmsezxpjbxkfnz#forum.dlang.org
import std.stdio;
import std.range;
void main(){
auto data = [[1,2,3], [4,5,6]]; // putting auto instead of int[][] here makes no difference;
auto coldata = data.dup();
auto otherData = data.dup();
writeln("coldata: ", coldata.transposed); // prints ok;
writeln("transposed data: ", otherData.transposed); // this also prints ok.
}
is one such way of doing this.
The main reason for doing this is how the API is designed in D. Not all ranges are destructively iterated, it just depends on the kind. In general, though you can.
The D Lang site has this to say:
Most of the ranges in the standard library are structs and so foreach iteration is usually non-destructive, though not guaranteed. If this guarantee is important, an specialization of an InputRange can be used— forward ranges with a .save method:
https://tour.dlang.org/tour/en/basics/ranges

Related

How can I extract values from within a list

Let us say that I have a Map in dart which holds value in this format : String, List<MyModel>. Now the Map would look something like this -
{
'a' : [MyModel1, MyModel2],
'b' : [MyModel3],
'c' : [MyModel4, MyModel5]
}
I want to design a function that would return me this : [MyModel1, MyModel2,......,MyModel5] . I can easily do the same by iterating over values in the map and then use a nested loop to iterate over each value to finally extract each of the elements. However, what I want is a better way to do it (probably without using the two for loops as my Map can get pretty long at times.
Is there a better way to do it ?
You could use a Collection for and the ... spread operator, like this:
void main() {
Map<String, List<int>> sampleData = {
'a': [1, 2],
'b': [3],
'c': [4, 5, 6]
};
final output = mergeMapValues(sampleData);
print(output); // [1, 2, 3, 4, 5, 6]
}
// Merge all Map values into a single list
List<int> mergeMapValues(Map<String, List<int>> sampleData) {
final merged = <int>[for (var value in sampleData.values) ...value]; // Collection for
return merged;
}
Here's the above sample in Dartpad: https://dartpad.dev/?id=5b4d258bdf3f9468abbb43f7929f4b73

remove in print or data Optional() with SQLite.swift

How to remove in print or data Optional() ? (swift3, xcode 8.2.1)
let statement = try connection.prepare("SELECT * FROM persons")
for data in statement
{
print(data)
}
// result print :
[Optional(1), Optional("John"), Optional("Do"), Optional("Pologne")]
thanks a lot every body
If you want to traverse over the optional elements of an collection, you could make use of for case ... in loop, a variation of the for ... in loop. This allows you optionally bind each element passed as a non-optional to the scope of the loop, given that the element is not nil.
E.g.:
let statement: [Any?] = [1, "John", "Doe", "Pologne"]
for case let data? in statement {
print(data)
} /* 1
John
Doe
Pologne */

Sequence of dictionaries in python

I am trying to create a sequence of similar dictionaries to further store them in a tuple. I tried two approaches, using and not using a for loop
Without for loop
dic0 = {'modo': lambda x: x[0]}
dic1 = {'modo': lambda x: x[1]}
lst = []
lst.append(dic0)
lst.append(dic1)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 0 , 1
With a for loop
lst = []
for j in range(0,2):
dic = {}
dic = {'modo': lambda x: x[j]}
lst.insert(j,dic)
tup = tuple(lst)
dic0 = tup[0]
dic1 = tup[1]
f0 = dic0['modo']
f1 = dic1['modo']
x = np.array([0,1])
print (f0(x) , f1(x)) # 1 , 1
I really don't understand why I am getting different results. It seems that the last dictionary I insert overwrite the previous ones, but I don't know why (the append method does not work neither).
Any help would be really welcomed
This is happening due to how scoping works in this case. Try putting j = 0 above the final print statement and you'll see what happens.
Also, you might try
from operator import itemgetter
lst = [{'modo': itemgetter(j)} for j in range(2)]
You have accidentally created what is know as a closure. The lambda functions in your second (loop-based) example include a reference to a variable j. That variable is actually the loop variable used to iterate your loop. So the lambda call actually produces code with a reference to "some variable named 'j' that I didn't define, but it's around here somewhere."
This is called "closing over" or "enclosing" the variable j, because even when the loop is finished, there will be this lambda function you wrote that references the variable j. And so it will never get garbage-collected until you release the references to the lambda function(s).
You get the same value (1, 1) printed because j stops iterating over the range(0,2) with j=1, and nothing changes that. So when your lambda functions ask for x[j], they're asking for the present value of j, then getting the present value of x[j]. In both functions, the present value of j is 1.
You could work around this by creating a make_lambda function that takes an index number as a parameter. Or you could do what #DavisYoshida suggested, and use someone else's code to create the appropriate closure for you.

Ordered lua table looping using C API

Consider the following lua table:
foo = {
bar1 = {a = 1, b = 2, c = "hello"},
bar2 = {a = 5, b = 2, c = "bbq"},
bar3 = {a = 76, b = 13, c = "pwnd"}
}
I am trying to iterate this table using the lua C API to retrieve the key names, bar1, bar2 and bar3. I used the lua_next(L, -2) function to iterate as suggested by many, but the problem is that it returns the elements in random order. The order changes on each run.
I use the following code:
for( lua_pushnil(L); lua_next(L, -2) != 0; lua_pop(L, 1) )
{
printf("%s\n", lua_tostring(L, -2));
}
Most of the time, the output is unordered, such as bar2 bar1 bar3. When lucky, it's ordered. Is there an easy way to loop the table keys in an ordered fashion? What would be the equivalent code as I use, but ordered? Thanks!
Edit:
I know I am using a map rather than an array. But in lua script we have ipairs which would work just fine for this case. I'm looking at the C API equivalent. I've found this stackoverflow answer which gives a different answer, but it doesn't work for me, so I wonder if that answer is good or relevant.
No. The order that Lua traverses tables is undefined.
If you know that the keys are of the form barXXX, then you can create these keys as strings dynamically in the order you wish and then get the corresponding value from the table.
Put the names in a C array, and then order them in C.
As others are saying, the order of keys returned by the hash portion of a table is not guaranteed.
Alternatively, use an array-like structure so you can use the array part:
foo = {
{name = 'bar1', a = 1, b = 2, c = "hello"},
{name = 'bar2', a = 5, b = 2, c = "bbq"},
{name = 'bar3', a = 76, b = 13, c = "pwnd"}
}
So you can use ipairs or the equivalent to for i=1,#foo to iterate over the items in order.
Checking Lua's documentation, the main structure that Lua supports is a Hash Table. Given that it's always going to be a hash-table, you'd probably want to reimplement foo as an array. The bar1, bar2, etc can be part of the entry into the array like so:
foo = {}
foo[0] = {name='bar1', ...}
foo[1] = {name='bar2', ...}
...
or as #lhf suggested, just build the bar names inside a for-loop (if you know it's in sequence) and retrieve the values from foo table.

merge 2 lists A over B in scala

I have 2 immutable case classes A(source, key, value) and B(source, key, value)
I want to add A over B in such a way when 'source' and 'key' doesn't exist, to be added from A to the B and when 'source' and 'key' exist to replace the value from B with the one from A. The same way 'merge_array' function from php works on a multidimensional array.
I tried with 'A.union(B).groupBy(.key)' and then 'groupBy(.source)' and get the 1st value. But then I realized that I can never be sure that first value will always be the value of A.
I'm quite new to scala and I really ran out of ideas how I could do this from a functional immutable point of view.
Anyone has any idea how I could do this?
Thank you
Edit:
case class TranslationValue(source: String, key: String, value: String)
def main(args:Array[String]):Unit = {
println(merge(data1.toSet, data2.toSet))
}
def merge(a: Set[TranslationValue], b: Set[TranslationValue]) = {
a.union(b).groupBy(_.key).flatMap{ case (s, v) =>
v.groupBy(_.source).flatMap{case (s1, v1) => {
for (res <- 0 to 0) yield v1.head
}
}
}
}
Example
data1 has this data
Set(
TranslationValue(messages,No,No),
TranslationValue(messages,OrdRef,Order Reference),
TranslationValue(messages,OrdId,Order Id)
)
data2 has this data
Set(
TranslationValue(messages,No,No),
TranslationValue(messages,OrdRef,OrderRef)
TranslationValue(messages,Name,Name)
)
putting data1 over data2 I want to obtain
List(
TranslationValue(messages,No,No),
TranslationValue(messages,OrdRef,Order Reference),
TranslationValue(messages,OrdId,Order Id)
TranslationValue(messages,Name,Name)
)
I know that what I do can be done better, but like I said, I'm learning :)
you can group in one go:
def merge(a: Seq[TranslationValue], b: Seq[TranslationValue]) = {
a.union(b).groupBy(t=>(t.key,t.source)).map(c=>c._2.head)
}
i think you could also override the equals method for TranslationValue so that two translation values are equal when source and key are the same(the hashcode method has also to be overridden). Then a.union(b) would be enough.
edit:
It seems Set doesnt guarantee order of items(Scala: Can I rely on the order of items in a Set?), but a seq should.