Re: -preview=in deprecation warning
On Thursday, 20 April 2023 at 09:41:13 UTC, Dennis wrote: On Thursday, 20 April 2023 at 09:14:48 UTC, Jack Applegame wrote: Can anyone help me get rid of this depreciation? Annotate `getFoo` with `return scope`: ```d struct Foo { string foo; string getFoo() return scope const @safe { return foo; } } Wow. Thanks. I tried this, but rearranged the return and scope like this ```d // doesn't work string getFoo() scope return const @safe { return foo; } ``` ```d // works string getFoo() return scope const @safe { return foo; } ```
-preview=in deprecation warning
Can anyone help me get rid of this depreciation? ```d struct Foo { string foo; string getFoo() const @safe { return foo; } } size_t bar(in Foo foo) @safe { return foo.getFoo().length; } void main() { Foo("hello").bar().writeln(); } ``` ```sh $ ldc2 -preview=in --run foo.d foo.d(9): Deprecation: scope variable `foo` assigned to non-scope parameter `this` calling `getFoo` ``` ```sh $ ldc2 --version LDC - the LLVM D compiler (1.32.1): based on DMD v2.102.2 and LLVM 15.0.7 ```
Re: print ubyte[] as (ascii) string
On Thursday, 30 December 2021 at 18:07:15 UTC, eugene wrote: On Thursday, 30 December 2021 at 17:52:20 UTC, eugene wrote: much better than my initial You can also write ```d auto s = cast(string)b; // or cast(string)(b) ``` instead of ```d char[] s = cast(char[])b[0 .. $]; ```
Re: function parameters: is it possible to pass byref ... while being optional at the same time ?
On Saturday, 17 July 2021 at 20:49:58 UTC, someone wrote: The following gives me a compiler error when I add the second parameter: is not an lvalue and cannot be modified ```d public bool add( ref classTickerID robjTickerID, ref classExchanges robjExchanges = null /// needing this optional ) { } ``` If I take out the null then the parameter is assumed mandatory of course. Just remove `ref`, because in D clasess themselves are references.
Re: How to disable assigning a value to a property?
On Tuesday, 6 July 2021 at 12:33:20 UTC, Adam D Ruppe wrote: The language always allows `a = b;` to be rewritten as `a(b);`. And that's sad. It should happen for properties only.
Re: How to disable assigning a value to a property?
On Tuesday, 6 July 2021 at 10:25:28 UTC, Dennis wrote: We're [still awaiting formal assessment on dip1038](https://forum.dlang.org/thread/sojvxakgruzfvbigz...@forum.dlang.org), but if that gets in, you can mark `clock` or `Field` `@nodicard`. Otherwise I don't know of a way. Yes, it would help.
Re: How to disable assigning a value to a property?
On Tuesday, 6 July 2021 at 10:24:45 UTC, drug wrote: Something like using different types for arguments in `Register.clock` and `Field.opAssign`? I've been thinking about it. Unfortunately, this is not always convenient.
How to disable assigning a value to a property?
Code: ```d import std.stdio; struct Field { void opAssign(int a) { writefln("Field.opAssign(%s)", a); } } struct Register { Field clock(int a) { writefln("Register.clock(%s)", a); return Field(); } } void main() { Register register; register.clock(1) = 10; // works, good register.clock = 10;// works too, how to disable it? } ``` How to disable `register.clock = 10;` but allow `register.clock(1) = 10;`? I want to get a compilation error on `register.clock = 10;`
Re: Strange error
On Sunday, 21 March 2021 at 08:45:19 UTC, Imperatorn wrote: On Sunday, 21 March 2021 at 07:18:10 UTC, Jack Applegame wrote: Could someone please explain what is wrong with this code? https://glot.io/snippets/fwxn2198kv ```d import std.stdio; struct Sample{ void function() func1; void function() func2; } void noth(Sample smpl)() { smpl.func1(); // Error: expression __lambda1 is not a valid template value argument smpl.func2(); // Error: expression __lambda2 is not a valid template value argument } void main(){ enum s = Sample( {writeln("Hello world1");}, {writeln("Hello world2");} ); s.func1(); s.func2(); noth!(s)(); } ``` https://forum.dlang.org/thread/mggbomxhjpglltsih...@forum.dlang.org There are no non-global templates in my snippet.
Strange error
Could someone please explain what is wrong with this code? https://glot.io/snippets/fwxn2198kv ```d import std.stdio; struct Sample{ void function() func1; void function() func2; } void noth(Sample smpl)() { smpl.func1(); // Error: expression __lambda1 is not a valid template value argument smpl.func2(); // Error: expression __lambda2 is not a valid template value argument } void main(){ enum s = Sample( {writeln("Hello world1");}, {writeln("Hello world2");} ); s.func1(); s.func2(); noth!(s)(); } ```
static alias this and if/do/while/for
There is a funny feature (or bug) in the D language: static alias this and static operator overloading. For example interface Foo { static { int value; void opAssign(int v) { value = v; } int get() { return value; } alias get this; } } Now we can use type Foo as if it were an lvalue/rvalue: Foo = 5; int a = Foo; int b = Foo + a; I heavily use this feature in my MCU library. But it doesn't work inside conditionals: if(Foo) {}// Error: type Foo is not an expression while(Foo) {} // Error: type Foo is not an expression Even if we define `static opCast!bool()`. It doesn't help. Should this be fixed?
Arrays and non-copyable elements
I think it should compile. ``` struct NonCopyable { int a; this(this) @disable; } void main() { NonCopyable[] arr = [NonCopyable(1), NonCopyable(2)]; // ok arr ~= NonCopyable(3); // fails } ```
Re: Should it compile?
On Saturday, 6 June 2020 at 11:58:06 UTC, Basile B. wrote: maybe it shouldn't but then with another message, for example Error, cannot `void` initialize a `const` declaration. since that makes very little sense, at least as a local variable. (as a member, this can be initialized in a constructor) The local variable is just an example. I need to move a constant structure from one place in memory to another. I want to write something like C++ std::unique_ptr. Consider (this is not real code, but just a simple example): https://run.dlang.io/is/mUUU8c ``` import core.memory : pureMalloc, pureFree; import std.algorithm : move, moveEmplace; import std.traits : hasElaborateDestructor; struct NonCopyable { this(this) @disable; } struct Unique(T) { this(this) @disable; T* m_data; this(T data) { m_data = cast(T*) pureMalloc(T.sizeof); moveEmplace(data, *m_data); } ~this() { if(m_data) { static if(hasElaborateDestructor!T) (cast(Unqual!T*) m_data).__xdtor; pureFree(m_data); } } } void main() { NonCopyable a; auto ua = Unique!NonCopyable(move(a)); // fine const NonCopyable const_a; auto const_ua = Unique!(const NonCopyable)(move(ca)); // error, why??? } ```
Re: Should it compile?
On Saturday, 6 June 2020 at 12:02:03 UTC, MoonlightSentinel wrote: On Saturday, 6 June 2020 at 08:55:20 UTC, Jack Applegame wrote: Should it compile? No, moveEmplace just sees a const reference and doesn't know that a is void-initialized. Actually, it knows. Because moveEmplace assumes target is uninitialized.
Should it compile?
Should it compile? ```d import std.algorithm.mutation; void main() { const char a = void; const char b ='b'; moveEmplace(b, a); // mutation.d: Error: cannot modify const expression target assert(a == 'b'); } ``` I think, it should.
Re: Bug?
On Monday, 11 May 2020 at 13:12:37 UTC, Simen Kjærås wrote: Filed here: https://issues.dlang.org/show_bug.cgi?id=20821 Thanks.
Re: Bug?
On Monday, 11 May 2020 at 12:30:22 UTC, Adam D. Ruppe wrote: UFCS is only defined to work with global scope functions. A restricted import (module : symbol, symbols) puts things in local scope so ufcs doesn't apply. But in this case the error should be displayed for lines 4 and 5, not 11. Line 11 contains a call to a member function, not UFCS. In addition, if you add the parentheses, then it works: assert(rng.front() == '1');
Re: Bug?
And the first example still doesn't compile: ``` struct Range(R) { import std.array : empty, front, popFront; R range; bool empty() const { return range.empty; } auto front() const { return range.front; } void popFront() { range.popFront(); } } void main() { auto rng = Range!string("1234"); assert(rng.front == '1'); } ``` onlineapp.d(11): Error: void has no value onlineapp.d(11): Error: incompatible types for (rng.front) == ('1'): void and char ```
Re: Bug?
On Monday, 11 May 2020 at 12:20:06 UTC, Jack Applegame wrote: assert(rng.front == 1); Damn! I made a typo. It must be: assert(rng.front == '1') So the second example works fine.
Bug?
Why doesn't it compile? ``` struct Range(R) { import std.array : empty, front, popFront; R range; bool empty() const { return range.empty; } auto front() const { return range.front; } void popFront() { range.popFront(); } } void main() { auto rng = Range!string("1234"); assert(rng.front == 1); } ``` onlineapp.d(11): Error: void has no value onlineapp.d(11): Error: incompatible types for (rng.front) == (1): void and int try here: https://run.dlang.io/is/Dg8Fpr If you move the import to the global scope, you will get a weird result: ``` import std.stdio; import std.array : empty, front, popFront; struct Range(R) { R range; bool empty() const { return range.empty; } auto front() const { return range.front; } void popFront() { range.popFront(); } } void main() { auto rng = Range!string("1234"); writefln("front: %s", rng.front); assert(rng.front == 1); } ``` front: 1 core.exception.AssertError@onlineapp.d(14): Assertion failure ??:? _d_assertp [0x56107489bc75] onlineapp.d:14 _Dmain [0x561074889902] try here: https://run.dlang.io/is/arieKR WAT???
Challenge
I recently came across an interesting exercise. Given a series of positive numbers, each of which belongs to the set { 2^^i * 3^^j * 5^^k | i, j, k ≥ 0 }. The series is ordered in ascending order. The beginning looks like this: { 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, ... } The goal is to get the Nth element of the series. For example, for N = 10, the answer is 12. On the Internet, I found an elegant and incredibly fast solution in Haskell: ``` mergeUniq :: Ord a => [a] -> [a] -> [a] mergeUniq (x:xs) (y:ys) = case x `compare` y of EQ -> x : mergeUniq xs ys LT -> x : mergeUniq xs (y:ys) GT -> y : mergeUniq (x:xs) ys powers :: [Integer] powers = 1 : expand 2 `mergeUniq` expand 3 `mergeUniq` expand 5 where expand factor = (factor *) <$> powers main = print $ powers!!99 ``` On my machine, the 100th element is found in 0.215s. OMG! After that, I spent almost the entire day searching for at least the same fast solution in D. My first attempt was simple and quite pretty, but awfully slow: ``` import std.stdio; import std.array; import std.bigint; import std.algorithm; auto generate(int n) { BigInt[] nums = [BigInt("1")]; foreach(i; 0..n) { nums = merge(nums, [nums[i] * 2, nums[i] * 3, nums[i] * 5]).uniq().array(); } return nums[n - 1]; } void main() { writeln(generate(5000)); } ``` 0.275s for 5000th element. At the end of the day, I managed to catch up and even overtake Haskell by emulating its lazyness with ranges and a funny trick. Victory! :) If you find this interesting, I will publish my latest version. And feel free to find your own solution. ;)
Re: Temporary objects as function parameters or when-is-this-shit-going-to-end?
On Friday, 13 October 2017 at 12:03:55 UTC, Dgame wrote: Interesting. If you remove the CTor in Foo it works again. If you remove DTor it works again too. :)
Re: Temporary objects as function parameters or when-is-this-shit-going-to-end?
On Friday, 13 October 2017 at 11:21:48 UTC, Biotronic wrote: BountySource[2] lets you do basically exactly that. My experience says that BountySource almost doesn't help.
Temporary objects as function parameters or when-is-this-shit-going-to-end?
If you don't want to get the great PITA, never create temporary objects in function parameters. I recently spent a whole day digging through my reference counted containers library. But nasty bug was not there, but in the compiler. Look at this: https://glot.io/snippets/eui2l8ov0r Result: Bar.this(int): 7FFD3D60CD38 fun: 7FFD3D60CD20 Bar.~this(): 7FFD3D60CD20 Compiler creates struct on the stack and silently (without postblitting and destruction old object) moves it to another address. Is it normal? I don't think so. But that's not the most fun. Look at this: https://glot.io/snippets/eui2pjrwvi Result: Bar.this(int): 7FFF87DD2D31 fun: 7FFF87DD2CE0 Bar.~this(): 7FFF87DD2CE0 Bar.~this(): 7FFF87DD2D31 WAT??? Compiler creates struct on the stack copies it without postblitting and destructs both objects. But if you create the structure before calling the function, then all will be well: https://glot.io/snippets/eui2vn2bu1 All this greatly angered me because there are several issues related wrong struct construction and destruction in the bugtracker. Because of these bugs my low level libraries full of strange hacks. I want to ask. How you guys are going to create a reliable RC library, if such fundamental bugs hang in the issue tracker for months and years. And instead of fixing them, you develop new minor bells and whistles. See: https://issues.dlang.org/buglist.cgi?quicksearch=destructor Since I myself can't fix such bugs (my knowledge in this area are extremely small), I have a question to Andrei Alexandrescu: Can I donate to the D Foundation and that my donations would be aimed at fixing exactly these bugs?
Re: What the hell is wrong with D?
On Tuesday, 19 September 2017 at 19:54:02 UTC, Steven Schveighoffer wrote: On 9/19/17 1:40 PM, EntangledQuanta wrote: The first returns x + w/2 and the second returns w/2! Did you mean (x + w) / 2 or x + (w / 2)? Stop being ambiguous! -Steve The best answer. :D
Re: Appending static arrays
On Tuesday, 18 July 2017 at 12:39:01 UTC, Stefan Koch wrote: whhhahhh template bloat Yes, and also very slow. :)
Re: Appending static arrays
On Monday, 17 July 2017 at 17:38:23 UTC, Nordlöw wrote: I'm want to define a specialization of `append()` that takes only static arrays as inputs and returns a static array being the sum of the lengths of the inputs. Have anybody already implemented this? If not, I'm specifically interested in how to most conveniently infer the length (as an enum) of the returned static array from the `.length`s of inputs (which of course must be enum-values too). My recursive version: auto concat(T, size_t N, ARRS...)(auto ref T[N] a, auto ref ARRS arrs) { static if(arrs.length == 0) { return a; } else { T[N + arrs[0].length] r = void; r[0..N] = a[]; r[N..$] = arrs[0][]; return concat(r, arrs[1..$]); } } unittest { int[3] a1 = [1, 2, 3]; int[3] a2 = [4, 5, 6]; int[3] a3 = [7, 8, 9]; static assert(is(typeof(concat(a1)) == int[3])); assert(concat(a1) == [1, 2, 3]); static assert(is(typeof(concat(a1, a2, a3)) == int[9])); assert(concat(a1, a2, a3) == [1, 2, 3, 4, 5, 6, 7, 8, 9]); }
Re: Static array with parameter based size?
On Wednesday, 12 July 2017 at 05:45:13 UTC, Miguel L wrote: Also what is it possible in D to write a function that accepts an static array of any size? void foo(size_t N)(ref int[N] arr) { ... } int[10] arr; foo(arr);
Re: Recursive template instantiation
Is this a bug?
Recursive template instantiation
I'm pretty sure that this code should compile (https://dpaste.dzfl.pl/cf1e1ee6ef4b): struct A(T) { ~this() { char[T.sizeof] data; } } struct B(T) { A!T foo; } struct C { B!C bar; } void main() { C c; } But it doesn't: /d300/f416.d(3): Error: struct f416.C no size because of forward reference /d300/f416.d(12): Error: template instance f416.B!(C) error instantiating Notice that the same C++ code compiles without problems: template struct A { ~A() { char data[sizeof(T)]; } }; template struct B { A foo; }; struct C { B bar; }; int main() { C c; } A simple recursion is compiled successfully (https://dpaste.dzfl.pl/5a8ff73bfa88): struct A(T) { ~this() { char[T.sizeof] data; } } struct C { A!C bar; } void main() { C c; }
Re: Cconditional expression in return statement. Bug?
On Tuesday, 7 March 2017 at 16:00:54 UTC, kinke wrote: Definitely a very bad bug. It works too if you mark `fun()` as nothrow. Please file a DMD issue. https://issues.dlang.org/show_bug.cgi?id=17246
Cconditional expression in return statement. Bug?
Code (https://dpaste.dzfl.pl/8e7a9c380e99): import std.stdio; struct Foo { int val; this(int val) { writefln("%s.this(int)", val); this.val = val; } this(this) { writefln("%s.this(this)", val); this.val = val; } ~this() { writefln("%s.~this()", val); this.val = val; } } struct Bar { Foo foo; this(Foo foo, bool) { this.foo = foo; } } bool fun(bool val) { return !val; } auto genBar(bool flag) { return flag ? Bar() : Bar(Foo(10), fun(!flag)); } void main(string[] args) { auto bar = genBar(args.length == 0); } Compiler generates extra destructor call: 10.this(int) 10.this(this) 10.~this() 10.~this() 10.~this() If we slightly change function genBar: auto genBar(bool flag) { auto a = flag ? Bar() : Bar(Foo(10), fun(!flag)); return a; } or auto genBar(bool flag) { return flag ? Bar() : Bar(Foo(10), false); } then output looks as expected: 10.this(int) 10.this(this) 10.~this() 10.~this() I'm pretty sure this is a bug. And very bad bug. I spent several hours looking for it. What do you think?
Re: Does vibe.d support setting cookies?
On Wednesday, 1 February 2017 at 14:09:41 UTC, aberba wrote: I can't find it. Like set_cookie() in php. Yes, it does. http://vibed.org/api/vibe.http.common/HTTPResponse.cookies
Re: Another bug?
bug report: https://issues.dlang.org/show_bug.cgi?id=17128
Re: Another bug?
WORKAROUND: import std.stdio; struct Foo { int val = 0; ~this() { writefln("destruct %s", val); } } void bar(ARGS...)() { struct Tuple { ARGS args; alias args this; } Tuple args; args[0].val = 1; writefln("val = %s", args[0].val); } void main() { bar!Foo(); }
Another bug?
Code: import std.stdio; struct Foo { int val = 0; ~this() { writefln("destruct %s", val); } } void bar(ARGS...)() { ARGS args; args[0].val = 1; writefln("val = %s", args[0].val); } void main() { bar!Foo(); } Excpected output: val = 1 destruct 1 But got: destruct 0 val = 1 It seems that the compiler destructs 'args' immediately after definition, not at the end of the function.
Re: Parsing a UTF-16LE file line by line, BUG?
On Monday, 16 January 2017 at 14:47:23 UTC, Era Scarecrow wrote: static char[1024*4] buffer; //4k reusable buffer, NOT thread safe Maybe I'm wrong, but I think it's thread safe. Because static mutable non-shared variables are stored in TLS.
Re: How to initialize a associative array?
On Saturday, 24 December 2016 at 00:55:01 UTC, Yuxuan Shui wrote: I tried this: immutable int[char] xx = ['Q':0, 'B':1, 'N':2, 'R':3, 'P':4]; And got a "non-constant expression" error (with or without 'immutable'). What's the correct way? This works: void main() { immutable int[char] xx = ['Q':0, 'B':1, 'N':2, 'R':3, 'P':4]; } If you want to initialize global variable, then immutable int[char] xx; shared static this() { xx = ['Q':0, 'B':1, 'N':2, 'R':3, 'P':4]; }
Re: Const/Immutable Slicing Syntax
cast(const) x[]; cast(immutable) x[];
Re: InterlockedIncrement, InterlockedCompareExchange, etc
On Sunday, 28 August 2016 at 20:38:30 UTC, Lodovico Giaretta wrote: On Sunday, 28 August 2016 at 19:53:51 UTC, Illuminati wrote: What are the D equivalents to these types of functions? I do not see anything in core.atomic that can accomplish this. I have tried to include core.sys.windows.winbase but still get linker errors(I've also directly tried importing kernel32 using various methods and still nothing). Regardless, would be nicer to have a more portable solution. I'm not an expert in this field (so probably I'm missing something), but I would think that InterlockedIncrement could be done with atomicOp!"+"(val, 1) and InterlockedCompareExchange with cas. Exactly! InterlockedIncrement - atomicOp!"+="(val, 1) or val.atomicOp!"+="(1) InterlockedCompareExchange - cas
mutable destructor? WAT???
object.destroy doesn't want to destroy const structure with destructor: struct T { ~this() {} } void foo_t(ref T t) { destroy(t); // works } void foo_ct(ref const T t) { destroy(t); // Error: mutable method T.~this is not callable using a const object } Mutable destructor? O___o With this difinition both functions compiles: struct T { ~this() const {} // WAT??? } Is there a bug in druntime?
Re: union mutability
On Thursday, 25 August 2016 at 19:19:49 UTC, Jonathan M Davis wrote: Why? I don't know exactly what that PR is supposed to do, but std.datetime uses immutable time zone objects, and if that PR made it so that you couldn't have an immutable instance of a class, then it would have failed the auto-tester. And it clearly doesn't stop having unions with immutable members, or it would have failed to compile because of Rebindable (though it may be that Rebindable can no longer be used in @safe code). - Jonathan M Davis Because lack of mutable references to immutable classes in @safe code is big PITA for me. It is easier to not use immutable classes at all.
Re: union mutability
Also I hate Rebindable.
Re: union mutability
On Thursday, 25 August 2016 at 17:01:40 UTC, Meta wrote: This should be fixed pretty soon: https://github.com/dlang/dmd/pull/5940 Bye-bye immutable classes. :'(
union mutability
Code: union A { immutable int f; } union B { immutable int f; int e; } void main() { A a = A(1); //a = A(2); // a.f is immutable, fails to compile as expected B b = B(1); b = B(2); // compiles!!! } It turns out that if the union contains at least one mutable member, then the entire union is considered to be mutable. It's logical, but does it meet the specs? I couldn't find description of this behavior.
Re: Metaprogramming, generate argument list.
On Tuesday, 23 August 2016 at 21:14:01 UTC, ciechowoj wrote: This is a bit strange, as the local variables aren't known either and they seem to work. I do not want to get the address, rather an alias to `&variable` expression. D doesn't accept aliases to expressions, only symbols and literals. Spec: https://dlang.org/spec/template.html#TemplateAliasParameter Alias parameters enable templates to be parameterized with almost any kind of D symbol, including user-defined type names, global names, local names, module names, template names, and template instance names. Literals can also be used as arguments to alias parameters.
Re: Metaprogramming, generate argument list.
On Monday, 22 August 2016 at 22:01:51 UTC, ciechowoj wrote: Is it possible to generate an argument list that contains pointers to local variables at compile time? For example, consider following code: template Repeat(alias int N, alias variable) { // Magic alias Repeat = /* Even more magic */; } void foo(int* x, int* y, int* z) { // [...] } void fun() { int bar = 42; foo(Repeat!(3, bar)); // want to replace it with &bar, &bar, &bar } This is impossible since pointers to local variables are unknown at compile time. But you can generate arguments list that contains functions that return pointers at run-time: template Repeat(int N, alias variable) { auto ptr() @property { return &variable; } import std.meta : AliasSeq; static if(N == 1) alias Repeat = ptr; else alias Repeat = AliasSeq!(ptr, Repeat!(N-1, variable)); } void foo(int* x, int* y, int* z) { } void main() { int bar = 42; foo(Repeat!(3, bar)); }
Re: Rebind template(bug?)
On Monday, 22 August 2016 at 21:46:35 UTC, Engine Machine wrote: I'm sorry if it confuses you... it doesn't confuse me. Confuses? No. I do not know why you have to try and prove something that is a preference. Do you often get in to arguments with people about how ford is better than chevy or blonds are better than brunettes? You're wrong again. I don't try to prove anything, just answer your questions. But finally I understood your main goal: You don't want to see more than one 'class' keyword. You want that recursive class template automatically stops inheritance without any additional moves, such as specializations, static ifs and so on.
Re: Rebind template(bug?)
On Monday, 22 August 2016 at 19:56:08 UTC, ag0aep6g wrote: So this is just to avoid typing out `class Pug : Dog {...} class Dog : Animal {...} class Animal {...}`? This allows you to create different inheritance chains with the same components quickly and easily. I don't know any use case, but looks funny: T!("Animal", "Dog", "Pug") pug1; T!("Life", "Animal", "Four-legged", "Pug") pug2; T!("Dog", "Small", "Pug", ) smallPug;
Re: Rebind template(bug?)
On Monday, 22 August 2016 at 18:48:12 UTC, ag0aep6g wrote: You can take this further with template constraints. Gives it a more uniform appearance at the price of some repetition: class T() { int x; } class T(A...) : T!(A[0..$-1]) if (A.length > 0 && A[$-1] == "Animal") { int y; } class T(A...) : T!(A[0..$-1]) if (A.length > 0 && A[$-1] == "Dog") { int z; } class T(A...) : T!(A[0..$-1]) if (A.length > 0 && A[$-1] == "Pug") { int s; } Yes. And even simpler, if to change the order of template parameters: class T() { int x; } class T(string type : "Animal", A...) : T!A { int y; } class T(string type : "Dog", A...) : T!A { int z; } class T(string type : "Pug", A...) : T!A { int s; }
Re: Rebind template(bug?)
On Monday, 22 August 2016 at 18:04:43 UTC, Engine Machine wrote: How do you seriously think this is cleaner/simpler? 1. No extra encrypted things, such as InstantiateOrEmptySeq 2. Much more understandable. You have two classes. No. I have one template with two specializations. Class template and class is not the same thing. Their is no uniformity between them. They have the same name. This is the best uniformity. You have uniformity between all the derived classes then have a special case for the base class. A certain easy to follow pattern is set up but needlessly break it for one case. Why? Because it is the base class. It has no parent. Also this is the standard and well known pattern in template metaprogramming.
Re: Rebind template(bug?)
On Monday, 22 August 2016 at 00:43:00 UTC, Engine Machine wrote: The following code works and does what I want! template InstantiateOrEmptySeq(alias tmpl, args...) { alias Seq(T...)=T; static if (args.length > 0) alias InstantiateOrEmptySeq = tmpl!(args[0 .. $-1]); else alias InstantiateOrEmptySeq = Seq!(); } class T(A...) : InstantiateOrEmptySeq!(T, A) { static if (A.length == 0) { // Base class int x; } else static if (A[$-1] == "Animal") { int y; } else static if (A[$-1] == "Dog") { int z; } else static if (A[$-1] == "Pug") { int s; } else static assert(A[$-1]~" not a defined class of "~this.stringof); } Why don't you like a cleaner (in my opinion) solution? class T() { // Base class int x; } class T(A...) : T!(A[0..$-1]) { static if (A[$-1] == "Animal") { int y; } else static if (A[$-1] == "Dog") { int z; } else static if (A[$-1] == "Pug") { int s; } else static assert(A[$-1]~" not a defined class of "~this.stringof); }
Re: Rebind template(bug?)
On Sunday, 21 August 2016 at 19:29:26 UTC, Engine Machine wrote: I know you like to play the right or wrong game, but did you ever learn that a single example does not prove the truth of something? How about something more complex? Your demagogy will not help you learn the basics of the D language. And you're wrong again, young arrogant padawan.
Re: Rebind template
On Sunday, 21 August 2016 at 00:06:07 UTC, Engine Machine wrote: On Saturday, 20 August 2016 at 22:21:00 UTC, ag0aep6g wrote: On 08/21/2016 12:11 AM, Engine Machine wrote: Is there a way to rebind the arguments of a template? template foo(X) { // X is like A!(a,b,c) Y = Rebind!(X,d,e,f); // Y is like A!(d,e,f); } foo(A!(a,b,c)); ? template Rebind(alias instance, newArgs...) { import std.traits: TemplateOf; alias tmpl = TemplateOf!instance; alias Rebind = tmpl!newArgs; } This doesn't work because the rebound type is of type tmpl and not the original e.g., Rebind!(T!b, a) is tmpl!a not T!a. You are wrong. tmpl is just alias of template T. So tmpl!a and T!a are the same type. alias X = T!(int, short, char); alias Y = Rebind!(X, short, char, int); static assert(is(Y == T!(short, char, int))); // passes
Re: CT Inheritence structures
On Saturday, 20 August 2016 at 00:46:15 UTC, Engine Machine wrote: Any ideas? Something like this? mixin template TypeData(string type: "Animal") { int y; } mixin template TypeData(string type: "Dog") { int z; } mixin template TypeData(string type: "Pug") { int s; } template Type(string type, ARGS...) { static if(ARGS.length == 0) { class Type { mixin TypeData!type; } } else { class Type : Type!ARGS { mixin TypeData!type; } } } void main() { auto a = new Type!("Pug", "Dog", "Animal")(); Type!("Dog", "Animal") b = a; Type!("Animal") c = b; a.s = 1; b.z = 2; c.y = 3; pragma(msg, typeof(a)); pragma(msg, typeof(b)); pragma(msg, typeof(c)); } See result - https://dpaste.dzfl.pl/1a76490aaf55
Re: Possible bug
On Tuesday, 5 July 2016 at 13:48:50 UTC, ag0aep6g wrote: Something is also going wrong in dmd. There should be a deprecation message. Exactly.
Possible bug
ttt.d import std.string; void main() { lastIndexOf("aa","bb"); } rdmd ttt.d compiles successfully without any errors or warnings rdmd -dw ttt.d compiles successfully without any errors or warnings rdmd -de ttt.d /usr/include/dmd/phobos/std/string.d(1239): Error: template std.algorithm.searching.endsWith cannot deduce function from argument types !((a, b) => std.uni.toLower(a) == std.uni.toLower(b))(const(char)[], const(char)[]), candidates are: /usr/include/dmd/phobos/std/algorithm/searching.d(981): std.algorithm.searching.endsWith(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese) if (isBidirectionalRange!Range && Needles.length > 1 && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[0])) : bool) && is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[1..__dollar])) : uint)) /usr/include/dmd/phobos/std/algorithm/searching.d(1048): std.algorithm.searching.endsWith(alias pred = "a == b", R1, R2)(R1 doesThisEnd, R2 withThis) if (isBidirectionalRange!R1 && isBidirectionalRange!R2 && is(typeof(binaryFun!pred(doesThisEnd.back, withThis.back)) : bool)) /usr/include/dmd/phobos/std/algorithm/searching.d(1076): std.algorithm.searching.endsWith(alias pred = "a == b", R, E)(R doesThisEnd, E withThis) if (isBidirectionalRange!R && is(typeof(binaryFun!pred(doesThisEnd.back, withThis)) : bool)) /usr/include/dmd/phobos/std/algorithm/searching.d(1086): std.algorithm.searching.endsWith(alias pred, R)(R doesThisEnd) if (isInputRange!R && ifTestable!(typeof(doesThisEnd.front), unaryFun!pred)) ttt.d(4): Error: template instance std.string.lastIndexOf!(char, char) error instantiating
Re: mutable keyword
On Monday, 23 May 2016 at 11:05:34 UTC, Jonathan M Davis wrote: I don't know why you think that D violates its own rules frequently though. It's not perfect, but it usually does follow its own rules - and when it doesn't, we fix it (though not always as quickly as would be ideal). The most PITA for me is lacking mutable references for immutable classes. I like immutability and hate Rebindable. Also, how to embed reference counter into immutable class without violating immutability?
Re: mutable keyword
On Sunday, 22 May 2016 at 13:08:19 UTC, Jonathan M Davis wrote: Given how const and immutable work in D, having any portion of them be treated as mutable, becomes highly problematic. It could theoretically be done by having to mark such variables with an attribute and mark such types with a similar attribute so that the compiler knows that the type in question is not really following the rules of const or immutable and thus doesn't make any assumptions about it like it would normally, but it risks getting rather complicated, and Walter is most definitely not in favor of such an idea. He is absolutely adamant that const is useless unless it's fully const with no backdoors whatsoever. So, I'd be very surprised if any kind of @mutable were added to the language. Certainly, you'd have to have a very strong technical reason to convince him otherwise, and odds are that he's just going to tell you to not use const, if it's not going to work for the type to be const. Ha-ha. All this does not prevent immutable class to have mutable monitor. Why D so often violates its own rules?
Re: mutable keyword
On Saturday, 21 May 2016 at 21:49:23 UTC, Jonathan M Davis wrote: Rebindable is in kind of a weird grey area. It involves a union, not casting, and it's only ever mutating the class reference, not the object itself. Certainly, if it mutated the object, it would be undefined behavior, but it's just mutating the reference - but then again, the type system itself doesn't really differentiate between the two. So, I suspect that what it comes down to is that Rebindable is doing something that you really shouldn't, but because it's using a union rather than a cast, and it's so limited in what it's mutating, its behavior is effectively defined in the sense that the compiler has no leeway, but's probably still technically undefined. I don't know what Walter would say though. Certainly, if casting were involved, it would be undefined behavior without question, and it's not the sort of thing that you should be doing in your own code. [...] I agree. But I think we need something that allows *logical* const and immutable. Strict binding constness to physical memory constancy is not always necessary and sometimes even harmful.
Re: mutable keyword
On Friday, 20 May 2016 at 20:46:18 UTC, Jonathan M Davis wrote: Casting away const and mutating is undefined behavior in D. No D program should ever do it. Really? Mutating immutable is UB too, but look at std.typecons.Rebindable.
Re: mutable keyword
On Friday, 20 May 2016 at 17:28:55 UTC, Namespace wrote: But you can cheat: You can just cast const away: struct A { int id = 0; this(int id) { this.id = id; } void change() const { (cast() id)++; } } void main() { import std.stdio; A a = A(42); a.change(); writeln(a.id); }
Re: Why does array loses it internal capacity on length change?
Why is this happening...? For safety reasons. Your array can be shared between parts of application. ...how to avoid it? https://dlang.org/library/object/assume_safe_append.html
Re: About Immutable struct members and arrays.
On Thursday, 7 January 2016 at 00:19:12 UTC, anonymous wrote: On 06.01.2016 23:04, Jack Applegame wrote: move(bar, arr[0]); // ok I consider it a bug that this compiles. You're overwriting immutable data, which shouldn't be possible (without casting). https://issues.dlang.org/show_bug.cgi?id=15315 I think it isn't a bug. I'm not overwriting immutable data, I'm replacing old data with a new constructed one. I want to destruct old data and fill uninitialized raw memory with a new constructed one.
About Immutable struct members and arrays.
import std.algorithm; struct Bar { const int a; int b; } void main() { Bar[1] arr; Bar bar = Bar(1, 2); bar[0].b = 4; move(bar, arr[0]); // ok arr[1] = bar;// fail, why? move(Bar(1, 2), arr[0]); // fail, why source parameter isn't auto ref? }
GC greediness
On a server with 4GB of RAM our D application consumes about 1GB. Today we have increased server memory to 6 Gb and the same application under the same conditions began to consume about 3Gb of memory. Does GC greediness depend on available RAM?
Re: Can't understand how to do server response with vibed
On Saturday, 28 November 2015 at 18:03:13 UTC, Suliman wrote: Could anybody help me to understand how to complete HTTP response with vibed. I am sending POST request from AngularJS: $.post("http://127.0.0.1:8080/my";, total_result); where total_result is JSON string: [{"QID":3,"AID":3}, {"SubAID":[4]}, {"MinArea":"10","MaxArea":"90"}] Handler is look like: void action(HTTPServerRequest req, HTTPServerResponse res) { // res.statusCode = 201; } I know that I can set statusCode like code above, but problem that in Chrome console I am getting: POST http://127.0.0.1:8080/my 404 (Not Found) How can I pass to it (from vibed to browser) status code? If you do not send any response in handler, vibe.d will try to match next route (if any). So you should send any response (empty string for example). void action(HTTPServerRequest req, HTTPServerResponse res) { res.statusCode = 201; res.writeBody(""); }
Re: Multidimensional AA question
On Thursday, 26 November 2015 at 17:27:34 UTC, André wrote: My question now is: is there some more elegant solution to achieve this? Something like in C++ when you have std::map's of std::map's and just access the elements and the entry is created implicitly? No. But you can create a wrapper: http://dpaste.dzfl.pl/80ad84e8f010
Re: Multidimensional AA question
On Friday, 27 November 2015 at 04:21:41 UTC, Nicholas Wilson wrote: AA are weird in that AFAIK you need to "initialise" them before you try to look suff up in them else they crash. i.e. int[string] foo; // auto e = "1" in foo; // crash AA not initialised foo[ "blah"] = 0; foo.remove("blah"); auto e = "1" in foo; //doesn't crash It's not true. "Not initalzed" AA s just empty AA. http://dpaste.dzfl.pl/82b38a2ad504
Re: Is it a bug?
On Wednesday, 25 November 2015 at 09:31:15 UTC, John Colvin wrote: import std.range; import std.algorithm; import std.utf; void main() { char[64] arr; copy(chain("test1", "test2").byCodeUnit, arr[0..10].byCodeUnit); } I'll use byCodeUnit. Thanks.
Is it a bug?
This doesn't compile: import std.range; import std.algorithm; void main() { char[64] arr; copy(chain("test1", "test2"), arr[0..10]); } http://dpaste.dzfl.pl/24230ac02e6e
Re: Manually allocate delegate?
On Sunday, 12 July 2015 at 08:38:01 UTC, Tofu Ninja wrote: Is it even possible? You can use function instead delegate, and bind captured variables as struct: http://dpaste.dzfl.pl/6e23bbcfe17f auto bind(F: R function(ARGS), R, ARGS...)(F fn, ARGS args) @nogc { struct Functor { F fn; ARGS args; this(F fn_, ARGS args_) { fn = fn_; args = args_; } R opCall() { return fn(args); } } return Functor(fn, args); } import std.stdio; auto foo(int x) { static int bar(ref int x){ return x++; } return bind(&bar, x); } void main() { auto f1 = foo(5); auto f2 = foo(10); writefln("%s, %s, %s", f1(), f1(), f1()); writefln("%s, %s, %s", f2(), f2(), f2()); }
pure vs immutable
I believe that object constructed with pure constructor should be implicitly convertible to immutable. It is, but only for default constructor. class Foo { string s; this() pure { s = "fpp"; } this(string p) pure { s = p; } } void main() { auto foo1 = new immutable Foo(); // compiles auto foo2 = new immutable Foo("bar"); // fails }
Re: pure vs immutable
Heh immutable Foo foo2 = new Foo("bar"); // compiles
Re: char[] == null
I prefer import std.array; if(!arr.empty) {}
Re: char[] == null
On Thursday, 19 November 2015 at 03:53:48 UTC, Meta wrote: On Wednesday, 18 November 2015 at 23:53:01 UTC, Chris Wright wrote: [...] This is not true. Consider the following code: import std.stdio; void main() { int[] a = [0, 1, 2]; //4002E000 3 writeln(a.ptr, " ", a.length); //Is not triggered, obviously assert(a == null); a.length = 0; //4002E000 0 writeln(a.ptr, " ", a.length, " ", a); //Is not triggered, not as obvious assert(a == null); } There are cases when an array may have 0 length but a non-null pointer. If you want to check if an array's length is 0, you must explicitly check its length member. Checking if an array is equal to null only compares its pointer field to null. It does *not* check the length. Really? http://dpaste.dzfl.pl/b11346e8e341
Re: dmd 2.068 deducing purity
On Tuesday, 25 August 2015 at 18:03:21 UTC, Steven Schveighoffer wrote: https://issues.dlang.org/show_bug.cgi?id=14962 -Steve Thanks.
Re: dmd 2.068 deducing purity
On Tuesday, 25 August 2015 at 14:05:17 UTC, Steven Schveighoffer wrote: Can you post an example? import std.range; import std.algorithm; class Foo { int baz() { return 1;} void bar() { auto s = [1].map!(i => baz()); // compiles auto r = [1].map!(i => [1].map!(j => baz())); // Error: need 'this' for 'baz' of type 'int()' } }
dmd 2.068 deducing purity
Using lambdas in 2.068 becomes painful: import std.algorithm; struct Foo { int baz(int v) { static int id; return v + id++; } void bar() { auto arr1 = [1, 2, 3]; auto arr2 = [4, 5, 6]; arr1.map!(i => arr2.map!(j => baz(i + j)) ); } } void main() { } Error: pure function 'bug.Foo.bar.__lambda1!int.__lambda1.__lambda2' cannot call impure function 'bug.Foo.baz' Also after switching to dmd 2.068 I got many stupid errors in lambdas (defined inside class non-static functions): Error: need 'this' for '...' of type '...' I have no idea how to fix it and had to go back to 2.067.
Re: Bug or feature?
fix - https://github.com/D-Programming-Language/phobos/pull/3524
Re: std.algorithm each documentation terse
Also, map is lazy, but each isn't.
Re: goroutines vs vibe.d tasks
On Tuesday, 30 June 2015 at 17:37:38 UTC, Atila Neves wrote: Sleep will almost certainly pause and block the fiber. Vibe.d only switches between them when there's IO to be done or something else from the event loop. Sleep blocks the fiber, but not the event loop. Because it isn't core.thread.Thread.sleep, but vibe.core.core.sleep - http://vibed.org/api/vibe.core.core/sleep
goroutines vs vibe.d tasks
Just creating a bunch (10k) of sleeping (for 100 msecs) goroutines/tasks. Compilers go: go version go1.4.2 linux/amd64 vibe.d: DMD64 D Compiler v2.067.1 linux/amd64, vibe.d 0.7.23 Code go: http://pastebin.com/2zBnGBpt vibe.d: http://pastebin.com/JkpwSe47 go version build with "go build test.go" vibe.d version built with "dub build --build=release test.d" Results on my machine: go: 168.736462ms (overhead ~ 68ms) vibe.d: 1944ms (overhead ~ 1844ms) Why creating of vibe.d tasks is so slow (more then 10 times)???
Re: Bug or feature?
https://issues.dlang.org/show_bug.cgi?id=14751
Bug or feature?
I don't see any reason why it should not compile. import std.array; import std.range; import std.algorithm; class Foo { } void main() { auto result = iota(3).map!(i => new immutable Foo).array(); } /usr/include/dmd/phobos/std/conv.d(4028): Error: cannot implicitly convert expression (arg) of type immutable(Foo) to test.Foo /usr/include/dmd/phobos/std/conv.d(3931): Error: template instance std.conv.emplaceImpl!(immutable(Foo)).emplaceImpl!(immutable(Foo)) error instantiating /usr/include/dmd/phobos/std/array.d(115):instantiated from here: emplaceRef!(immutable(Foo), Foo, immutable(Foo)) test.d(9):instantiated from here: array!(MapResult!(__lambda1, Result))
Re: Mutable reference for immutable AA
I made trivial pull request - https://github.com/D-Programming-Language/phobos/pull/3341 RebindableAA!(immutable int[string]) aa = ["a": 1, "b": 2]; // works assert(aa["a"] == 1); // cool aa = ["a": 3, "b": 4]; // nice auto bb = aa; // yes bb = ["a": 4, "b": 5]; // super aa["a"] = 2; // error, good aa.remove("a");// error, very good
Mutable reference for immutable AA
I need mutable storage for immutable associative array. Just create new immutable AA and store it for future passing it between threads/fibers. First attempt: just immutable AA immutable aa = ["1":1, "2":1]; aa = ["1":1, "2":1]; // fail, can't assign a new AA Second attempt: mutable AA with immutable elements. immutable (int)[string] aa = ["1":1, "2":1]; aa = ["1":1, "2":1]; // sucess! aa["2"] = 2; // doesn't compile, is AA immutable? aa.remove("1"); // fail, this compiles, AA actually isn't immutable Third attempt: Rebindable Rebindable!(immutable int[string]) aa; // fail, Rebindable doesn't accept AAs
Re: How to create a mutable array of strings?
On Sunday, 17 May 2015 at 09:10:06 UTC, Dennis Ritchie wrote: It's uncomfortable: - char[][] s = [['f', 'o', 'o'], ['b', 'a', 'r']]; s[1][1] = 't'; auto s = ["foo".dup, "bar".dup]; s[1][1] = 't';
Re: Bug or feature?
Ok, it's a feature. Thanks.
Bug or feature?
code: class A { void test(int) {} } class B : A { void test() { super.test(1); // compiles test(10); // error } } Error: function B.test () is not callable using argument types (int)
SysTime.toISOExtString with timezone offset
I need current system time ISO string with timezone offset. For example "2015-04-20T11:00:44.735441+03:00" but Clock.currTime.toISOExtString doesn't write offset: "2015-04-20T11:00:44.735441+03:00" I found workaround, but it looks redundant and needs memory allocation: auto t = Clock.currTime; t.timezone = new immutable SimpleTimeZone(t.utcOffset); writeln(t.toISOExtString); Is there a simple way to get time ISO string with timezone offset?
Re: return the other functions of the void main()
I quite often have to write similar designs: - import std.stdio; void main() { auto a = [ 1, 2, 3, 4, 5 ]; foreach (e; a) { if (e == 4) { writeln("Yes"); return; } } writeln("No"); } - But is not it easier to write :) import std.stdio; void main() { auto a = [ 1, 2, 3, 4, 5 ]; foreach (e; a) { if (e == 4) { return writeln("Yes"); } } writeln("No"); } import std.stdio; import std.algorithm; import std.array; void main() { auto a = [ 1, 2, 3, 4, 5 ]; writeln(a.find(4).empty ? "No" : "Yes"); }
Re: I want to introduce boost_asio to dlang
On Thursday, 5 March 2015 at 06:05:56 UTC, zhmt wrote: I am a gameserver developer, my programming lang is java now. I want to change java to dlang, and I like boost_asio and it's coroutine, so, I want to create a binding of boost_asio. But I am not familiar with dlang, so I want to find someone help me, or develope this binding with me. I will put the asio binding on github, and opensource, and free. Anybody help or join? There is no need to do it. Just use http://vibed.org/ instead of boost::asio.
Re: "is" expression and type tuples
On Tuesday, 3 March 2015 at 17:49:24 UTC, bearophile wrote: That's 1 + n-1 :-) Could you please explain what does '1 + n-1' mean?
Re: "is" expression and type tuples
On Tuesday, 3 March 2015 at 16:42:22 UTC, bearophile wrote: But it should be not too much hard to implement it your code. Just use two is(), or use recursion (with splitting in two, and not 1 + n-1). Bye, bearophile I already have one: template Is(ARGS...) if(ARGS.length % 2 == 0) { enum N = ARGS.length/2; static if(N == 1) enum Is = is(ARGS[0] : ARGS[1]); else enum Is = is(ARGS[0] : ARGS[N]) && Is!(ARGS[1..N], ARGS[N+1..$]); }
"is" expression and type tuples
Seems like "is" expression doesn't support type tuples: pragma(msg, is(short : int)); // true enum Test(ARGS...) = is(ARGS[0..2] : ARGS[2..4]); pragma(msg, is(Test!(int, int, int, int))); // false pragma(msg, Test!(int, short, int, int)); // false Is it by design, or just not implemented?
std.conv.to purity
why std.conv.to is not pure? string foo(real v) pure { return v.to!string; } // Error: pure function 'foo' cannot call impure function 'std.conv.to!string.to!(real).to'
Re: The best way to compare floating point values.
On Saturday, 14 February 2015 at 10:23:48 UTC, Gary Willoughby wrote: I wrote a similar function here: https://github.com/nomad-software/dunit/blob/master/source/dunit/toolkit.d#L42 or using an epsilon value: https://github.com/nomad-software/dunit/blob/master/source/dunit/toolkit.d#L134 I don't know if they are useful to you? Very interesting. Thanks.
The best way to compare floating point values.
I wrote this function for comparing two floating point values: import std.math; import std.traits; bool isEqual(T)(T v1, T v2) if(isFloatingPoint!T) { return T.mant_dig - feqrel(v1, v2) < 2; } What do you think about it?
Re: struct vs built-in type
On Wednesday, 17 December 2014 at 08:09:44 UTC, Daniel Kozák via Digitalmars-d-learn wrote: This should work only with ref by spec I totally agree.