Re: Conway's game of life
Uf... you are right! I've fixed it. Thanks! On Monday, 2 February 2015 at 11:23:17 UTC, FG wrote: Bloody Thunderbird has sent a reply to the OP and not to the NG. On 2015-02-02 at 11:45, gedaiu wrote: I don't think that the line of code is wrong. If use && the function will check for neighbours only on diagonals. Having || allows the search on the vertical and horizontal axis and diagonals. In short: Yes, && alone would check only diagonals, but I forgot to tell you to also change the ==. (diff1 == 1 || diff2 == 1) -- bad, accepts whole neighbouring rows and columns (diff1 == 1 && diff2 == 1) -- bad, accepts only neighbouring diagonals (diff1 <= 1 && diff2 <= 1) -- correct, I think :) This unittest should show the difference: unittest { CellList world = [ Cell(0,0), Cell(0,1), Cell(0,2), Cell(0,3) ]; assertEqual(Cell(1,1).neighbours(world), 3); } Cell(0,3) is not a neighbour bit fits the (diff1 == 1 || diff2 == 1) criterion.
Re: Conway's game of life
I don't think that the line of code is wrong. If use && the function will check for neighbours only on diagonals. Having || allows the search on the vertical and horizontal axis and diagonals. There are some tests that check the function: unittest { CellList world = [ Cell(0,0), Cell(0,1), Cell(0,2), Cell(1,0), Cell(1,2), Cell(2,0), Cell(2,1), Cell(2,2) ]; assertEqual(Cell(1,1).neighbours(world), world.length); } unittest { CellList world = [ Cell(0,0), Cell(1,1), Cell(2,2), Cell(3,3) ]; assertEqual(Cell(1,1).neighbours(world), 2); } I don't see a glitch. Thanks, Bogdan On Sunday, 1 February 2015 at 22:51:42 UTC, FG wrote: On 2015-02-01 at 22:00, gedaiu wrote: I implemented Conway's game of life in D. I think you are playing a different game here. /// Count cell neighbours long neighbours(Cell myCell, CellList list) { long cnt; foreach(cell; list) { auto diff1 = abs(myCell.x - cell.x); auto diff2 = abs(myCell.y - cell.y); if(diff1 == 1 || diff2 == 1) cnt++; // Why || instead of && ??? } return cnt; }
Re: Conway's game of life
It's true that I have to change that function. Thanks for the notice! Why do you think that D's GC is crap? On Sunday, 1 February 2015 at 21:54:43 UTC, Foo wrote: On Sunday, 1 February 2015 at 21:00:07 UTC, gedaiu wrote: Hi, I implemented Conway's game of life in D. What do you think that I can improve to this program to take advantage of more D features? https://github.com/gedaiu/Game-Of-Life-D Thanks, Bogdan For each remove you create a new array. That is lavish. You should use a bool inside the struct Cell. If it's false, the cell is not displayed and is out of the game. My suggestion: don't use the D GC, it's crap. Try to circumvent the GC wherever possible. Therefore you should use the -vgc compiler flag and the @nogc attribute.
Conway's game of life
Hi, I implemented Conway's game of life in D. What do you think that I can improve to this program to take advantage of more D features? https://github.com/gedaiu/Game-Of-Life-D Thanks, Bogdan
Re: template bug?
On Wednesday, 3 December 2014 at 18:25:41 UTC, bearophile wrote: Ali Çehreli: Attempting to compile with a recent dmd git head causes segmentation fault. Any compiler crash is a compiler bug. Please report it at https://issues.dlang.org/ Ali A first reduction for Bugzilla: alias TypeTuple(T...) = T; struct A { void foo() {} } template ItemProperty(item, string method) { static if(__traits(getProtection, ItemProperty!(item, method)).stringof) alias ItemProperty = TypeTuple!(ItemProperty!(item, method)); } void main() { auto l = ItemProperty!(A, "foo").length; } Bye, bearophile Thanks for the code revised version. I thought that the compiler crashes because I was trying to get the access of an overrided method. Bogdan
template bug?
Hi, Is this a bug in the compiler? import std.stdio; import std.typetuple; class A { int foo() { return 0; } } class B : A { alias A.foo foo; override int foo() { return 1; } } template ItemProperty(item, string method) { static if(__traits(hasMember, item, method)) { static if(__traits(getProtection, ItemProperty!(item, method)).stringof[1..$-1] == "public") { alias ItemProperty = TypeTuple!(ItemProperty!(item, method)); } else { alias ItemProperty = TypeTuple!(); } } else { alias ItemProperty = TypeTuple!(); } } void test()() { static if(ItemProperty!(B, "foo").length > 1) { writeln("found"); } else { writeln("not found"); } } void main() { test; }
Re: find all public properties at compile time
[sorry... this is the edit for the prev post] Thank you for your response! I don't think that it helps me... I wanted to get an array like this [ "a", "b", "c" ] for this class class test { int a; string b; double c; } Bogdan On Tuesday, 30 September 2014 at 14:20:04 UTC, Rene Zwanenburg wrote: On Monday, 29 September 2014 at 20:21:43 UTC, gedaiu wrote: Hi, There is a way to determine all public properties (not methods) from a struct/class at compile time? I seen that there are traits to get only methods but not properties. Am I wrong? thanks, Bogdan You can get the function attributes of the returned methods using std.traits: http://dlang.org/library/std/traits/functionAttributes.html http://dlang.org/library/std/traits/FunctionAttribute.html Vibe's serializer is also a good place to look. The code is a bit intimidating but it's handling a ton of corner cases: https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/data/serialization.d#L710
Re: find all public properties at compile time
Thank you for your response! I don't think that it helps me... I wanted to get an array like this [ "a", "b", "c" ] for this class class test { } Bogdan On Tuesday, 30 September 2014 at 14:20:04 UTC, Rene Zwanenburg wrote: On Monday, 29 September 2014 at 20:21:43 UTC, gedaiu wrote: Hi, There is a way to determine all public properties (not methods) from a struct/class at compile time? I seen that there are traits to get only methods but not properties. Am I wrong? thanks, Bogdan You can get the function attributes of the returned methods using std.traits: http://dlang.org/library/std/traits/functionAttributes.html http://dlang.org/library/std/traits/FunctionAttribute.html Vibe's serializer is also a good place to look. The code is a bit intimidating but it's handling a ton of corner cases: https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/data/serialization.d#L710
find all public properties at compile time
Hi, There is a way to determine all public properties (not methods) from a struct/class at compile time? I seen that there are traits to get only methods but not properties. Am I wrong? thanks, Bogdan
using regex at compiletime
Hi, I am trying to use regex at compile time for pasing of some html files. The code works perfect at runtime but at compile time i get this error: /usr/include/dmd/phobos/std/regex.d(5824): Error: malloc cannot be interpreted at compile time, because it has no available source code /usr/include/dmd/phobos/std/regex.d(5824):called from here: enforce(malloc(size), delegate const(char)[]() => null, "/usr/include/dmd/phobos/std/regex.d", 5824LU) /usr/include/dmd/phobos/std/regex.d(5961):called from here: matchOnce(input, re) source/cthtml.d(121):called from here: matchFirst(text, rTag) source/cthtml.d(397):called from here: structure.this(content, "", "ROOT") It is not possible to use regex at compiletime and I should use palain text matching? Thanks, Bogdan
Re: unserialize variants
Thanks for the response... I thought there is a faster way for that. I will use the standard lib or i will use json to store that into a file. Thanks, Bogdan On Sunday, 1 September 2013 at 16:19:32 UTC, Ali Çehreli wrote: On 08/31/2013 10:22 PM, gedaiu wrote:> Hi, > > i want to save data from an array of variants into a file. I saw that > to!string format the array content in a nice way... I don't think the format is sufficient for recreating the array: import std.variant; import std.conv; import std.stdio; struct S { int i; } void main() { auto a = [ Variant(42), Variant("hello"), Variant(S(5)) ]; writeln(a); } Outputs: [42, hello, S(5)] We can only guess that 'hello' is a string but what if it were the string "43"? It would look like an int. Also, any type can overload toString; so, S(5) could output itself as e.g. "world". > There is a way of > converting the resulted string back to an array of varianta? This requires a serialization module. std.serialization is in review right now: http://forum.dlang.org/post/hsnmxykmoytfvwroi...@forum.dlang.org Its author Jacob Carlborg already has a serialization module called Orange: https://github.com/jacob-carlborg/orange > > thanks, > Bogdan Ali
unserialize variants
Hi, i want to save data from an array of variants into a file. I saw that to!string format the array content in a nice way... There is a way of converting the resulted string back to an array of varianta? thanks, Bogdan
Re: Strange seg fault
Hi, How should i submit this bug? Thanks, Bogdan On Wednesday, 12 June 2013 at 20:49:54 UTC, Ali Çehreli wrote: On 06/12/2013 01:12 PM, gedaiu wrote: > Hi, > > Can anyone help me why this code goes wrong? I get exit code 139 with > DMD 2.063 > > > import std.stdio; > > > > struct Test { > string val = ""; > string[] key; > > /** > * operator "=" overload > */ > Test opAssign(string val){ > this.val = val; > > string[1] t; > t = val; > > key ~= t; Instead of the last three lines: key ~= val; However, if you really wanted a 1-element fixed-length array then: string[1] t = [ val ]; > return this; > } > Remove the following opAssign altogether: > Test opAssign(Test val){ > this.val = val.val; > > key ~= val.key; > > return this; > } As general rules: * Define a post-blit only if the code would be incorrect if you don't do that. (For example, it may be incorrect that two objects share the same array.) * Define an opAssign from the same type only if your implementation will be more efficient than the compiler's safe alternative, which happens to be "first copy, then swap." For example, instead of copying a member array, you may decide to reuse it. > void append(Test t) { > val ~= t.val; > key ~= t.key; > }; > } > > void main() { > > Test val; > val = "test"; > > Test[string] data; > Test v; > v = "asd"; > data["test"] = v; > > writeln(v); > writeln(data["test"]); > > data["test"].append(val); > > > writeln(data["test"].key); > writeln("done"); > } > > Thanks, > Bogdan Ali
Re: Associative multidimensional Arrays
Hi, Please look at this thread. You might find your answer there: http://forum.dlang.org/thread/vphniyxyvgsiazutt...@forum.dlang.org Bogdan On Wednesday, 12 June 2013 at 20:20:09 UTC, MaB wrote: Hi! I want to bulid up a IndexArray with a structure like this (PHP code): $arrIndex = array( "A" => array( "B" => array() ), "B" => array( "B" => array("C" => array()) ) ); The Keys are of Type string and the values can be arrays with the same structure. The Array-Depth has to be variable.. Is there a way in D to make it possible? I am trying it now since hours :( Greetings
Strange seg fault
Hi, Can anyone help me why this code goes wrong? I get exit code 139 with DMD 2.063 import std.stdio; struct Test { string val = ""; string[] key; /** * operator "=" overload */ Test opAssign(string val){ this.val = val; string[1] t; t = val; key ~= t; return this; } Test opAssign(Test val){ this.val = val.val; key ~= val.key; return this; } void append(Test t) { val ~= t.val; key ~= t.key; }; } void main() { Test val; val = "test"; Test[string] data; Test v; v = "asd"; data["test"] = v; writeln(v); writeln(data["test"]); data["test"].append(val); writeln(data["test"].key); writeln("done"); } Thanks, Bogdan
Re: Nesting Variants
what about this class? https://bitbucket.org/szabo_bogdan/cmsushid/raw/e2e4d2195bf48df586887768d2d800d21227c80d/src/base/Value.d
Re: Garbage collector question
On Thursday, 16 May 2013 at 06:21:06 UTC, Namespace wrote: On Thursday, 16 May 2013 at 06:08:30 UTC, gedaiu wrote: Does the garbage collector manages the memory from extern(C) functions, or we have to delete manualy the objects created in those kind of functions? Thanks, Bogdan You mean something like malloc or any kind of, for example, derelict functions? If so: You have to delete manually. Or did you mean regular functions in D which are denoted with extern (C)? If so: extern (C) means only C linkage behaviour. So as long as you do not use some C functions, like malloc, you don't have to delete your memory manually in this case. Otherwise I've misunderstood your question. Thanks, That was the answer that i was looking for... i thought that if i use extern(C) the compiler it's acting like a c compiler or something like that.. But it's good to know that every object that I create with new it will be "watched" bu GC. Bogdan
Garbage collector question
Does the garbage collector manages the memory from extern(C) functions, or we have to delete manualy the objects created in those kind of functions? Thanks, Bogdan
Re: callback parameter order question
On Saturday, 11 May 2013 at 11:28:10 UTC, evilrat wrote: On Saturday, 11 May 2013 at 10:44:01 UTC, gedaiu wrote: On Saturday, 11 May 2013 at 10:04:54 UTC, Andrej Mitrovic wrote: On 5/11/13, gedaiu wrote: if i do that, i get this error I don't know what "ahc_echo" is, but I imagine you'll have to make it an extern(C) function. Hi, i have this code, and i don't think i can add extern(C) there void start() { auto ahc_echo = function(void* cls, MHD_Connection* connection, const char *url, const char *method, const char *ver, const char *upload_data, size_t *upload_data_size, void **ptr) { ... }; d = MHD_start_daemon(MHD_FLAG.MHD_USE_THREAD_PER_CONNECTION, 8080, null, null, ahc_echo, null, MHD_OPTION.MHD_OPTION_END); } and if i create a function like this: extern(C) int ahc_echo(void* cls, MHD_Connection* connection, const char *url, const char *method, const char *ver, const char *upload_data, size_t *upload_data_size, void **ptr) { }; i get this error: Error: function cmsutils.CMServer.ahc_echo (void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** ptr) is not callable using argument types () Error: expected 8 function arguments, not 0 looks like you are trying to pass func as parameter in this func, but you forgot to take its address d = MHD_start_daemon(MHD_FLAG.MHD_USE_THREAD_PER_CONNECTION, 8080, null, null, &ahc_echo, // <-- here null, MHD_OPTION.MHD_OPTION_END); yeah... what a shameful mistake.. i vave a new tricky question... how i can provide a class method instead a simple function as callback?
Re: callback parameter order question
On Saturday, 11 May 2013 at 10:04:54 UTC, Andrej Mitrovic wrote: On 5/11/13, gedaiu wrote: if i do that, i get this error I don't know what "ahc_echo" is, but I imagine you'll have to make it an extern(C) function. Hi, i have this code, and i don't think i can add extern(C) there void start() { auto ahc_echo = function(void* cls, MHD_Connection* connection, const char *url, const char *method, const char *ver, const char *upload_data, size_t *upload_data_size, void **ptr) { ... }; d = MHD_start_daemon(MHD_FLAG.MHD_USE_THREAD_PER_CONNECTION, 8080, null, null, ahc_echo, null, MHD_OPTION.MHD_OPTION_END); } and if i create a function like this: extern(C) int ahc_echo(void* cls, MHD_Connection* connection, const char *url, const char *method, const char *ver, const char *upload_data, size_t *upload_data_size, void **ptr) { }; i get this error: Error: function cmsutils.CMServer.ahc_echo (void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** ptr) is not callable using argument types () Error: expected 8 function arguments, not 0
Re: callback parameter order question
On Saturday, 11 May 2013 at 09:39:42 UTC, Andrej Mitrovic wrote: On 5/11/13, gedaiu wrote: alias int function(void **con_cls, size_t *upload_data_size, const char *upload_data, const char *ver, const char *method, const char *url, MHD_Connection* connection, void* cls) MHD_AccessHandlerCallback; Add extern(C) to the alias: alias extern(C) int function(void **con_cls, ...) MHD_AccessHandlerCallback; if i do that, i get this error src/import/server.d(128): Error: function gnu.microhttpd.MHD_start_daemon (uint flags, uint port, extern (C) int function(void* cls, const(sockaddr*) addr, uint addrlen) apc, void* apc_cls, extern (C) int function(void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** con_cls) dh, void* dh_cls, ...) is not callable using argument types (MHD_FLAG,int,typeof(null),typeof(null),int function(void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** ptr) @system,typeof(null),MHD_OPTION) src/import/server.d(128): Error: cannot implicitly convert expression (ahc_echo) of type int function(void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** ptr) @system to extern (C) int function(void* cls, MHD_Connection* connection, const(char*) url, const(char*) method, const(char*) ver, const(char*) upload_data, ulong* upload_data_size, void** con_cls)
callback parameter order question
Hi, I try to create a D interface to GNU Libmicrohttpd because i could not find any, and while i was implementing a demo webserver i've noticed that the MHD_AccessHandlerCallback in D is triggered with the parameters in the reverse order. This is in c: struct MHD_Daemon * MHD_start_daemon (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...); typedef int (*MHD_AccessHandlerCallback) (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls); and to work in D I had to this: alias int function(void **con_cls, size_t *upload_data_size, const char *upload_data, const char *ver, const char *method, const char *url, MHD_Connection* connection, void* cls) MHD_AccessHandlerCallback; extern (C) { . MHD_Daemon *MHD_start_daemon(uint flags, uint port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls,...); } Can anyone help me to understand this? Thanks, Bogdan
Re: how hash_t toHash() works?
On Tuesday, 30 April 2013 at 17:48:08 UTC, Ivan Kazmenko wrote: - import std.functional; ... RedBlackTree !(MyRecord, binaryFun!"a.key < b.key", true) cont; ... cont = redBlackTree !("a.key < b.key", true, MyRecord) (); - Error: template instance RedBlackTree!(ValueRecord, binaryFun, true) RedBlackTree!(ValueRecord, binaryFun, true) does not match template declaration RedBlackTree(T, alias less = "a < b", bool allowDuplicates = false) if (is(typeof(binaryFun!(less)(T.init, T.init Error: RedBlackTree!(ValueRecord, binaryFun, true) is used as a type I am able to reproduce it if I write RedBlackTree !(MyRecord, binaryFun, true) instead of RedBlackTree !(MyRecord, binaryFun!"a.key < b.key", true) If you are using a plain regular function instead of "a.key < b.key" there, consider the following form: - bool less (T) (auto ref T a, auto ref T b) { return a.key < b.key; } ... RedBlackTree !(MyRecord, less, true) cont; ... cont = redBlackTree !(less, true, MyRecord) (); - Note that the straightforward notation does *not* work yet in 2.062 if you want ref parameters: - bool less (ref MyRecord a, ref MyRecord b) { return a.key < b.key; } - The current condition of binaryFun is too tight. So, for now, we have to create a non-ref version too to pass it. See (and perhaps comment) the following issue in BugZilla: http://d.puremagic.com/issues/show_bug.cgi?id=9513 Ivan Kazmenko. One more question... why associative arrays in D can't be implemented like here? http://svn.php.net/viewvc/php/php-src/trunk/Zend/zend_hash.h?view=markup it seems that php arrays uses hash tables too but they preserve orders. Thanks, Bogdan
Re: strange runtime error
On Thursday, 2 May 2013 at 19:55:23 UTC, Jesse Phillips wrote: On Thursday, 2 May 2013 at 10:30:20 UTC, gedaiu wrote: can anyone help me tu understand this kind of errors? /home/user/workspace/path/project/src(_D4core7runtime18runModuleUnitTestsUZb19unittestSegvHandlerUiPS4core3sys5posix6signal9siginfo_tPvZv+0x3e)[0x485ede] Basic translation: core.runtime.runModuleUnitTests.unittest-SegvHandler-core.sys.posix.signal-siginfo = tPvZv+0x3e[0x485ede] <- Memory location Yes, i am using linux. Thanks! Bogdan
strange runtime error
can anyone help me tu understand this kind of errors? /home/user/workspace/path/project/src(_D4core7runtime18runModuleUnitTestsUZb19unittestSegvHandlerUiPS4core3sys5posix6signal9siginfo_tPvZv+0x3e)[0x485ede]
Re: how hash_t toHash() works?
On Monday, 29 April 2013 at 16:01:15 UTC, Ivan Kazmenko wrote: one more question What is the type of cont? auto cont = redBlackTree !("a.key < b.key", true, MyRecord) (); I want to use this as a property in a class and i can't use there auto keyword... I tried different types but it did not work. For me, the following declaration works: - import std.functional; ... RedBlackTree !(MyRecord, binaryFun!"a.key < b.key", true) cont; ... cont = redBlackTree !("a.key < b.key", true, MyRecord) (); - I admit it could have been easier to figure out. For example, "writeln (typeof (cont).stringof);" just prints "RedBlackTree" which is not enough for a proper declaration. I've inferred the right declaration from the following lines in container.d: - /++ Ditto +/ auto redBlackTree(alias less, bool allowDuplicates, E)(E[] elems...) if(is(typeof(binaryFun!less(E.init, E.init { //We shouldn't need to instantiate less here, but for some reason, //dmd can't handle it if we don't (even though the template which //takes less but not allowDuplicates works just fine). return new RedBlackTree!(E, binaryFun!less, allowDuplicates)(elems); } - Error: template instance RedBlackTree!(ValueRecord, binaryFun, true) RedBlackTree!(ValueRecord, binaryFun, true) does not match template declaration RedBlackTree(T, alias less = "a < b", bool allowDuplicates = false) if (is(typeof(binaryFun!(less)(T.init, T.init Error: RedBlackTree!(ValueRecord, binaryFun, true) is used as a type Do you know what this error means? Thank, Bogdan
Re: how hash_t toHash() works?
On Sunday, 28 April 2013 at 13:18:04 UTC, Ivan Kazmenko wrote: Hi, I have a class which I want to use as key in an assoc array like this: string["KeyString"] myArray; What i want is to preserve the order in the array. I want always to have "1" before "2" if the string is a numeric value. Can anyone help me to understand how const hash_t toHash() should work? Associative arrays in D are implemented as hash tables. Hashing sacrifices ordering capabilities for greater speed. Creating a hash table will most certainly take your toHash value modulo some integer you can not control (small for small tables, large for larger ones). It would be crippling, if at all possible, to have foreach on an associative array always produce a sorted result. I'd suggest using std.container.RedBlackTree instead. It doesn't provide syntactic sugar (like "container[key] = value") but preserves the ordering. Also note that sorting items as strings should be separated from sorting as integers. For example, a value convertible to integer should be always less (or always greater) than a non-convertible value. Otherwise, it would quickly lead to inconsistent comparisons, as in "22" Here, " Below is an example of using RedBlackTree close to what you might need: - import std.container; import std.conv; import std.stdio; bool doConv(out long val, string s) { try { val = to!long(s); return true; } catch(ConvException) { return false; } } struct KeyString { string str; KeyString opAssign(string val) { str = val; return this; } const int opCmp(ref const KeyString s) { long v1, v2; auto b1 = doConv(v1, str); auto b2 = doConv(v2, s.str); if (b1 != b2) return b2 - b1; if (b1 && b2) return (v1 > v2) - (v1 < v2); return std.string.cmp(str, s.str); } } struct MyRecord { KeyString key; int val; this(string nkey, int nval) { key = nkey; val = nval; } } void main () { auto cont = redBlackTree !("a.key < b.key", true, MyRecord) (); cont.insert(MyRecord("1", 1)); cont.insert(MyRecord("111", 2)); cont.insert(MyRecord("25", 3)); cont.insert(MyRecord("53", 4)); cont.insert(MyRecord("a", 5)); cont.insert(MyRecord(" ", 6)); cont.insert(MyRecord("1234567890123456789", 7)); cont.insert(MyRecord("12345678901234567890", 8)); foreach (ref const cur; cont) { writefln("cont[\"%s\"] = %s", cur.key.str, cur.val); } } - The example prints: - cont["1"] = 1 cont["25"] = 3 cont["53"] = 4 cont["111"] = 2 cont["1234567890123456789"] = 7 cont[" "] = 6 cont["12345678901234567890"] = 8 cont["a"] = 5 - The last three entries are strings not convertible to a long, so they are ordered lexicographically. Ivan Kazmenko. Thanks! it looks great! one more questionWhat is the type of cont? auto cont = redBlackTree !("a.key < b.key", true, MyRecord) (); I want to use this as a property in a class and i can't use there auto keyword... I tried different types but it did not work. Bogdan
how hash_t toHash() works?
hi, I have a class which I want to use as key in an assoc array like this: string["KeyString"] myArray; What i want is to preserve the order in the array. I want always to have "1" before "2" if the string is a numeric value. Can anyone help me to understand how const hash_t toHash() should work? Here is the KeyString class: struct KeyString { string str; KeyString opAssign(string val) { str = val; return this; } const hash_t toHash() { try { return to!long(str); } catch(Exception e) { hash_t hash; foreach (char c; str) hash = (hash * 9) + c; return hash; } } const int opCmp(ref const KeyString s) { //return std.string.cmp(this.str, s.str); try { auto val1 = to!long(this.str); auto val2 = to!long(s.str); if(val1 < val2) { return -1; } if(val1 == val2) { return 0; } } catch(Exception e) { return std.string.cmp(str, s.str); } return 1; } } Thanks, Bogdan
opAssign overload question
Hi folks, i have this struct: import std.stdio, std.string; struct Value { private long intVal; private bool boolVal; private string type; Value opAssign(long val) { intVal = val; if(val == 0) { boolVal = false; } else { boolVal = true; } type = "LONG"; return this; } Value opAssign(bool val) { if(val) { boolVal = true; intVal = 1; } else { boolVal = false; intVal = 0; } type = "BOOL"; return this; } string getType() { return type; } } int main() { Value data; data = 1; writeln(data); writeln(data.getType()); assert(data.getType() == "LONG"); return 0; } output: Value(1, true, "BOOL") BOOL Can anyone tell me why the compiler call opAssign(bool val) and not opAssign(long val). I am passing an long value not a bool one. Thanks, Bogdan
Re: writeln an object
Ok, i understand now the diference... my question is how I should solve this problem? Thanks, Bogdan On Thursday, 18 April 2013 at 20:57:23 UTC, Ali Çehreli wrote: On 04/18/2013 12:37 PM, John Colvin wrote: > However, by a wider definition of the word, a struct could also be said > to be an object. You are missing some words there. :) Not a struct itself, but instances of it are said to be objects. Ali
Re: writeln an object
On Thursday, 18 April 2013 at 18:25:21 UTC, John Colvin wrote: On Thursday, 18 April 2013 at 18:04:03 UTC, Andrej Mitrovic wrote: On 4/18/13, gedaiu wrote: i've done that but i get this error: Error: function base.Value.Value.toString cannot override a non-virtual function Error: function base.Value.Value.toString override only applies to class member functions If it's a struct then don't put "override". Just to provide a bit more info: Classes all derive from Object, which defines toString. Hence, you need to override it to define your own. Structs don't have a parent (or any inheritance at all) and hence you don't override anything, you just define the method. i'm realy sorry... it's my mistake... i have a struct not an object. I have someting like this when i get the error: struct Value { string strVal; this(string val) { strVal = val; } override string toString() { return strVal; } }
Re: writeln an object
On Thursday, 18 April 2013 at 17:42:53 UTC, JN wrote: On Thursday, 18 April 2013 at 17:36:10 UTC, gedaiu wrote: Hi, how i can control what writeln outputs when I pass an object parameter? Thanks, Bogdan You can override the toString() method, like this http://dpaste.dzfl.pl/db7dbe28 i've done that but i get this error: Error: function base.Value.Value.toString cannot override a non-virtual function Error: function base.Value.Value.toString override only applies to class member functions
writeln an object
Hi, how i can control what writeln outputs when I pass an object parameter? Thanks, Bogdan
Re: mysql
On Monday, 15 April 2013 at 19:25:19 UTC, simendsjo wrote: On Monday, 15 April 2013 at 17:34:07 UTC, gedaiu wrote: Hi, Can anyone help me to connect to mysql from D? Thanks! You can use Steve Teales native library. The most up-to-date version is here: https://github.com/rejectedsoftware/mysql-native It relies on vibes async sockets though. You'll have to grab an earlier version or modify it yourself if you want to use phobos sockets. Thanks for the tip! I would like to use vibe, but i don't know how to install it.. I am using ubuntu. I ran the setup-linux.sh script, it worked perfectly, but my d procram does not see the mdules... Thanks, Bogdan
mysql
Hi, Can anyone help me to connect to mysql from D? Thanks!
Re: opIndex operators
On Saturday, 13 April 2013 at 11:41:02 UTC, bearophile wrote: gedaiu: What i want to create, is an array structure like the one from PHP where array levels are not fixed and the sintax to access rhe values is val[][] so returning a reference to a struct that have the same type as the current type is useful. there is a way to do this in D? Instead of returning float as in my case, you return something else that has opIndex and opIndexAssign. This way you can pile up the []: import std.stdio; struct Foo { ref Foo opIndex(in size_t i) { writeln("opIndex: ", i); return this; } void opIndexAssign(in float value, in size_t i) { writeln("opIndexAssign: ", value, " ", i); } } void main() { Foo f; f[1] = 2; f[3][4] = 5; f[6][7][8] = 9; } That outputs: opIndexAssign: 2 1 opIndex: 3 opIndexAssign: 5 4 opIndex: 6 opIndex: 7 opIndexAssign: 9 8 Bye, bearophile Value[Value] container; ref Value opIndex(Value index) { return container[index]; } why I get this error? Error: function base.Value.Value.opIndex (Value index) is not callable using argument types (string) Error: cannot implicitly convert expression ("string") of type string to Value I have implemented this methods: this(string) Value opCast(string val) Value opAssign(ref const string val) Thanks!
Re: How i can clear Associative Arrays
On Saturday, 13 April 2013 at 21:10:16 UTC, Nicolas Guillemot wrote: I think we should introduce a removeAll function for hashes. Either through Druntime or through a UFCS function that we could put in std.array or somewhere. How about .clear() for consistency with C++ containers? It looks nice... i am waiting for it :P
Re: opIndex operators
Hi, thanks for the answer, but it's not the solution what i was expectig. What i want to create, is an array structure like the one from PHP where array levels are not fixed and the sintax to access rhe values is val[][] so returning a reference to a struct that have the same type as the current type is useful. there is a way to do this in D? thanks!
opIndex operators
Hi again! I don't understand why we have opIndex() and opIndexAssign()... can anyone explain this for me? Because in c++ there is only one operator overload for "[]" and it looks like this: Value& Value::operator[] (constValue offset) { return container[offset]; } and with this operator overload I can set or get values from container, and also easily implement custom multilevel arrays. In D when I have this method Value& opIndex(Value index) { return container[index]; } I get this error. Error: no identifier for declarator Value Error: semicolon expected, not '&' Declaration expected, not '&' And also, how you can implement custom structs that acts like a multilevel array in D like in c++? Thanks!
Re: How i can clear Associative Arrays
On Saturday, 13 April 2013 at 09:52:45 UTC, Andrej Mitrovic wrote: On 4/13/13, gedaiu wrote: looks great, but i cleared the array like this: values = null; That's not clearing the array, that's clearing the reference to the array. For example: void main() { int[int] hash; hash[1] = 1; auto hash2 = hash; // new reference hash = null; // clear the reference assert(1 in hash2); // hash still exists } I know, that's why I am asking how i should do this...
Re: How i can clear Associative Arrays
On Saturday, 13 April 2013 at 09:09:36 UTC, Nicolas Guillemot wrote: Hey gedaiu, I'm still a novice to D, but here are some solutions I found. They can probably be improved. 1) Assigning to it an empty map https://ideone.com/h7ffmD 2) Removing all entries https://ideone.com/E7k2WL My guess is that the first method is more efficient. I wish I knew how to do it without having to explicitly declare the "empty" variable. Cheers. Hi, string[string] empty; values = empty; looks great, but i cleared the array like this: values = null; and it seems it works great. But, i don't know how correct is this... I was expecting to have a clear() method on array. Thanks, Bogdan
How i can clear Associative Arrays
Hi, I have an associative array: string values[string], and i want to remove all the values from this array. I looked at the documentation here: http://dlang.org/hash-map.html and i can't see any method for this action. There is a nice way to remove the values, or I should use foreach? Thanks!
Re: class constructor
On Saturday, 13 April 2013 at 07:57:30 UTC, Nicolas Guillemot wrote: Classes are instanciated with new, structs are not. The following program compiles: class A { int myVal; this(int val) { myVal = val; } } struct B { int myVal; this(int val) { myVal = val; } } void main() { A myA = new A(8); B myB = 8; } Thanks!
class constructor
Hi, Why in D this expression does not call the class constructor? class A { int myVal; this(int val) { myVal = val; } } int main() { A myA = 8; } I would like to have a feature like this, because i want to create my own data type. I think it's possible, but i don't know why... std.variant, can be initialized like this. Thanks!