digitalmars.D - Nested struct sauses error
- fantom (71/71) Mar 12 2017 I write simple function to get unique values in array of arrays
- Adam D. Ruppe (7/8) Mar 12 2017 easy fix is to likely make it a `static struct` even if nested.
- Era Scarecrow (4/7) Mar 12 2017 While it's the most likely reason for the error; Shouldn't it
I write simple function to get unique values in array of arrays
with position
import std.stdio;
import std.range;
import std.algorithm;
struct Value {
int var;
size_t index;
bool opEquals()(auto ref const Value rhs) const {
return var==rhs.var;
}
int opCmp(ref const Value rhs) const {
return var-rhs.var;
}
}
auto get_unique(int[][] row) {
auto unique=row.enumerate
.map!(iv=>iv.value.map!(var=>Value(var, iv.index)))
.join
.sort()
.group
.filter!(t=>t[1]==1)
.map!(t=>[t[0].var, t[0].index]);
return unique;
}
void main(){
auto
row=[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]];
get_unique(row).writeln;
}
Output: [[1, 0], [9, 4]]
But when I move Value struct into function, I get compilation
error
import std.stdio;
import std.range;
import std.algorithm;
auto get_unique(int[][] row) {
struct Value {
int var;
size_t index;
bool opEquals()(auto ref const Value rhs) const {
return var==rhs.var;
}
int opCmp(ref const Value rhs) const {
return var-rhs.var;
}
}
auto unique=row.enumerate
.map!(iv=>iv.value.map!(var=>Value(var, iv.index)))
.join
.sort()
.group //here: Error: template instance
std.algorithm.iteration.group!("a == b", SortedRange!(Value[], "a
< b")) error instantiating
.filter!(t=>t[1]==1)
.map!(t=>[t[0].var, t[0].index]);
return unique;
}
void main(){
auto
row=[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]];
get_unique(row).writeln;
}
dmd2/include/std/algorithm/iteration.d(1419): Error: field
_current must be initialized in constructor, because it is nested
struct
app.d(21): Error: template instance
std.algorithm.iteration.group!("a == b", SortedRange!(Value[], "a
< b")) error instantiating
Can anybody explain me what is wrong? Thanks
Mar 12 2017
On Sunday, 12 March 2017 at 18:46:14 UTC, fantom wrote:Can anybody explain me what is wrong? Thankseasy fix is to likely make it a `static struct` even if nested. That will remove access to local variables of the function but should compile. The reason is that access to those local variables needs a hidden pointer that won't be initialized properly without the right construction.
Mar 12 2017
On Sunday, 12 March 2017 at 18:59:43 UTC, Adam D. Ruppe wrote:The reason is that access to those local variables needs a hidden pointer that won't be initialized properly without the right construction.While it's the most likely reason for the error; Shouldn't it detect it never used anything outside and not try to include the hidden pointer?
Mar 12 2017








Era Scarecrow <rtcvb32 yahoo.com>