Re: I like dlang but i don't like dub
On Monday, 21 March 2022 at 10:29:53 UTC, Alexandru Ermicioi wrote: On Friday, 18 March 2022 at 21:04:03 UTC, H. S. Teoh wrote: On Fri, Mar 18, 2022 at 11:16:51AM -0700, Ali Çehreli via Digitalmars-d-learn wrote: tldr; I am talking on a soap box with a big question mind hovering over on my head: Why can't I accept pulling in dependencies automatically? Because it's a bad idea for your code to depend on some external resource owned by some anonymous personality somewhere out there on the 'Net that isn't under your control. True, and because of that you can try and have local/company wide dub registry (if not, should be added support for), in which packages are verified by you/your company, eliminating the problem of net not being under control. Best regards, Alexandru. That's actually possible right now, in the easiest case you can have a directory of package zip files. Isn't that best practice in all language eco systems.
Re: I like dlang but i don't like dub
On Monday, 21 March 2022 at 09:25:56 UTC, Dadoum wrote: On Friday, 18 March 2022 at 04:13:36 UTC, Alain De Vos wrote: Dlang includes some good ideas. But dub pulls in so much stuff. Too much for me. I like things which are clean,lean,little,small. But when i use dub it links with so many libraries. Are they really needed ? And how do you compare to pythons pip. Feel free to elaborate. Personally I use CMake, it allows me to access to C and C++ libraries while still being able to use small Dub libraries. Also everyone knows how to build a project with CMake nowadays. I do the same with meson and I wish dub would be easier to integrate into third party build systems. The first problem with dub is, that it doesn't really let you decide where it puts stuff. There is `--cache`, but that doesn't accept an path either and does not guarantee that afterwards everything you need is there. For example if you `dub fetch A --cache=local` and some dependencies of A are already under $HOME/.dub, you won't have them locally afterwards. There is a workaround for this though: `HOME=. dub fetch A`. A second problem is that `dub describe` returns paths to the packages directories not to the actual build directories, thus you can only use one compiler and the last `dub build` wins. Although there are custom build directories per compiler and half of the code to integrate dub packages in meson is to find and use the correct build directory (instead of just calling `dub describe`). This would be much easier, if there were a `dub provide` (or whatever) that builds all deps for a project, installs them into a given prefix/path and makes them usable from `dub describe` afterwards, so that dub describe works more or less like pkg-config afterwards.
Re: I like dlang but i don't like dub
On Friday, 18 March 2022 at 04:13:36 UTC, Alain De Vos wrote: Dlang includes some good ideas. But dub pulls in so much stuff. Too much for me. I like things which are clean,lean,little,small. But when i use dub it links with so many libraries. Are they really needed ? And how do you compare to pythons pip. Feel free to elaborate. Dub is fantastic at some places, e.g. if you need to just execute something from code.dlang.org via `dub run`, or single file packages (https://dub.pm/advanced_usage) are great to write small cmdline utilities with dependencies. I don't like it as a build system and it is notoriously hard to integrate into existing build systems. You can look at meson (which had some D related bug fixes recently) or reggae for that. Or just do `dmd -i` as long as compile times are low enough.
Re: Mixin a function into a struct only if no member with that name already exists
On Wednesday, 29 December 2021 at 10:21:07 UTC, Stanislav Blinov wrote: On Wednesday, 29 December 2021 at 10:14:13 UTC, Tobias Pankrath wrote: How do I mixin a function only if it is not already present? Perhaps use opDispatch? That's a great idea and I'll look into it.
Mixin a function into a struct only if no member with that name already exists
I am trying to implement the builder pattern for some structs. Currently I am auto implementing all methods by mixing them into the builder, but now I need some custom logic for some of the fields and I figured I just write them down by hand and mixin the rest. I tried checking if it is contained in the FieldNameTuple, but that (understandably) creates a circular reference: https://run.dlang.io/is/Xih7yP How do I mixin a function only if it is not already present?
Re: Is there a way to make a function parameter accept only values that can be checked at compile time?
On Tuesday, 28 December 2021 at 21:19:29 UTC, rempas wrote: I would like to know if that's possible. Actually I would like to do something like the following: ``` extern (C) void main() { void print_num(int num, comp_time_type int mul) { static if (is(mul == ten)) { printf("%d\n", num * 10); } else static if (is(mul == three)) { printf("%d\n", num * 3); } else { printf("%d\n", num); } } int multi = 211; print_num(10, 3); // Ok, accept this print_num(10, multi); // Error, do not accept this } ``` So I want to have "mul" only accept values that can be calculate at compile time so I can use it with things like "static if". Is this possible? I think you have to make 'mul' a template parameter.
Re: EMSI Containers and HashMap of HashMaps
On Sunday, 2 May 2021 at 07:38:03 UTC, Tobias Pankrath wrote: For your convenience: https://run.dlang.io/is/gHSlu1 I am using Refcounted() because HashMap itself is not copy-able. Is there another way to have HashMaps as values of HashMaps? I've figured it out and filed an PR https://github.com/dlang-community/containers/pull/169. Would be great if we can get a new version out with this.
Re: EMSI Containers and HashMap of HashMaps
On Sunday, 2 May 2021 at 08:59:15 UTC, Imperatorn wrote: ```d HashMap!(int, RefCounted!Map) mapOfMaps = HashMap!(int, RefCounted!Map)(1024); ``` That only fixes it, because you are avoiding the rehash with the initial size.
Re: EMSI Containers and HashMap of HashMaps
On Sunday, 2 May 2021 at 08:59:15 UTC, Imperatorn wrote: On Sunday, 2 May 2021 at 07:38:03 UTC, Tobias Pankrath wrote: ```d HashMap!(int, RefCounted!Map) mapOfMaps = HashMap!(int, RefCounted!Map)(1024); ``` Is HashMap.init a broken state? That makes using them hard as struct members :/
EMSI Containers and HashMap of HashMaps
The following code segfaults, when the outer hashmap rehashes, and I am not yet sure why. ```d module tests.refcounted_hashmap_test; import containers; import std.typecons; struct Map { HashMap!(int, int) theMap; } unittest { HashMap!(int, RefCounted!Map) mapOfMaps; foreach (i; 0 .. 1000) { RefCounted!Map val; if (i == 0) val.theMap.getOrAdd(i, i); mapOfMaps.getOrAdd(i, val); } } ``` For your convenience: https://run.dlang.io/is/gHSlu1 I am using Refcounted() because HashMap itself is not copy-able. Is there another way to have HashMaps as values of HashMaps?
Re: GC memory fragmentation
On Tuesday, 13 April 2021 at 12:30:13 UTC, tchaloupka wrote: Some kind of GC memory dump and analyzer tool as mentioned `Diamond` would be of tremendous help to diagnose this.. You could try to get the stack traces of the allocating calls via eBPF. Maybe that leads to some new insights.
Re: noobie question, dub or meson?
On Thursday, 18 March 2021 at 02:28:56 UTC, Chris Piker wrote: Hi D I've started a D layer for one of my C libraries that's adds some new functionality and a bit of an interface upgrade. In turn I'm using this combined code-base as a dependency for D "scripts". Since my software is used by a few outside groups in my field, it seems I should get used to packaging D modules, even if those packages never make it to the central dub repo. Given that source code for the combined library is some D but mostly C, would you recommend that I: 1) Keep the D sources and C sources in separate projects? 2) Use meson to create a combined package? 3) Use dub to create a combined package? 4) Some other option? The D code is useless without it's C core, so a dub package that just includes the D parts would be disappointing. The library's not huge, only about 25K lines, but I don't think I have time for a straight conversion of the whole thing to D at this point. Thanks for your opinions on the matter, The D support from meson is not perfect, but for your use case I'd go for it, esp. if you have do not have many dependencies on dub packages. One problem with meson is that it goes the separate compilation route by default. I recommend just to -I your dependencies and build with -i, to avoid the hit in your compile times.
Re: rdmd and D equivalent for PYTHONPATH?
On Wednesday, 17 March 2021 at 19:33:26 UTC, Chris Piker wrote: So, if I could do the equivalent of: dub add-path via an environment variable (not a permanent change under ~/.dub), or have some environment variable that tells dub where to read a "system-level" local-packages.json file and merge it's paths in with any personal settings, that would likely handle our internal code sharing needs. For scripts this could be a good way, but it does not really work with most dub packages: 1. put all your dependencies into a single location, like /home//dstuff 2. add -I /home//dstuff to your call to rdmd/dmd (or put into /etc/dmd.conf 3. add -i (lowercase) to your call of rdmd/dmd 4. profit -i automatically adds all modules that are imported to the compilation, i.e. all your dependencies are compiled together with your code, when they are needed. It searches for them where -I points to. To make this work the dependencies must have the correct project layout, e.g. sources should be in the top-level project directory and not in a subdirectory source. This rules out most dub packages :/
Re: Using multiple mixin templates to implement operator overloading
On Saturday, 12 December 2020 at 18:14:31 UTC, Paul Backus wrote: Functions from different mixin templates can't overload each other. The reason for this is that, when you mix in a mixin template, it does not *actually* add the declarations inside it to a current scope: instead, it adds them to a new scope, and then (essentially) "imports" them into the current scope. Much appreciated! Exactly the explanation I needed.
Using multiple mixin templates to implement operator overloading
I want to wrap e.g. an int and implement basic arithmetic. In the provided example [1] I use two mixin templates to separately implement scaling (multiplication with int/double) and addition and subtraction with the type itself. In the end I want to have several distinct wrappers and allow specific operations between them and int / double. It's important that the return values are typed correctly, otherwise I could use std.typecons.Proxy. My problem is that both overloads of opBinary work, but not at the same time. As soon as I mixin both templates, they stop to work. If I just paste the implementation into the body of WrapInt, they work both at the same time though. Could someone explain the mechanics behind it? Thanks! [1] https://run.dlang.io/is/WbG987
Re: regex: ] in a character class
On Saturday, 12 December 2020 at 12:03:49 UTC, kdevel wrote: I don't have a suggestion for better wording yet. [1] https://dlang.org/phobos/std_regex.html This [1] is how I would word it. [1] https://github.com/dlang/phobos/pull/7724
Re: regex: ] in a character class
On Saturday, 12 December 2020 at 12:03:49 UTC, kdevel wrote: In some situations a ] must be escaped as in auto re = regex(`^[a\]]$`); // match a and ] only Unfortunately dmd/phobos does not warn if you forget the backslash: auto re = regex(`^[a]]$`); // match a] This leads me to the documentation [1] which says \c where c is one of [|*+?() Matches the character c itself. ] must be added to this list since \] obviously matches ]. Additionally the statement any character except [{|*+?()^$ Matches the character itself. is not true since ] does not match itself when ] denotes the end of a character class. I don't have a suggestion for better wording yet. [1] https://dlang.org/phobos/std_regex.html As I understand it, the statement is indeed true and a regex `]]]` would match and only match the string `]]]`. What should be added somewhere is Inside character classes the character ']' has to be written as '\]'.
Re: dub: standard project: how to build the unittest (the thing `dub test` runs)
On Saturday, 12 December 2020 at 12:18:47 UTC, Andre Pany wrote: In any case you should have configurations in your dub json. Thank you for your detailed reply and I am sure I can make it work in the way you described. But I don't think my use case is invalid and dub should improve its usability here. Either it is indeed necessary to provide configuration even for very simple projects. Than dub should generate them on `dub init`. Or dub allows one to just build the test without running them. I'd propose `dub build test` or `dub build --test` for it. What do you think?
dub: standard project: how to build the unittest (the thing `dub test` runs)
Whenever I come back to some D, I seem to be stumbling over dub. Somehow dub and I don't align: $ dub init dubtest && cd dubtest $ dub test -> creates executable `dubtest` (saying Falling back to "dub -b unittest".) $ touch source/lib.d dub test -> creates executable dubtest-test-library Question is: How do I build the `dubtest-test-library` without running the tests? If no explicit configuration is given, an existing "unittest" configuration will be preferred for testing. If none exists, the first library type configuration will be used, and if that doesn't exist either, the first executable configuration is chosen. I've tried $ dub test -b unittest -c library but that re-creates ./dubtest not ./dubtest-test-library.
Re: Can I convert string to expression somehow?
On Saturday, 12 December 2020 at 09:05:19 UTC, Godnyx wrote: I'm trying to create a cool function that will let us do formatting sorter and faster. The function will work like that: outln("My name is {name} and my age is {age}"); this will be equivalent to: writeln("My name is ", name, " and my age is ", age); or: writefln("My name is %s and my age is %d", name, age); There was a DIP to bring something akin to this into the language, but there were also some decent counter proposals. See for example here: http://dpldocs.info/this-week-in-d/Blog.Posted_2019_12_16.html
Re: Concatenation/joining strings together in a more readable way
On Wednesday, 25 December 2019 at 12:39:08 UTC, BoQsc wrote: Are there any other ways to join two strings without Tilde ~ character? I can't seems to find anything about Tilde character concatenation easily, nor the alternatives to it. Can someone share some knowledge on this or at least point out useful links/resources? Tilde operator is documented under cat expression: https://dlang.org/spec/expression.html#cat_expressions An alternative would be std.algorithm.joiner: https://dlang.org/phobos/std_algorithm_iteration.html#.joiner
Re: Bug or Feature: unsigned integer overflow
On Saturday, 14 December 2019 at 10:32:10 UTC, berni44 wrote: On Saturday, 14 December 2019 at 09:33:13 UTC, Tobias Pankrath wrote: See: https://dlang.org/spec/lex.html#integerliteral What I am aiming at: Is the spec wrong or am I misunderstanding it and did this change recently? You are right. The implementation does not do what the specs tell here. I filed a bug report: https://issues.dlang.org/show_bug.cgi?id=20449 Thank you!
Re: Bug or Feature: unsigned integer overflow
On Saturday, 14 December 2019 at 07:44:37 UTC, berni44 wrote: On Saturday, 14 December 2019 at 07:09:30 UTC, Tobias Pankrath wrote: void main() { auto x = 9223372036854775808; // long.max + 1 } You need to tell, that this is an unsigned long literal, else the compiler treats it as an int: void main() { auto x = 9223372036854775808UL; // long.max + 1 } As far as I understand the spec, the type is inferred from the value range: Literal Type Usual decimal notation 0 .. 2_147_483_647 int 2_147_483_648 .. 9_223_372_036_854_775_807 long 9_223_372_036_854_775_808 .. 18_446_744_073_709_551_615 ulong See: https://dlang.org/spec/lex.html#integerliteral What I am aiming at: Is the spec wrong or am I misunderstanding it and did this change recently?
Bug or Feature: unsigned integer overflow
void main() { auto x = 9223372036854775808; // long.max + 1 } onlineapp.d(3): Error: signed integer overflow According to spec x should be of type ulong and this should compile? It indeed compiles if I add the uL postfix. Is this a bug or indented behaviour?
Use my private phobos version in dub project
Hi, I wanted to hack a bit on phobos and wondered what the best way is to use my own version in a project managed by dub. I have used the dlang/tools/setup.sh and got ../d/dmd, ../d/phobos/ ../d/druntime etc. Now I want to hack on phobos and use that version in a project of mine to test the changes. What's the best way to do this? I've searched the wiki, but didn't find anything useful. Thanks!
No UFCS with nested functions?
Why does the following not work? It works, if I move the 'prop' out of 'foo'. --- struct S { ubyte[12] bar; } bool foo (ref S s) { static bool prop(const(ubyte)[] f) { return f.length > 1; } return s.bar[].prop; } --- Thanks!
Re: Documentation: is it intentional that template constraints are displayed after the signature?
On Friday, 1 November 2019 at 09:17:03 UTC, Dennis wrote: Template constraints are not allowed before the signature in the language, so it can be expected the documentation does not swap that order. On Thursday, 31 October 2019 at 13:34:35 UTC, Tobias Pankrath wrote: I was confused at first by the trailing if (!is(T == struct) && !is(T == interface) && !is(T == class) && !__traits(isStaticArray, T)); Or are you confused by the newline between the ) and the if? I do think the indentation is a bit confusing, but I don't know a better one. I always have difficulty myself when trying to cleanly format long signatures of template functions. Ah yes, now I see it.
Documentation: is it intentional that template constraints are displayed after the signature?
e.g. here: https://dlang.org/library/object/destroy.html I was confused at first by the trailing if (!is(T == struct) && !is(T == interface) && !is(T == class) && !__traits(isStaticArray, T)); after I somehow managed to completely parse that page without recognizing all other constraints.
Re: std.container.array: Error: unable to determine fields of Test because of forward references
On Thursday, 31 October 2019 at 12:37:55 UTC, user1234 wrote: struct S { S*[] children; } because otherwise when you declare the array the compiler has not finished the semantic ana of S. --- struct Test { Test[] t; } --- Works today. Putting pointers into the container (and thus having another indirection) is not an option, though.
std.container.array: Error: unable to determine fields of Test because of forward references
My Problem: --- (https://run.dlang.io/is/CfLscj) import std.container.array; import std.traits; struct Test { Test[] t; } struct Test2 { Array!Test2 t; } int main() { return FieldTypeTuple!Test.length + FieldTypeTuple!Test2; } --- I've found https://issues.dlang.org/show_bug.cgi?id=19407 but I am not using separate compilation, just `dmd test.d`. I want to have a tree structure like --- struct S { S[] children; } --- but I do not want to rely on the GC and thus wanted to use a custom array type. What's the best way to do this?
Re: How Different Are Templates from Generics
On Friday, 11 October 2019 at 14:43:49 UTC, Just Dave wrote: I come from both a C++ and C# background. Those have been the primary languages I have used. Probably the D templates relate to C# generics the same way that C++ templates do.
Re: Functional Programming in D
On Wednesday, 9 October 2019 at 18:57:01 UTC, SrMordred wrote: https://garden.dlang.io/ This should be more prominent. Very nice.
Re: Using enforce or assert to check for fullness when appending to fixed length array container
On Friday, 4 October 2019 at 10:00:08 UTC, Per Nordlöw wrote: Is the usage of `enforce` to check for out of bounds (fullness) idiomatic D or should an `assert()` be used instead? I'd say it should follow -boundscheck: https://dlang.org/dmd-linux.html#switch-boundscheck Does that set an version identifier?
Re: How to get the address of an instance of a class
On Wednesday, 25 September 2019 at 17:32:25 UTC, dokutoku wrote: I wrote the following code to get the address of a class instance, but it doesn't work. Please let me know if there is a way to write it to work properly. private import std; ``` class C { C* this_pointer() { return this; } } void main() { C Z = new C(); writeln( == Z.this_pointer()); } ``` Classes are always references. I think you can just cast 'Z' to void* to get the address. Conversely should be an address on the stack.
Re: Inspecting __traits(isDeprecated) and deprecation warnings
On Tuesday, 24 September 2019 at 17:01:46 UTC, Anonymouse wrote: I want to write a piece of code that reflects on the names of members of a passed struct, where some are depreacted. https://run.dlang.io/is/P9EtRG struct Foo { string s; int ii; bool bbb; deprecated("Use `s`") string ; } template longestMemberLength(T) { enum longestMemberLength = () { size_t maxLength; foreach (immutable i, immutable name; __traits(allMembers, T)) { static if (!__traits(isDeprecated, __traits(getMember, T, name))) { maxLength = max(maxLength, name.length); } } return maxLength; }(); } static assert (longestMemberLength!Foo == "bbb".length); onlineapp.d(23): Deprecation: variable `onlineapp.Foo.` is deprecated - Use s Is there any way to inspect the deprecated-ness of a member this way? I only have what __traits(allMembers) gives me. Does your code work or does it not? I don't seem to unterstand neither what the question here is nor what the desired result is. Is the problem that the static reflections triggers the deprecation warning?
Re: Looking for a Simple Doubly Linked List Implementation
On Saturday, 21 September 2019 at 09:03:13 UTC, Ron Tarrant wrote: Ah! Thanks, ag0aep6g. I was wondering about that when I was writing the code. (If I already knew this, I'd forgotten.) I did as you suggested, took out all '*' and '&' and it works perfectly. Is this what you want? --- current.setPrev(current); ---
dub with sub packages: sub package with targetType "executable" builds with configuration ""
Hi, I've got a dub package with the following configuration file --- { "description": "A minimal D application.", "license": "proprietary", "authors": [ "me" ], "copyright": "Copyright © 2019, me", "name": "test", "targetType" : "none", "dependencies": { "test:mylib" : "*" ,"test:myexe1" : "*" }, "subPackages": [ { "name": "mylib" ,"targetType" : "library" ,"sourcePaths" : ["mylib/source"] ,"importPaths" : ["mylib/source"] } ,{ "name" : "myexe1" ,"targetType" : "executable" ,"sourcePaths": ["myexe1/source"] ,"importPaths": ["myexe1/source"] ,"dependencies": { "test:mylib" : "*" } } ] } --- when building this, dub gives me --- dub build --force Performing "debug" build using /usr/bin/dmd for x86_64. test:mylib ~master: building configuration "library"... test:myexe1 ~master: building configuration ""... Linking... --- Note that the configuration of myexe1 is "". I want it to be 'application', just like this: --- % dub build test:myexe1 Building package test:myexe1 in /home/tobias/projects/test/ Performing "debug" build using /usr/bin/dmd for x86_64. test:mylib ~master: target for configuration "library" is up to date. test:myexe1 ~master: building configuration "application"... Linking... To force a rebuild of up-to-date targets, run again with --force. --- Background: the project will contain multiple executables that use vibe-d. If they are not build as 'application' the version VibeDefaultMain seems to have no effect. What's the best way to configure this?
Re: Line numbers in backtraces (2017)
Including Phobos? Your posted backtrace looks to me like templates instantiated within Phobos, so I think you'd need Phobos with debug symbols for those lines. --- int main(string[] argv) { return argv[1].length > 0; } --- ~ [i] % rdmd -g -debug test.d core.exception.RangeError@test.d(3): Range violation No difference when I compile with 'dmd -g -debug' and run in manually.
Re: Line numbers in backtraces (2017)
On Tuesday, 31 October 2017 at 11:21:30 UTC, Moritz Maxeiner wrote: On Tuesday, 31 October 2017 at 11:04:57 UTC, Tobias Pankrath wrote: [...] ??:? pure @safe void std.exception.bailOut!(Exception).bailOut(immutable(char)[], ulong, const(char[])) [0xab5c9566] ??:? pure @safe bool std.exception.enforce!(Exception, bool).enforce(bool, lazy const(char)[], immutable(char)[], ulong) [0xab5c94e2] I've found this StackOverflow Question from 2011 [1] and if I remember correctly this could be fixed by adding -L--export-dynamic which already is part of my dmd.conf [...] [1] https://stackoverflow.com/questions/8209494/how-to-show-line-numbers-in-d-backtraces Does using dmd's `-g` option (compile with debug symbols) not work[1]? [1] This is also what the answer in your linked SO post suggest? Of course I've tried this.
Line numbers in backtraces (2017)
Hi, I'm using ArchLinux and the recent DMD from the Arch repositories and my backtraces show no line numbers. I now that is an old issue, but I'm back to D after a long pause and I thought that this used to work out of the box. My backtraces look likes this: ??:? pure @safe void std.exception.bailOut!(Exception).bailOut(immutable(char)[], ulong, const(char[])) [0xab5c9566] ??:? pure @safe bool std.exception.enforce!(Exception, bool).enforce(bool, lazy const(char)[], immutable(char)[], ulong) [0xab5c94e2] I've found this StackOverflow Question from 2011 [1] and if I remember correctly this could be fixed by adding -L--export-dynamic which already is part of my dmd.conf cat /etc/dmd.conf [Environment32] DFLAGS=-I/usr/include/dlang/dmd -L-L/usr/lib32 -L--export-dynamic -fPIC [Environment64] DFLAGS=-I/usr/include/dlang/dmd -L-L/usr/lib -L--export-dynamic -fPIC which is in fact read by dmd: % dmd -v DMD64 D Compiler v2.076.1 Copyright (c) 1999-2017 by Digital Mars written by Walter Bright Documentation: http://dlang.org/ Config file: /etc/dmd.conf How do I get useful back traces back? Thanks, Tobias [1] https://stackoverflow.com/questions/8209494/how-to-show-line-numbers-in-d-backtraces
[std.regex] Set operations with unicode properties.
Greetings, I need to match any character, except control characters and some other exceptions and thought this would be a good usecase to use character classes and set operations. Can I combine this with unicode properties?, e.g: any Charactor that is not a control character and not ';' or ':'? --- string regex = "[\p{Any}--\p{Control}--[;:]]"; --- Is this possible somehow? Thanks, - Tobias
Re: emplace, immutable members and undefined behaviour
this compiles and runs fine. Because emplace expects a typed pointer, it actually modifies (*p).x and (*p).y As far as I understand, this causes undefined behavior. Are there any (safe) alternatives to this code other than making the immutable members mutable? As long as there are no other references to the immutable members and you can guarantee that they are indeed in mutable memory (both guaranteed by malloc) you are safe. If you really don't want to write to any immutable member, you could do this: struct Point { double a; double b; } Point* p = (allocate memory from somewhere); emplace!Point(p, 1, 2); immutable(Point)* immutableP = cast(immutable(Point)*) p;
Re: emplace, immutable members and undefined behaviour
On Sunday, 15 November 2015 at 10:59:43 UTC, Tobias Pankrath wrote: Point* p = (allocate memory from somewhere); emplace!Point(p, 1, 2); immutable(Point)* immutableP = cast(immutable(Point)*) p; You could also use the emplace version that takes untyped memory: http://dlang.org/phobos/std_conv.html#.emplace The last one.
Re: my first D program (and benchmark against perl)
or with ~ operator: import std.stdio; [...] Did anyone check that the last loop isn't optimized out? Could also be improved further if you make the function take an output range and reuse one appender for every call, but that might be to far off the original perl solution.
Re: String interpolation
On Tuesday, 10 November 2015 at 10:21:32 UTC, tired_eyes wrote: Hi, The only example of string interpolation I've found so far is on Rosetta Code: void main() { import std.stdio, std.string; "Mary had a %s lamb.".format("little").writeln; "Mary had a %2$s %1$s lamb.".format("little", "white").writeln; } Is this a "proper" way of string interpolation in D? This looks a little clumsy. Are there any better approaches? Quick skimming through the docs didn't give anything. std.string.format and std.format are the standard options. What are you missing?
Re: Tree datatype
On Wednesday, 14 October 2015 at 14:42:31 UTC, Namal wrote: Hello, I don't remember exactly but I think when I first saw D code there was tree datatype implemented without pointers. Is it possible to make a tree struct without pointers? struct Tree { Tree[] children; } That works quite well as long as you don't have to change the tree.
Re: Interlocked (compare) exchange
On Friday, 17 April 2015 at 10:36:33 UTC, Szymon Gatner wrote: Hi, are there equivalents of Interlocked.Exchange [1] and Interlocked.CompareExchange [2] in D? I can't find it in teh docs? [1] https://msdn.microsoft.com/en-us/library/f2090ex9(v=vs.110).aspx [2] https://msdn.microsoft.com/en-us/library/h7etff8w(v=vs.110).aspx [2] sounds like compare-and-swap from http://dlang.org/phobos/core_atomic.html
Re: Keep Track of the Best N Nodes in a Graph Traversal Algorithm
On Wednesday, 25 March 2015 at 14:40:28 UTC, Per Nordlöw wrote: On Wednesday, 25 March 2015 at 13:55:29 UTC, bearophile wrote: Nordlöw: I have graph traversal algorithm that needs to keep track of the N best node visit. std.algorithm.topNCopy? Bye, bearophile Notice that, ideally, I would like my list of top-nodes to have a fixed size during the whole algorithm (99.9 % of time) as soon it has reached the length of N. What's wrong with binary heaps?
Re: Contributing to Phobos Documentation
On Saturday, 21 March 2015 at 17:48:41 UTC, Craig Dillabaugh wrote: Motivated by this thread: http://forum.dlang.org/thread/measc3$qic$1...@digitalmars.com I was hoping to see if I could do some work on the Phobos documentation, but I am curious to know what the easiest way for someone with limited/no ddoc experience to get involved in this would be. I checked the CONTRIBUTING.md file in phobos and it is a bit on the 'light' side. http://wiki.dlang.org/Building_DMD
Re: Lazy functions, lazy arrays
On Friday, 20 March 2015 at 12:15:22 UTC, Dennis Ritchie wrote: On Friday, 20 March 2015 at 10:38:17 UTC, John Colvin wrote: I don't understand what you mean. You mean a function that isn't compiled if it isn't used anywhere? Yes. That's exactly what I mean. Use case?
Re: Lazy functions, lazy arrays
Now I am totally confused. lazy and eager evaluation are unrelated to compile time and run time.
Re: How to use UFCS and std.algorithm.sort?
.array .sort buildin arrays have a .sort-property that is called.
Re: Filling a char array with letters and element type of char[]
I have three questions? If I change the iterator which I get from algorithm, the owner data will change or not? How to use std.algorithm.fill with char types? What is the type of char array holds why it does not matches char? Regards Kadir Erdem I have no time to dig into this, but: is(typeof(arr.front = 'a')) does _not_ check if arr.front is of type char. It is true if you can assign an 'a' to arr.front. is(typeof(_expr_)) is another way to write __traits(compiles, _expr). So, either the range returned by until has elements that are not assignable or the reason is that until returns a range of dchar, because all string types are treated as ranges of dchar.
Re: Error instantiating std.container.Array
I'm really clueless... :P Something is wrong with your Material class, but you'll need to show us a reduced example.
Re: Shouldn't std.conv.emplace be @nogc?
On Monday, 2 March 2015 at 12:37:33 UTC, drug wrote: I guess the reason why std.conv.emplace is not @nogc-ed is that nobody added it yet? I didn't see using of gc in the emplace sources. It's a template and an instance will be @nogc, if possible.
Re: Error instantiating std.container.Array
On Monday, 2 March 2015 at 14:08:29 UTC, Francesco Cattoglio wrote: I'm trying to instantiate a std.container.Array of a given class (named Material), by a simple Array!Material _myStuff; I get two compile errors stating the following: C:\D\dmd2\windows\bin\..\..\src\phobos\std\container\array.d(85): Error: template std.algorithm.initializeAll cannot deduce function from argument types !()(Material[]), candidates are: C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(1502): std.algorithm.initializeAll(Range)(Range range) if (isInputRange!Range hasLvalueElements!Range hasAssignableElements!Range) C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(1530): std.algorithm.initializeAll(Range)(Range range) if (is(Range == char[]) || is(Range == wchar[])) C:\D\dmd2\windows\bin\..\..\src\phobos\std\container\array.d(825): Error: template std.algorithm.copy cannot deduce function from argument types !()(Range, Range), candidates are: C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(7808): std.algorithm.copy(Range1, Range2)(Range1 source, Range2 target) if (isInputRange!Range1 isOutputRange!(Range2, ElementType!Range1)) Any idea about what might be happening? I can't give a quick minimal example of the code since it is quite complex (and I failed at using dustmite trying to minimize it) Try to reduce your Material class for a small failing example. It's probably your constructors or opAssign or something like that. Anyway, it's a bug if template errors from the implementation bubble up, so please file a report.
Re: D constness: head tail
On Monday, 2 March 2015 at 10:15:00 UTC, ketmar wrote: or, tl;dr: `const` in D is working as it was designed to work. there are no changes planning for it, and it will not be turned to c++-like const. It's working as it's designed to work, although the design is somewhat lacking: https://github.com/D-Programming-Language/phobos/blob/master/std/container/array.d#L505
Re: Error instantiating std.container.Array
On Monday, 2 March 2015 at 15:14:49 UTC, Francesco Cattoglio wrote: On Monday, 2 March 2015 at 15:01:55 UTC, Tobias Pankrath wrote: I'm really clueless... :P Something is wrong with your Material class, but you'll need to show us a reduced example. After a really long time I finally found what was wrong. http://dpaste.dzfl.pl/16d202b7124d Wow, I honestly could have NEVER foreseen this. This is all it takes for a class being unusable in a std.container.Array class MyClass { void init(); } .init is a special property of every type: http://dlang.org/property.html#init
Re: Opening temporary files for std.process.spawnProcess input/output
On Wednesday, 25 February 2015 at 13:56:06 UTC, wobbles wrote: Hi, Any reason why the following wont work? void main(string[] args) { auto pidIn = File.tmpfile(); auto pidOut = File.tmpfile(); auto pid = spawnProcess([ls, ./], pidIn, pidOut, std.stdio.stdout, null, Config.newEnv); if(wait(pid) == 0) writefln(%s, pidOut.readln()); } The pidOut.readln() throws this exception: object.Exception@/usr/include/dmd/phobos/std/stdio.d(1377): Attempt to read from an unopened file. I figured tmpfile() would be open for read/write by default? Also, theres no way to pass in args to File.tmpfile() to make them read/write. Any ideas? maybe only for writing: http://www.cplusplus.com/reference/cstdio/tmpfile/
DList.Range magically becomes empty.
import std.container; import std.stdio; void main() { DList!int list; Array!(DList!int.Range) stack; foreach(i; 0 .. 4) { list.stableInsertBack(i); stack.insertBack(list[]); } writefln(list: %s, list[]); // fine writefln(stack: %s, stack[]); //fine foreach(s; stack[]) writefln(s: %s, s); // all s are empty? writefln(stack: %s, stack[]); //not fine } It prints: list: [0, 1, 2, 3] stack: [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] s: [] s: [] s: [] s: [] stack: [[], [], [], []]
Re: Struct inheritance
On Tuesday, 24 February 2015 at 12:05:51 UTC, amber wrote: Hi, Is it possible in D to have inheritance using value types, i.e. structs? No runtime polymorphism, but a kind of sub typing via alias this. struct S { void foo() { writeln(S.foo); } struct T { S s; alias s this; } T t; t.foo(); // prints S.foo Also I don't quite understand how copy ctors work in D. Do I need to implement opAssign(S other) {}, or this(this) {} and what's the difference between these two? If available, opAssign will be used in an assignment like x = y; You're custom opAssign can take arbitrary parameter types, so typeof(y) does not have to be typeof(x). postblit is used for copy construction. This could be assignment if no opAssign is provided (not sure about this), but also e.g. passing parameter by value or returning from a function.
Re: strings and array literal mutability
On Tuesday, 24 February 2015 at 22:12:57 UTC, Freddy wrote: Why are strings immutable but array literals are not? Because string is an alias for immutable(char).
Re: Searching for Elements in Containers
On Sunday, 22 February 2015 at 13:53:51 UTC, Nordlöw wrote: Is there some function similar to std.algorithm.find() which returns an element index instead of a range? I guess 0 means no hit and 1, 2, 3 means hits at indexes 0, 1, 2 etc. I want this to avoid having to create ranges ([]) when searching for a specific element in std.container.Array. You could use a range and countUntil.
SubClass[] does not implicitly convert to SuperClass[], why?
What's the reason behind this design? class Super {} class Sub : Super {} void foo(Super[] sup) {} void main() { Sub[] array; foo(array); // error, cannot call foo(Super[]) with arguments (Sub[]) }
Re: SubClass[] does not implicitly convert to SuperClass[], why?
On Friday, 20 February 2015 at 08:25:49 UTC, rumbu wrote: On Friday, 20 February 2015 at 07:57:17 UTC, Tobias Pankrath wrote: What's the reason behind this design? class Super {} class Sub : Super {} void foo(Super[] sup) {} void main() { Sub[] array; foo(array); // error, cannot call foo(Super[]) with arguments (Sub[]) } Just make the sup parameter const: void foo(in Super[] sup) {} http://dlang.org/arrays.html (end of the page): A dynamic array T[] can be implicitly converted to one of the following: const(U)[] const(U[]) Where U is a base class of T. The reson behind the design - I wonder about that also. Thanks, didn't know that. Makes sense. Probably the reason is: void foo(Super[] sup) { sup[3] = new AnotherDerivedClass(); } After foo returns the slice passed as argument would violate its invariant.
Re: Problem Instantiating a BinaryHeap with a Comparison Function the needs this
On Thursday, 19 February 2015 at 11:56:19 UTC, Nordlöw wrote: Please provide reduced examples. This fails: class C { int[] a; alias BH = BinaryHeap!(int[], (x, y) = (x+a y)); } This works: class C { int[] a; void foo() { alias BH = BinaryHeap!(int[], (x, y) = (x+a y)); } } But will create an instance of BinaryHeap per member function. What to do? Dunno.
Re: Reference or Value Semantics for Graph Traversal Range
On Wednesday, 18 February 2015 at 13:59:43 UTC, Nordlöw wrote: On Wednesday, 18 February 2015 at 13:53:17 UTC, Tobias Pankrath wrote: All the data members except distMap have reference semantics. I thought AAs had reference semantics. Me too, but the indeed have value semantics. See for example: unittest { string[int] x; auto y = x; x[0] = zero; assert(x != y); } This makes usage of storing internal state in Ranges bug-prone. Isn't there some way to store an AA in reference wrapper? This would simplify my .save member. Because y does not alias x, it's a null pointer like AA. This class is clearly a reference type, but the assert holds as well. class C { int i; } void main() { C c1; C c2 = c1; c1 = new C(12); assert(c1.i != c2.i); }
Re: Reference or Value Semantics for Graph Traversal Range
On Wednesday, 18 February 2015 at 13:37:57 UTC, Nordlöw wrote: I've written a Dijkstra-style graph traversal range at https://github.com/nordlow/justd/blob/master/knet/traversal.d#L105 that needs to internally store the AA distance map in member variable distMap. 1. All the data members except distMap have reference semantics. I thought AAs had reference semantics. Therefore I've made my range a class instead of a struct. Is this the correct way to do it? Neither false nor necessary. You could use a struct just as well. 2. To make it a ForwardRange I've also add a save() member. For now I've hardcoded the single member that needs to be duped. Is this correct way of doing it? That's how I'd do it.
Re: Type-Strict Indexes: IndexedBy
Having this in the language will attract (more) Ada programmers to D. “Having this or that will attract (XY)-programmers / magically make D successful in niche Z” is an argument too weak for phobos inclusion, IMO.
Re: Reference or Value Semantics for Graph Traversal Range
On Wednesday, 18 February 2015 at 14:38:24 UTC, Nordlöw wrote: On Wednesday, 18 February 2015 at 14:07:01 UTC, Steven Schveighoffer wrote: An UNINITIALIZED AA has not yet been allocated, and so it's reference is null. What's reason for uninitialized AA not behaving in the same way as arrays do? It's the same with arrays.
Re: Emptying D Arrays and std.container.Arrays
On Monday, 16 February 2015 at 16:56:15 UTC, Per Nordlöw wrote: Is there a specific function in to empty a builtin D array or should I just do auto x = [1,2,3]; x = []; I'm asking because std.container.Array has the member .clear() and I would like my code to compatible with both builtin arrays and std.container.Array. If not is there an con to using x = [] for std.container.Array aswell? I can't find any clear() function in std.algorithm nor std.range. You can set the length to zero for both.
Re: @nogc with assoc array
On Monday, 16 February 2015 at 17:55:42 UTC, Jonathan Marler wrote: Why is the 'in' operator nogc but the index operator is not? void main() @nogc { int[int] a; auto v = 0 in a; // OK auto w = a[0]; // Error: indexing an associative // array in @nogc function main may // cause GC allocation } Might throw.
Re: Type-Strict Indexes: IndexedBy
On Monday, 16 February 2015 at 20:09:09 UTC, Nordlöw wrote: I'm trying to figure out how to implement a light-weight wrappr realizing type-safe indexing á lá Ada. Here's my first try: struct Ix(T = size_t) { @safe pure: @nogc nothrow: this(T ix) { this._ix = ix; } alias _ix this; private T _ix = 0; } struct IndexedBy(R, I) { auto ref opIndex(I ix) inout { return _r[ix]; } auto ref opSlice(I lower, I upper) inout { return _r[lower .. upper]; } R _r; alias _r this; } auto indexedBy(I, R)(R range) { return IndexedBy!(R, I)(range); } unittest { import std.stdio; auto x = [1, 2, 3]; alias I = int; auto ix = x.indexedBy!I; ix[0] = 11; alias J = Ix!size_t; auto jx = x.indexedBy!J; jx[J(0)] = 11; // should compile jx[0] = 11; // TODO how can I make this not compile? } My question now of course is: How can I prevent jx[0] = 11; from compiling? Did you actually try that? This does not compile because of c[13] struct IndexT { this(size_t s) { x = s; } size_t x; } struct Container { int opIndex(IndexT i) { return 12; } } void main() { auto it = IndexT(13); Container c; c[it]; c[13]; }
Re: Why uniq do not work with array of strings?
On Monday, 16 February 2015 at 18:45:17 UTC, Suliman wrote: Oh I understood. It's means that it work only of two or more element's is placed one after one? That's why you'll usually want to sort before using uniq.
Re: Why uniq do not work with array of strings?
On Monday, 16 February 2015 at 18:45:17 UTC, Suliman wrote: Oh I understood. It's means that it work only of two or more element's is placed one after one? Yes, uniq returns exactly the same range as its input, except that elemens that are equal to their immediate predecessor are dropped.
Re: Why uniq do not work with array of strings?
On Monday, 16 February 2015 at 18:28:13 UTC, Suliman wrote: The question appear here http://stackoverflow.com/questions/28546572/how-to-find-duplicates-in-array-of-strings-in-d I can't understand, why uniq work for array of int but do not work with array of strings. int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ]; writeln(uniq(arr)); string [] str = [qwe,asd,zxc, qwe]; auto uniqarr = uniq(str); foreach(x;uniqarr) { writeln(x); } Running .\test.exe [1, 2, 3, 4, 5] qwe asd zxc qwe ^ qwe prints two times. Works as expected. From the docs: Iterates unique - _consecutive_ - elements of the given range Though I concur that the description might be more verbose.
Re: Why uniq do not work with array of strings?
Docs will get a lot better in the next release: http://dlang.org/phobos-prerelease/std_algorithm_iteration.html#uniq
Re: Data-Flow (Escape) Analysis to Aid in Avoiding GC
On Friday, 13 February 2015 at 08:21:53 UTC, Per Nordlöw wrote: When reading/parsing data from disk often try to write code such as foreach (const line; File(filePath).byLine) { auto s = line.splitter( ) const x = s.front.to!uint; s.popFront; const y = s.front.to!double; s.popFront; ... } In response to all the discussions regarding performance problems related to the GC I wonder if there are plans to implement data-flow analysis in DMD that can detect that the calls to s.front in the example above doesn't need to use the GC. This because their references aren't used outside of the foreach scope (Escape Analysis). I haven't looked into the source, but the only point where this snippet should allocate is at byLine.
Re: Data-Flow (Escape) Analysis to Aid in Avoiding GC
On Friday, 13 February 2015 at 11:34:50 UTC, Per Nordlöw wrote: On Friday, 13 February 2015 at 09:13:48 UTC, Kagamin wrote: Whether s.front uses GC is determined by s.front implementation, caller can't affect it. Compiling https://github.com/nordlow/justd/blob/master/t_splitter.d with -vgc on dmd git master gives no warnings about GC allocations! Is this really true!? Why should splitter.front allocate?
Re: Data-Flow (Escape) Analysis to Aid in Avoiding GC
On Friday, 13 February 2015 at 12:40:57 UTC, Per Nordlöw wrote: On Friday, 13 February 2015 at 11:52:50 UTC, Tobias Pankrath wrote: On Friday, 13 February 2015 at 11:34:50 UTC, Per Nordlöw wrote: On Friday, 13 February 2015 at 09:13:48 UTC, Kagamin wrote: Whether s.front uses GC is determined by s.front implementation, caller can't affect it. Compiling https://github.com/nordlow/justd/blob/master/t_splitter.d with -vgc on dmd git master gives no warnings about GC allocations! Is this really true!? Why should splitter.front allocate? Ahh, I think I understand now. I thought that slice creations ment GC-allocation but it doesn't right? It just increases a reference counter somewhere and creates a stack context for the slice right? There are no reference counts involved, just simple arithmetic. string a = abc; string b = a[1 .. $]; struct Slice(T) { T* ptr; size_t length }; Slice!char a = { ptr_to_constant, 3 } Slice!char b = { a.ptr + 1, 2 } But what about to!string in auto x = line.strip.splitter!isWhite.joiner(_).to!string; ? That needs to allocate. Probably -vgc only lists GC allocation inside the current scope and doesn't look inside called functions. For this, there is @nogc.
Re: Data-Flow (Escape) Analysis to Aid in Avoiding GC
On Friday, 13 February 2015 at 12:58:40 UTC, Per Nordlöw wrote: On Friday, 13 February 2015 at 12:50:14 UTC, Tobias Pankrath wrote: There are no reference counts involved, just simple arithmetic. string a = abc; string b = a[1 .. $]; Then how does the GC know when to release when there are multiple references? Is this because string references immutable storage? It scans the memory for pointers to the memory to be freed before freeing them. Isn't vgc recursively inferred bottom-up for calls to templates functions? I didn't know vgc exists until your question, so I don't know what it does exactly. Thought that it will highlight calls to GC.malloc in the current function, even if emitted by the compiler for e.g. closures. I don't think it treats template functions different than other functions (it only considers their signature).
Re: I can has @nogc and throw Exceptions?
On Friday, 13 February 2015 at 19:03:10 UTC, Jonathan Marler wrote: This question comes from wanting to be able to throw an exception in code that is @nogc. I don't know if it's possible but I'd like to be able to throw an exception without allocating memory for the garbage collector? You can do it in C++ so I think you should be able to in D. One idea I had was to allocate the memory for the Exception beforehand and create the Exception class with the pre-allocated memory. I came up with the following code: T construct(T,A...)(void* buffer, A args) { return (cast(T)buffer).__ctor(args); } Now to test it: void main() { ubyte[ __traits(classInstanceSize, Exception)] exceptionBuffer; throw construct!(Exception)(exceptionBuffer.ptr, My Exception Allocated on the STACK!); } I got an assertion error. I'm not sure why, but when I print out the contents of the buffer of my stack exception it differs from an exception created for the garbage collector with new. It looks like it has some accounting information embedded in the class instance. I figured as much but I didn't think the code that performs the throw would be dependent on this. Also, this doesn't look like a very safe option because the initial values for the class members don't get set using this construct template. If anyone has any other ideas or a way to fix mine let me know, thanks. 1. Throw preallocated exceptions is the way to go 2. Allocating them on the stackframe that will cease to exist by throwing is a bad idea 3. use emplace To construct a type in preallocated memory
Re: To write such an expressive code D
On Tuesday, 10 February 2015 at 08:40:38 UTC, Dennis Ritchie wrote: On Tuesday, 10 February 2015 at 08:12:00 UTC, Vladimir Panteleev wrote: Why is that? Потому что я спорил с одним упёртым человеком, которому не нравится D, на этом форуме: http://www.cyberforum.ru/holywars/thread1367892-page13.html Он просил меня написать такую программу с использованием только возможностей языка и функции sin(). Because I was arguing with one quiet a stubborn person who does not like D, on this forum: http://www.cyberforum.ru/holywars/thread1367892-page13.html He asked me to write such a program using only the language features and functions sin(). How to win the holy language war: 1. Pick a feature that only one of the languages has 2. Pick a task that this feature solves neatly 3. Solve it using that feature 4. Forbid every other solution not involving the features that only your preferred language has. Done.
Re: To write such an expressive code D
On Monday, 9 February 2015 at 19:40:42 UTC, Dennis Ritchie wrote: Good evening. Is it possible to D something to replace the container on the F#, which displays the values of the sine from 0 to 90 degrees with an interval of 10 degrees: let pi = Math.PI let sins = [for x in 0.0..pi / 2.0 / 9.0..pi / 2.0 - sin x] sins.Dump() Output: 0 0,17364817766693 0,342020143325699 0,5 0,642787609686539 0,76603118978 0,866025403784439 0,939692620785908 0,984807753012208 1 P.S. Interested in code that will be as impressive as this. In General, I would like to see something akin to D. iota(0, 91, 10).map!sin.writeln or something like that.
Re: primitive type variables not nullable ?
On Sunday, 8 February 2015 at 23:13:33 UTC, Venkat Akkineni wrote: Never mind, stupid question I realize, would delete it if I could. http://stackoverflow.com/questions/11047276/null-for-primitive-data-types Check for null with (x is null) not via printing to stdout.
Re: Do you have a better way to remove element from a array?
On Thursday, 5 February 2015 at 13:25:37 UTC, FrankLike wrote: Now I can remove element from a array: module removeOne; import std.stdio; import std.array; import std.algorithm; void main() { int[] aa =[1,2,3,4,5]; aa = aa[0..2] ~aa[3..$]; writeln(aa); //ok remove(aa,1); writeln(aa);//get error result } You will found the error result,why? Thank you. Works as designed: http://dlang.org/phobos/std_algorithm.html#.remove
Re: Do you have a better way to remove element from a array?
On Thursday, 5 February 2015 at 13:55:59 UTC, FrankLike wrote: On Thursday, 5 February 2015 at 13:29:30 UTC, Tobias Pankrath wrote: Works as designed: http://dlang.org/phobos/std_algorithm.html#.remove Thank you. aa = remove(aa,1);//ok but how to remove one item? such as aa.remove(2) ? I don't get your question.
Re: Syntax for checking if an element exists in a list
import std.algorithm; int main(string[] options) { // true if the first option given to this program is either foo, bar, or baz. if(options[1].canFind(foo, bar, baz)) return 0; return 1; }
Re: Want to read a whole file as utf-8
On Tuesday, 3 February 2015 at 19:44:49 UTC, FG wrote: On 2015-02-03 at 19:53, Foo wrote: How can I do that without any GC allocation? Nothing in std.file seems to be marked with @nogc I'm asking since it seems very complicated to do that with C++, maybe D is a better choice, then we would probably move our whole project from C++ to D. Looks like std.stdio isn't marked with @nogc all the way either. So for now the temporary solution would be to use std.c.stdio. Get the file size, malloc a buffer large enough for it[1], use std.c.stdio.read to fill it, assign it to a char[] slice and std.utf.decode to consume the text... Oh wait, decode isn't @nogc either. FFS, what now? [1] I assume the file is small, otherwise there would be an extra step involved where after nearing the end of the buffer you move the rest of the data to the front, read new data after it, and continue decoding. Use std.utf.validate instead of decode. It will only allocate one exception if necessary.
Re: Want to read a whole file as utf-8
On Tuesday, 3 February 2015 at 23:07:03 UTC, Foo wrote: On Tuesday, 3 February 2015 at 19:44:49 UTC, FG wrote: On 2015-02-03 at 19:53, Foo wrote: How can I do that without any GC allocation? Nothing in std.file seems to be marked with @nogc I'm asking since it seems very complicated to do that with C++, maybe D is a better choice, then we would probably move our whole project from C++ to D. Looks like std.stdio isn't marked with @nogc all the way either. So for now the temporary solution would be to use std.c.stdio. Get the file size, malloc a buffer large enough for it[1], use std.c.stdio.read to fill it, assign it to a char[] slice and std.utf.decode to consume the text... Oh wait, decode isn't @nogc either. FFS, what now? [1] I assume the file is small, otherwise there would be an extra step involved where after nearing the end of the buffer you move the rest of the data to the front, read new data after it, and continue decoding. How would I use decoding for that? Isn't there a way to read the file as utf8 or event better, as unicode? Arrays of char, wchar and dchar are supposed to be UTF strings and of course you can just read them using a c function from a file. You'd just need to make sure they are valid UTF before passing them on to other parts of phobos. What do you mean with as unicode?
Re: Conway's game of life
1. I prefer alias CellList = Cell[]; over alias Cell[] CellList; 2. Do you really need to create a complete new CellList for every single removal? If so, you'd know the size of the new list in advance and can allocate it directly at the correct size. I get the impression that you think Cell[] is a linked list but it's an array slice.
Re: std.algorithm sort() and reverse() confusion
On Friday, 30 January 2015 at 17:07:17 UTC, Paul wrote: On Friday, 30 January 2015 at 16:21:24 UTC, Kagamin wrote: writeln(Sorted, reversed: , retro(sort(myVals))); ? Or... writeln(Reverse sorted: , sort!(a b)(vals)); but I still don't understand the original 'error'. Take a look at the return type of reverse.
Re: Virtual functions and inheritance
This is almost the same code as written initially, let somone explain why the hell this is working: --- module test; import std.conv; class Parent { @property final string typeName() { return to!string(this); } } class Child : Parent { } void main() { auto p = new Parent; auto c = new Child; assert(p.typeName == __MODULE__ ~ .Parent); assert(c.typeName == __MODULE__ ~ .Child); } --- Because to!string calls toString, which is a virtual function. It's the same as the NVI-Idiom in C++.
Re: shared Variant[string]
On Wednesday, 28 January 2015 at 12:29:09 UTC, Fyodor Ustinov wrote: On Wednesday, 28 January 2015 at 11:27:53 UTC, Kagamin wrote: Associative array doesn't support thread-safe operations, that's why they don't work on shared instance. You should use std.concurrency or implement low-level concurrency mechanism. If associative array does not support share attribute, this code should not be compiled without any warning or error, I think: shared string[string] t; void main() { t[t] = bebebe; } But will. In your case above, it's std.variant : Variant, which does not work when shared. You'll need to cast it and ensure yourself that no two threads access the same instance concurrently. I don't know, if AA should/do work with shared.
Re: Virtual functions and inheritance
- class Bar { static T construct(this T, A...)(A a) { return new T(a); } } I think it's a bug that you can use a template this parameter (this T) on a static member function without a direct compilation error. - class Bar { static typeof(this) construct(A...)(A a) { return new typeof(this)(a); } } Because it's exactly the same to write it as static Bar construct(A...)(A a) { return new Bar(a); } Of course this does not work. I don't know how to do it without one line of boilerplate per class or without supplying the type via template argument. std.container.util : make takes the type to construct as an argument, but std.container do not form a class hierarchy.
Re: crash on args.getopt
On Sunday, 25 January 2015 at 10:21:34 UTC, Suliman wrote: But is it good practice to fail with exception during passing unknown parameters? Maybe std.getopt.config.passThrough should be as default? I really can't remember Apps that crush if pass to in unknown parameters. Almost all programs fail with an error message, if you pass unknown parameter. Just catch that exception.
Re: using the full range of ubyte with iota
On Sunday, 25 January 2015 at 12:25:35 UTC, Dominikus Dittes Scherkl wrote: map!(x = fn(cast(ParameterTypeTuple!fn[0])x) but instead with map!(paramCast!fn) Because this is useful in more situations, e.g. in every place where you know the values would fit into the parameter (and for a single call would use a cast). But so far I couldn't manage to make this work :-/ http://dpaste.dzfl.pl/07b1fa3c2dad
Re: Sqlite
On Sunday, 25 January 2015 at 18:15:21 UTC, Paul wrote: I'd like to vary the query based on input but if I try to move the string out of the sqlite3_exec call like this: string sqlStatement = CREATE TABLE people(id INT PRIMARY KEY NOT NULL, surname TEXT NOT NULL);; result = sqlite3_exec(db, sqlStatement, aCallback, null, msg); ...it won't compile: Error: function etc.c.sqlite3.sqlite3_exec (sqlite3*, const(char)* sql,... is not callable using argument types (sqlite3*, string,... I can assign using: const char *sqlStatement = CREATE TABLE... So how do I get a constant character pointer that can be modified at runtime? Paul Only string literals convert to const(char)*, because only for them it is guaranteed that they are null terminated. For everything else use toStringz.
Re: using the full range of ubyte with iota
On Saturday, 24 January 2015 at 20:49:03 UTC, Dominikus Dittes Scherkl wrote: Maybe I'm just too stupid, but I cannot manage to call a simple function with all 256 possible values of ubyte with iote: int foo(ubyte c); auto myRange = iota(0,256).map!foo; -- Error: function foo(ubyte c) is not callable using argument types (int) and this is because of the f*** end-type cannot be ubyte because in phobos everywhere end is excluded, so I have to define it too large by one. Has anyone any idea how to work around this? I would have no problem using an explicit cast, but where should I apply it? iota(0, 256).map!(x = foo(cast(ubyte) x))
Re: crash on args.getopt
http://dlang.org/phobos/std_getopt.html But problem that I do not know how handle not existing values: void main(string[] args) { args.getopt ( help, help ); } app.exe -sss causes crash: std.getopt.GetOptException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\getopt.d(4 63): Unrecognized option -sss 0x00453F0E in @safe void std.getopt.getoptImpl!().getoptImpl(ref immutable(char) [][], ref std.getopt.configuration) at C:\D\dmd2\windows\bin\..\..\src\phobos\st d\getopt.d(463) Look for Passing unrecognized options through in the documentation.