Re: Help optimizing code?
On Monday, 1 January 2018 at 15:09:53 UTC, Lily wrote: I started learning D a few days ago, coming from some very basic C++ knowledge, and I'd like some help getting a program to run faster. The code is here: https://github.com/IndigoLily/D-mandelbrot/blob/master/mandelbrot.d Right now it runs slower than my JavaScript Mandelbrot renderer on the same quality settings, which is clearly ridiculous, but I don't know what to do to fix it. Sorry for the lack of comments, but I can never tell what will and won't be obvious to other people. Hey! I happened to also write a Mandelbrot generator in D. It was based of the version given on rossetacode for C[0]. Some of the optimizations I used were: 0. Use LDC. It is significantly faster. 1. Utilize the fact that the Mandelbrot set is symmetric about the X axis.You can half the time taken. 2. Use std.parallelism for using multiple cores on the CPU 3. Use @fastmath of LDC 4. imageData.reserve(width * height * 3) before the loop 5. [1] is a great article on this specific topic For reference, on my 28W 2 core i5, a 2560x1600 image took about 2 minutes to render, with 500,000 iterations per pixel. [2] is my own version. [0]: https://rosettacode.org/wiki/Mandelbrot_set#PPM_non_interactive [1]: https://randomascii.wordpress.com/2011/08/13/faster-fractals-through-algebra/ [2]: https://github.com/Sirsireesh/Khoj-2017/blob/master/Mandelbrot-set/mandlebrot.d
Re: Help optimizing code?
On Tuesday, 2 January 2018 at 07:17:23 UTC, Uknown wrote: [snip] 0. Use LDC. It is significantly faster. 1. Utilize the fact that the Mandelbrot set is symmetric about the X axis.You can half the time taken. 2. Use std.parallelism for using multiple cores on the CPU 3. Use @fastmath of LDC 4. imageData.reserve(width * height * 3) before the loop 5. [1] is a great article on this specific topic [snip] Forgot to mention that since you already know some of the edges, you can avoid unnecessarily looping through some regions. That saves a lot of time
Re: Manually allocating a File
On Tuesday, 20 February 2018 at 15:21:59 UTC, Uknown wrote: On Tuesday, 20 February 2018 at 14:56:54 UTC, Chris M. wrote: void main() [snip] Never mind, I confused FILE* with File...
Re: Manually allocating a File
On Tuesday, 20 February 2018 at 14:56:54 UTC, Chris M. wrote: I'm doing this mainly for experimentation, but the following piece of code gives all sorts of errors. Hangs, segfaults or prints nothing and exits import std.stdio; import core.stdc.stdlib; void main() { auto f = cast(File *) malloc(File.sizeof); *f = File("test.txt", "r"); (*f).readln.writeln; // freeing is for chumps } I could have sworn I've done something similar recently and it worked, unfortunately I can't remember what the case was. This is what gdb gave me on a segfault Program received signal SIGSEGV, Segmentation fault. 0x77a56c32 in _D2rt5minfo__T17runModuleFuncsRevSQBgQBg11ModuleGroup8runDtorsMFZ9__lambda1ZQCkMFAxPyS6object10ModuleInfoZv () from /usr/lib64/libphobos2.so.0.78 So it looks like it's reaching the end of main. Past that I can't tell what's going on. Ideas? File * is a C standard library type. You mixed the C standard library and D standard library in a way that would not work. The correct way to initialize a File*: void main() { import core.stdc.stdlib; auto F = fopen("test.txt", "r"); scope_exit(fclose(f)); //Reading from the file: char[100] str; fgets(&s[0], s.length, f); } Honestly speaking though you should avoid using the C library when you can use th D standard library. You can read more on the C standard library and how to use it here: http://en.cppreference.com/w/c/io
Re: iota to array
On Sunday, 25 February 2018 at 06:22:03 UTC, psychoticRabbit wrote: On Sunday, 25 February 2018 at 05:40:19 UTC, Jonathan M Davis wrote: int[] intArr = iota(1, 11).array(); - Jonathan M Davis thanks! oh man. It's so easy to do stuff in D ;-) But this leads me to a new problem now. When I run my code below, I get ints printed instead of doubles?? - module test; import std.stdio : writeln; import std.traits : isArray; import std.array : array; import std.range : iota; void main() { int[] intArr = iota(1, 11).array(); // 1..10 double[] doubleArr = iota(1.0, 11.0).array(); // 1.0..10.0 char[] charArr = iota('a', '{').array(); // a..z printArray(intArr); printArray(doubleArr); // why is it printing ints instead of doubles?? printArray(charArr); } void printArray(T)(const ref T[] a) if (isArray!(T[])) { foreach(t; a) writeln(t); } - 2 Things: 1. You can just use writeln to directly print Arrays. If you want a specific format for the array you can use writef/writefln 2. By default, writeln will print [1, 2, 3] when your array contains [1.0, 2.0, 3.0], since thats considered neater. You can use writefln to address that. You can see this here: https://run.dlang.io/is/bNxIsH You can read more about format strings here: https://dlang.org/phobos/std_format.html#format-string
Re: Speed of math function atan: comparison D and C++
On Monday, 5 March 2018 at 06:01:27 UTC, J-S Caux wrote: On Monday, 5 March 2018 at 05:40:09 UTC, rikki cattermole wrote: On 05/03/2018 6:35 PM, J-S Caux wrote: I'm considering shifting a large existing C++ codebase into D (it's a scientific code making much use of functions like atan, log etc). I've compared the raw speed of atan between C++ (Apple LLVM version 7.3.0 (clang-703.0.29)) and D (dmd v2.079.0, also ldc2 1.7.0) by doing long loops of such functions. I can't get the D to run faster than about half the speed of C++. Are there benchmarks for such scientific functions published somewhere Gonna need to disassemble and compare them. atan should work out to only be a few instructions (inline assembly) from what I've looked at in the source. Also you should post the code you used for each. So the codes are trivial, simply some check of raw speed: double x = 0.0; for (int a = 0; a < 10; ++a) x += atan(1.0/(1.0 + sqrt(1.0 + a))); for C++ and double x = 0.0; for (int a = 0; a < 1_000_000_000; ++a) x += atan(1.0/(1.0 + sqrt(1.0 + a))); for D. C++ exec takes 40 seconds, D exec takes 68 seconds. Depending on your platform, the size of `double` could be different between C++ and D. Could you check that the size and precision are indeed the same? Also, benchmark method is just as important as benchmark code. Did you use DMD or LDC as the D compiler? In this case it shouldn't matter, but try with LDC if you haven't. Also ensure that you've used the right flags: `-release -inline -O`. If the D version is still slower, you could try using the C version of the function Simply change `import std.math: atan;` to `core.stdc.math: atan;` [0] [0]: https://dlang.org/phobos/core_stdc_math.html#.atan
Re: Speed of math function atan: comparison D and C++
On Tuesday, 6 March 2018 at 08:20:05 UTC, J-S Caux wrote: On Tuesday, 6 March 2018 at 07:12:57 UTC, Robert M. Münch wrote: On 2018-03-05 20:11:06 +, H. S. Teoh said: [snip] Now, with Uknown's trick of using the C math functions, I can reconsider. It's a bit of a "patch" but at least it works. I'm glad I could help! In an ideal world, I'd like the language I use to: - have double-precision arithmetic with equal performance to C/C++ - have all basic mathematical functions implemented, including for complex types - *big bonus*: have the ability to do extended-precision arithmetic (integer, but most importantly (complex) floating-point) on-the-fly if I so wish, without having to rely on external libraries. D has std.complex and inbuilt complex types, just like C [0][1]. I modified the mandelbrot generator on Wikipedia, using D's std.complex and didn't have too much of an issue with performance.[2] Also, std.bigint and mir might be of interest to you.[3] C++ was always fine, with external libraries for extended precision, but D is so much more pleasant to use. Many of my colleagues are switching to e.g. Julia despite the performance costs, because it is by design a very maths/science-friendly language. D is however much closer to a whole stack of existing codebases, so switching to it would involve much less extensive refactoring. Theres a good chance D can interface with those libraries you mentioned... [0]: https://dlang.org/phobos/std_complex.html [1]: https://dlang.org/phobos/core_stdc_complex.html [2]: https://github.com/Sirsireesh/Khoj-2017/blob/master/Mandelbrot-set/mandelbrot.d [3]: https://github.com/libmir
Re: See docs compiler message
On Tuesday, 6 March 2018 at 14:28:52 UTC, ixid wrote: /opt/compilers/dmd2/include/std/algorithm/iteration.d(663): Deprecation: function `std.range.Transposed!(string[], cast(TransverseOptions)0).Transposed.save` is deprecated - This function is incorrect and will be removed November 2018. See the docs for more details. If it's going to say 'See the docs' how about linking the docs or even just specifying which docs it's referring to? I agree that compiler error messages should be improved. If you are still wondering though, https://dlang.org/phobos/std_range.html#transposed is the relevant documentation
Re: LDC / BetterC / _d_run_main
On Saturday, 10 March 2018 at 12:00:12 UTC, Richard wrote: On Saturday, 10 March 2018 at 07:54:33 UTC, Mike Franklin wrote: On Saturday, 10 March 2018 at 02:25:38 UTC, Richard wrote: [snip] Based on the above this seems to work fine so I'll use this since it's the simplest option. ``` extern(C) int main(int argc, char** argv) { return d_main(); } int d_main() { // Do stuff } ``` You can simplify it further: ``` extern(C) int main(int argc, char** argv { //Do stuff } ``` This compiles but main() is never called btw ``` import core.stdc.stdio; private alias extern(C) int function(char[][] args) MainFuncType; extern (C) int _d_run_main(int argc, char **argv, void* mainFunc) { MainFuncType mFunc = cast(MainFuncType) mainFunc; return mFunc(null); } int main() { // Do stuff } ``` I tried compiling with ldc2 -defaultlib= -debuglib= -mtriple=thumb-none-linux-eabi -mcpu=cortex-m3 --od=. -c -betterC main.d I think you should not put `-betterC` since you are trying to use _d_run_main, which is only called when in regular mode.
Re: Why does struct initializer works for arrays but not for associative arrays?
On Wednesday, 14 March 2018 at 13:36:51 UTC, Andre Pany wrote: Hi, I do not understand why struct initializer works for arrays but not for associative arrays: struct Bar { string s; } struct Foo { Bar[string] asso; Bar[] arr; } void main() { Foo foo = { arr: [{s: "123"}], asso: ["0": {s: "123"}] // does not work }; } The coding for both types of arrays looks very similiar: https://github.com/dlang/dmd/blob/9ed779a7d68d2ac489338cc4758c10d0cb169b39/src/dmd/initsem.d#L634 I cannot spot the difference. Kind regards André This might just be a bug. Changing the initializer to an explicit call to Bar constructor compiles just fine https://run.dlang.io/is/nuuolx Even just doing Foo foo = { arr: [{s: "123"}], asso: ["0": {"123"}] // does not work };
Re: auto-decoding
On Sunday, 1 April 2018 at 01:19:08 UTC, auto wrote: What is auto decoding and why it is a problem? Auto-decoding is essentially related to UTF representation of Unicode strings. In D, `char[]` and `string` represent UTF8 strings, `wchar[]` and `wstring` represent UTF16 strings and `dchar[]` and `dstring` represent UTF32 strings. You need to know how UFT works in order to understand auto-decoding. Since in practice most code deals with UTF8 I'll explain wrt that. Essentially, the problem comes down to the fact that not all the Unicode characters are representable by 8 bit `char`s (for UTF8). Only the ASCII stuff is represented by the "normal" way. UTF8 uses the fact that the first few buts in a char are never used in ASCII, to tell how many more `char`s ahead that character is encoded in. You can watch this video for a better understanding[0]. By default though, if one were to traverse a `char` looking for characters, they would get unexpected results with Unicode data Auto-decoding tries to solve this by automatically applying the algorithm to decode the characters to Unicode "Code-Points". This is where my knowledge ends though. I'll give you pros and cons of auto-decoding. Pros: * It makes Unicode string handeling much more easier for beginners. * Much less effort in general, it seems to "just work™" Cons: * It makes string handling slow by default * It may be the wrong thing, since you may not want Unicode code-points, but graphemes instead. * Auto-decoding throws exceptions on reaching invalid code-points, so all string handling code in general throws exceptions. If you want to stop auto-decoding, you can use std.string.representation like this: import std.string : representation; auto no_decode = some_string.representation; Now no_decode wont be auto-decoded, and you can use it in place of some_string. You can also use std.utf to decode by graphemes instead. You should also read this blog post: https://jackstouffer.com/blog/d_auto_decoding_and_you.html And this forum post: https://forum.dlang.org/post/eozguhavggchzzruz...@forum.dlang.org [0]: https://www.youtube.com/watch?v=MijmeoH9LT4
Re: What is the equivalent of C++'s std::optional and std::nullopt in D?
On Tuesday, 3 April 2018 at 02:10:09 UTC, helxi wrote: For reference: https://en.cppreference.com/w/cpp/utility/optional Nullable!T would be the closest thing: https://dlang.org/phobos/std_typecons.html#Nullable I'm not sure how comparable they are though.
Re: Why toUTF8 not accept wchar[] as argument?
On Tuesday, 3 April 2018 at 02:31:15 UTC, Uknown wrote: On Tuesday, 3 April 2018 at 02:24:08 UTC, Domain wrote: wchar[10] buffer; toUTF8(buffer); Error: template `std.utf.toUTF8` cannot deduce function from argument types `!()(wchar[10])`, candidates are: /dlang/dmd/linux/bin64/../../src/phobos/std/utf.d(2713): `std.utf.toUTF8(S)(S s) if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S))` I know buffer.idup is OK. But why? That's very inconvenient. What you need to do is slice your buffer. So your call will become like this: --- toUTF8(buffer[]); --- Now it will work as expected. I should mention that you need to slice any static array when passing to functions that expect ranges
Re: Why toUTF8 not accept wchar[] as argument?
On Tuesday, 3 April 2018 at 02:24:08 UTC, Domain wrote: wchar[10] buffer; toUTF8(buffer); Error: template `std.utf.toUTF8` cannot deduce function from argument types `!()(wchar[10])`, candidates are: /dlang/dmd/linux/bin64/../../src/phobos/std/utf.d(2713): `std.utf.toUTF8(S)(S s) if (isInputRange!S && !isInfinite!S && isSomeChar!(ElementEncodingType!S))` I know buffer.idup is OK. But why? That's very inconvenient. What you need to do is slice your buffer. So your call will become like this: --- toUTF8(buffer[]); --- Now it will work as expected.
Re: Taming templates and mixin magic: type inpector helper in D/Phobos?
On Wednesday, 4 April 2018 at 05:28:57 UTC, Carlos Navarro wrote: As a newbie in D (and making a lots of mistakes), I've found myself relying heavily in the use of a rudimentary type inspector to visualize my templated code instantiations. It's simple and incomplete as hell but good enough to see what happens under the hood quickly. QUESTION: Is there a function like that already in D? //real-life example goodEnoughTypeInspector!Human; goodEnoughTypeInspector!(Database!Human); //compile-time output Inspecting type: Human - public string name - public string address - public bool active Inspecting type: Database!(Human) - private string[] name - private string[] address - private bool[] active - public pure nothrow @nogc @safe ulong() count - public void insert you might want to check std.traits [0] and __traits [1]. They both contain functions that may be useful. To get members you could use __traits(allMembers, MyTemplate!SomeType); Just check through the docs for relevant functions. You can then compose the relevant function. I wrote a basic version you can play with [2]. [0]: https://dlang.org/phobos/std_traits.html [1]: https://dlang.org/spec/traits.html [2]: https://run.dlang.io/is/COZ89T
Re: c2 classes
On Friday, 6 April 2018 at 14:43:25 UTC, Ali wrote: On Friday, 6 April 2018 at 14:31:49 UTC, Alex wrote: On Friday, 6 April 2018 at 13:41:50 UTC, aerto wrote: [...] A question from me, since I am also still learning D what is the difference between those following two declarations UUsers[int] uid; UUsers[] uid; T[U] declares an Associative Array but T[] declares a Dynamic Array. Some examples will help: --- void main() { char[int] s1; char[] s2; s1[1] = 'c'; //allowed, it is an Associative array. key 1 stores value 'c' s2[0] = 1; //error: out of bounds of array s2 } --- You can check out the spec[0] and the tour[1] [0]: https://dlang.org/spec/hash-map.html [1]: https://tour.dlang.org/tour/en/basics/associative-arrays
Re: Function template argument deduction
On Saturday, 7 April 2018 at 05:10:05 UTC, Paul Backus wrote: I'm playing around with functional programming in D, and have run into a problem with the following code: [...] I don't see the error you are talking about: https://run.dlang.io/is/XWPIc1 Are you using the latest compiler?
Re: Function template argument deduction
On Saturday, 7 April 2018 at 05:58:10 UTC, Paul Backus wrote: On Saturday, 7 April 2018 at 05:46:07 UTC, Uknown wrote: I don't see the error you are talking about: https://run.dlang.io/is/XWPIc1 Are you using the latest compiler? Compile with -unittest. And yes; I'm using DMD 2.079.0. Now I feel silly. Anyway, I played around with your code. One thing I found was `cons.head` returns a `T`, which can't be appended to a string. You can fix this with `cons.head.to!string`, where `to` is from std.conv. I'm not sure why IFTI isn't deducing `T` to be `int` though. Hopefully some one else can help out here. What I did notice though is that when `string list2string(T)(List!T list)` was changed to `string list2string(T)(VariantN!(16LU, Nil, Tuple!(T, "head", This*, "tail")) list)` The compiler correctly deduce `T` to be `int`
Re: Checking if a function pointer is set or null
On Monday, 9 April 2018 at 00:25:08 UTC, solidstate1991 wrote: Would the if(!(myFunctionPointer is null)){} work is I intended? Yes, that works as you expect https://run.dlang.io/is/ZTtm0P
Re: Escaping address of
On Wednesday, 11 April 2018 at 16:25:20 UTC, Jonathan M Davis wrote: [...] Adding a destructor makes the compiler return an error about lifetimes, with or without -dip1000 https://run.dlang.io/is/ddXqNu
Re: Using iteration / method chaining / etc on multi-dimensional arrays
On Thursday, 12 April 2018 at 15:38:34 UTC, Chris Katko wrote: I googled but couldn't find any clear solution. I've got a 2-D array of strings read from a text file I parsed. So it's like 0 1 15 0 0 2 12 1 0 0 ... 0 1 0 10 0 They come in with spaces, so I join into an array between them. But then the last ones have a newline \n on the end, which explodes the to! type conversion. If it was a single array, I could simply do: string [25] test; test.each((ref n) => n.stripRight()); But how do you do that when it's a 2-D array? I'm looking not just for this case, but the generate case of iterating / applying filters to 2-D arrays. Thanks. I think something like this would work: test.each((ref s) => s.each((ref n) => n.stripRight())); Essentially, get each 1D array from the 2D array, and then apply the algorithms on that. There's probably a better way though
Re: dynamically allocating on the stack
On Saturday, 21 April 2018 at 07:37:50 UTC, Mike Franklin wrote: Does D have some way to dynamically allocate on the stack? I'm looking for something roughly equivalent to the following C code. int doSomething(size_t len) { char stackBuffer[len + 1]; doSomethingElse(stackBuffer); } Thanks, Mike The language itself doesn't have something, but you could use `alloca`: --- void doSomething(size_t len) { import core.stdc.stdlib, core.stdc.stdio; auto stackBuffer = (cast(char*) alloca(char.sizeof * len + 1))[0 .. len + 1]; stackBuffer[0] = 'H'; stackBuffer[1] = '\0'; printf("%.*s", stackBuffer.ptr); } void main() { doSomething(2); } ---
Re: dynamically allocating on the stack
On Sunday, 22 April 2018 at 01:07:44 UTC, Giles Bathgate wrote: On Saturday, 21 April 2018 at 19:06:52 UTC, Steven Schveighoffer wrote: alloca is an intrinsic, and part of the language technically -- it has to be. Why does: scope c = new C(); // allocate c on stack scope a = new char[len]; // allocate a via gc? Its a special case for classes. Makes them usable without the GC.
Re: How to use std.meta.Filter?
On Saturday, 21 April 2018 at 17:46:05 UTC, Dr.No wrote: On Saturday, 21 April 2018 at 17:15:47 UTC, Jonathan M Davis wrote: On Saturday, April 21, 2018 16:05:22 Dr.No via Digitalmars-d-learn wrote: import std.meta : Filter; enum isNotReservedSymbol(string name) = name != "none" && name != "lastToken"; enum string[] members = staticMembers!Token; static foreach(member; Filter!(isNotReservedSymbol, members)) {{ This return the error: Error: template instance `pred!(["none", "word", "n", "digits", "name", /* my whole array here */ ]) does not match template declaration isNotReservedSymbol(string name) how should have isNotReservedSymbol be defined? std.meta.Filter operates on an AliasSeq, not a dynamic array. If you have an array, then you can just use std.algorithm.iteration.filter with a normal lambda. - Jonathan M Davis I've tried use normal filter - albeit i'm willing to do all that at runtin, but I got f cannot be read at compile time. static foreach(member; staticMembers!Token.filter!(f => isNotReservedSymbol!(member)) If you are confused by why some things work during compilation and others don't, I would encourage you to read https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time Its a nice article explaining how there are two "compile-time" steps where code can be executed.
Re: Passing to c++ std::string and vector
On Monday, 30 April 2018 at 01:07:35 UTC, NewUser wrote: Hi, How do I pass a d string to a c++ std::string? NewUser There is no trivial way to do this as far as I'm aware, mostly due to C++ mangling issues in DMD. You can try calypso [0] or dpp [1], which might work. You can also see this PR[2] [0]: https://wiki.dlang.org/Calypso [1]: https://forum.dlang.org/post/kbcdppawjtcdkdtdz...@forum.dlang.org [2]: https://github.com/dlang/druntime/pull/1316
Re: Is build a 64 bit version worth if I'm looking for better perfomance?
On Tuesday, 1 May 2018 at 22:48:08 UTC, Dr.No wrote: Looking for make application run fast as possible, aside optimization in the source code, is using 64 bit over 32 really worth? With the GC yes, since false pointers become less of an issue. Also you get to take full advantage of the target CPU. The vast majority of home computers today use 64 bit. You'll also be able to take advantage of more optimizations since the compiler can assume more features are available. But you will *probably* get better performance from profiling + optimizing than 32 bit -> 64 bit.
Re: C++ / const class pointer signature / unable to find correct D syntax
On Friday, 4 May 2018 at 07:49:02 UTC, Robert M. Münch wrote: I have a static C++ and can't make it to get a correct binding for one function: DMD: public: unsigned int __cdecl b2d::Context2D::_begin(class b2d::Image & __ptr64,class b2d::Context2D::InitParams const * __ptr64 const) __ptr64 LIB: public: unsigned int __cdecl b2d::Context2D::_begin(class b2d::Image & __ptr64,class b2d::Context2D::InitParams const * __ptr64) __ptr64 So I somehow get some more const from D. This is the code I used: final uint _begin(ref Image image, const(InitParams) initParams); Which creates a const pointer to a const class signature. But it should only be a const pointer. Any idea how to solve this? The problem is that const in D is transitive. That means T * const from C++ is not expressible in D. Any reference through a const becomes const. To use it, IMO your best bet is to make a wrapper function on the C++ side like this: unsigned int __cdecl b2d::Context2D::_begin(class b2d::Image & im,class b2d::Context2D::InitParams const * const InitParams) { return //the call to the original c++ function } Alternatively you can use dpp, or dstep or some similar tool to try and let the tool create bindings. As a last ditch, you can force the mangle to match by using pragma(mangle, ...) like this: pragma(mangle, _ZactualMangleFromC++Compiler) final uint _begin(ref Image image, const(InitParams) initParams);
Re: Extra .tupleof field in structs with disabled postblit blocks non-GC-allocation trait
On Thursday, 10 May 2018 at 11:06:06 UTC, Per Nordlöw wrote: On Wednesday, 9 May 2018 at 21:09:12 UTC, Meta wrote: It's a context pointer to the enclosing function/object/struct. Mark the struct as static to get rid of it. Ok, but why an extra void* for `S.tupleof` and not for `T.tupleof` which is also scoped inside a unittest? I'm guessing T is a POD, so it doesn't need a context pointer, whereas S is not counted as a POD since a member function was @disabled.
Re: Temporary file creation for unittests
On Friday, 18 May 2018 at 15:16:52 UTC, Russel Winder wrote: Hi, What's the current official position on how to create temporary files for use during a unittest. I found https://github.com/dlang/phobos/pull/5788 but it seems to be languishing in the "we have discussed all the issues that no-one will ever have a problem with" phase. What to do between now and when there is an LDC release that has the result of the merge? You could use libc's tmpfile with std.stdio.File until a D alternative pops up. http://en.cppreference.com/w/c/io/tmpfile
Re: is ==
On Friday, 18 May 2018 at 23:53:12 UTC, IntegratedDimensions wrote: Why does D complain when using == to compare with null? Is there really any technical reason? if one just defines == null to is null then there should be no problem. It seems like a pedantic move by who ever implemented it and I'm hoping there is actually a good technical reason for it. D only complains of this when you use ref types (classes or AAs). For e.g: --- test.d void main() { int * p; assert (p == null && p is null); class C { int x; } C c; assert (c is null); assert (c == null); //error, c is a reference, so there is confusion between opEquals and null check } ---
Re: Conditionally set nothrow: for a block of code.
On Thursday, 24 May 2018 at 18:51:31 UTC, Mike Franklin wrote: I'm trying to find a way to declare a block of code `nothrow:` when compiling with -betterC, but not `nothrow` when not compiling with -betterC. The solution is needed for this PR: https://github.com/dlang/druntime/pull/2184/files#r188627707 [...] Given that the PR above is for object.d, I can't turn the entire object.d source file into a string and conditionally mix that in. Does anyone have a solution to this? Thanks, Mike I think conditional application of attributes would be something useful. Something like this: version (D_BetterC) enum BetterC = true; else enum BetterC = false; nothrow!(BetterC): ... Of course that would require a DIP though
How to sort byCodeUnit.permutations.filter(...)
I wrote a small program for Project Euler problem 41 ( https://projecteuler.net/problem=41 ). --- project_euler_41.d void main() { import math_common : primesLessThan; import std.stdio : writeln; import std.conv : parse; import std.algorithm : permutations, canFind, filter, each, sort; import std.utf : byCodeUnit; import std.range : assumeSorted; import std.array : array; auto primes = primesLessThan(9_999_999UL).assumeSorted; "1234567".byCodeUnit .permutations .filter!(a => primes.canFind(a.parse!uint)) .each!(a => a.writeln); } --- The problem is this prints a list of numbers. The task requires only the largest, so the intuitive fix is to add `.array.sort[$ - 1].writeln` in place of the `each`, but this prints an array of `1234567`s instead of the permutations. Does anyone know how to sort the filter result without modifying the individual results?
Re: How to sort byCodeUnit.permutations.filter(...)
On Monday, 11 June 2018 at 04:12:57 UTC, Adam D. Ruppe wrote: On Monday, 11 June 2018 at 04:06:44 UTC, Uknown wrote: The problem is this prints a list of numbers. The task requires only the largest, so the intuitive fix I would just pull the max out of it. http://dpldocs.info/experimental-docs/std.algorithm.searching.maxElement.2.html Thanks for your reply. I completely forgot about maxElement. I used it, but it prints 1234567, not the permutations. The same happens when using array. Why are the strings getting modified? The same happens with this: "123".byCodeUnit.permutations.writeln;//[123, 213, 312, 132, 231, 321] "123".byCodeUnit.permutations.array.writeln;//[123, 123, 123, 123, 123, 123] Seems odd. Is this a bug or expected behaviour?
Re: How to sort byCodeUnit.permutations.filter(...)
On Tuesday, 12 June 2018 at 14:21:48 UTC, Adam D. Ruppe wrote: On Monday, 11 June 2018 at 04:39:54 UTC, Uknown wrote: Why are the strings getting modified? I'm guessing it reuses a buffer as it iterates. "123".byCodeUnit.permutations.writeln;//[123, 213, 312, 132, 231, 321] [...] "1234567".byCodeUnit .permutations .map!(to!int) .filter!(a => primes.canFind(a)) .maxElement that should do it too. I solved the problem by piping the output to `sort`, but your workaround is useful. I'll submit a bug report on this ASAP. Thanks for your help!
Re: Which character set does D use?
On Wednesday, 13 June 2018 at 23:34:02 UTC, Murilo wrote: Does D use ASCII or UNICODE? It seems to use ASCII since it causes error whenever I use a non-ASCII character. Your system might be misconfigured. D can use UTF-8 (Unicode) too. See https://dlang.org/spec/lex.html#source_text
Re: Preferred Alias Declaration Style
On Wednesday, 27 June 2018 at 10:22:38 UTC, Vijay Nayar wrote: Most of the documentation at https://dlang.org/spec/declaration.html#alias uses examples of the form: `alias aliasName = other;`, where `aliasName` becomes the new name to reference `other`. Alternatively, one may write `alias other aliasName;`. My understanding is that the syntax with `=` is the preferred one stylistically. However, when it comes to `alias this` declarations, the only syntax supported is `alias other this;`, and one cannot write `alias this = other;`. Does this mean that the `alias other aliasName;` syntax is preferred, or does it simply mean that this is a low priority issue that hasn't been addressed yet? `alias Alias = SomeType;` is preferred. It is the new style, and is more clear on what is the alias and what is the new type, especially when complex types come into play. For `alias this` though, there is only one syntax, `alias other this;`, since it does something conceptually different from regular aliases.
Getting the underlying range from std.range.indexed, with elements in swapped order, when Indexed.source.length == Indexed.indices.length
Title says it all. Is there a trivial way to do this?
Re: Preferred Alias Declaration Style
On Wednesday, 27 June 2018 at 14:01:06 UTC, Basile B. wrote: On Wednesday, 27 June 2018 at 12:25:26 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 10:22:38 UTC, Vijay Nayar wrote: [...] aliasing a function type only works with the old syntax too: alias void proto_identifier(); Very unfriendly syntax. Impossible to express with AliasDeclarationY (aka "the new alias syntax"). You can use this syntax for functions : `alias proto_identifier = void function();`
Re: Getting the underlying range from std.range.indexed, with elements in swapped order, when Indexed.source.length == Indexed.indices.length
On Wednesday, 27 June 2018 at 14:21:39 UTC, Alex wrote: On Wednesday, 27 June 2018 at 13:27:46 UTC, Uknown wrote: Title says it all. Is there a trivial way to do this? There are https://dlang.org/library/std/algorithm/mutation/reverse.html and https://dlang.org/library/std/range/retro.html both require a bidirectional range, which Indexed, luckily is. I wasn't clear enough. I meant getting back the underlying `Source` range with _its_ elements in the order that the indices specify. This wouldn't be possible in the generic case, but the special case when indices.length == source.length, it should be possible. So indexed(myRange, [2, 3, 5, 1, 4]).sourceWithSwappedElements should return a typeof(myRange) with the elements swapped in that order.
Re: Preferred Alias Declaration Style
On Wednesday, 27 June 2018 at 14:29:18 UTC, Basile B. wrote: On Wednesday, 27 June 2018 at 14:23:25 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 14:01:06 UTC, Basile B. wrote: On Wednesday, 27 June 2018 at 12:25:26 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 10:22:38 UTC, Vijay Nayar wrote: [...] Nah it's not the same thing ;) void main() { alias void proto_identifier_old(); alias proto_identifier_new = void function(); assert(!is(proto_identifier_old == proto_identifier_new)); // passes } - proto_identifier_new is a function type (stuff) - proto_identifier_new is a function **pointer** type (e.g &stuff) Actually my answer was more informative because i reported this limitation years ago, see https://issues.dlang.org/show_bug.cgi?id=16020. Didn't know that, I assumed that the old style also declared a function pointer
Re: Getting the underlying range from std.range.indexed, with elements in swapped order, when Indexed.source.length == Indexed.indices.length
On Wednesday, 27 June 2018 at 14:50:25 UTC, Alex wrote: On Wednesday, 27 June 2018 at 14:29:33 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 14:21:39 UTC, Alex wrote: On Wednesday, 27 June 2018 at 13:27:46 UTC, Uknown wrote: [...] I see. Ok, one possibility is source = indexed(source, indices).array; but I assume you want something without extra allocation, right? This doesn't work for some reason. "123".byCodeUnit.permutations.array.writeln //[123, 123, 123, 123, 123, 123]
Re: Getting the underlying range from std.range.indexed, with elements in swapped order, when Indexed.source.length == Indexed.indices.length
On Wednesday, 27 June 2018 at 15:18:05 UTC, Alex wrote: On Wednesday, 27 June 2018 at 15:07:57 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 14:50:25 UTC, Alex wrote: On Wednesday, 27 June 2018 at 14:29:33 UTC, Uknown wrote: On Wednesday, 27 June 2018 at 14:21:39 UTC, Alex wrote: On Wednesday, 27 June 2018 at 13:27:46 UTC, Uknown wrote: [...] This would: ["123".byCodeUnit.permutations].joiner.writeln; Thanks. This works, but it still seems silly that permutations doesn't just return a range with front returning the original type
Parallelizing factorial computation
I was messing and tried comparing the performance of different ways to compute the factorial of a number. Here's the benchmark results: recursive: 244 ms, 283 μs, and 2 hnsecs loop: 241 ms, 412 μs, and 3 hnsecs parallel: 1 sec, 784 ms, 829 μs, and 5 hnsecs https://run.dlang.io/is/uyVlqu I was quite surprised by the fact that parallel ran so much slower than recursive and loop implementations. Does anyone know why?
Re: Parallelizing factorial computation
On Friday, 24 August 2018 at 20:43:46 UTC, Peter Alexander wrote: On Friday, 24 August 2018 at 13:04:47 UTC, Uknown wrote: I was quite surprised by the fact that parallel ran so much slower than recursive and loop implementations. Does anyone know why? n = 100 is too small to see parallelism gains. Try n = 1 https://run.dlang.io/is/XDZTSd I was using n = 1 originally, I reduced it because that wasn't running on run.dlang. Tried this again on my machine and you were right.
Re: pure void* memset(return void* s, int c, size_t n)?
On Wednesday, 6 September 2017 at 06:09:46 UTC, Psychological Cleanup wrote: What is the return doing there? The return implies that the function will return the parameter `s` after it has done whatever it needs to. It is useful for the compiler to do escape analysis or So memset would be something like this: pure void * memset(return void * s, int c, size_t n) { foreach (i; 0 .. n) (cast(char *) s)[i] = cast(char) c; return s; }