std.range.only with different range types
--- import std.algorithm; import std.range; import std.stdio; void main(){ only(iota(0,4),[1,4,5]).writeln; } --- How can I call std.range.only with different range types?
generate with state
Is there a version of http://dlang.org/phobos/std_range.html#.generate with state.
Re: generate with state
On Tuesday, 3 November 2015 at 00:08:54 UTC, Ali Çehreli wrote: generate() already allows "callables", which can be a delegate: import std.stdio; import std.range; struct S { int i; int fun() { return i++; } } void main() { auto s = S(42); writefln("%(%s %)", generate().take(5)); } Prints 42 43 44 45 46 Will that allocate gc memory? Is there any why I pass state as a tuple and have my generator modify state as It's called?
Unionize range types
Is there any way I can Unionize range Types? --- auto primeFactors(T)(T t, T div = 2) { if (t % div == 0) { return t.only.chain(primeFactors(t / div, div)); } if (div > t) { return []; } else { return primeFactors(t, div + 1); } } ---
Re: good reasons not to use D?
On Friday, 30 October 2015 at 10:35:03 UTC, Laeeth Isharc wrote: I'm writing a talk for codemesh on the use of D in finance. I want to start by addressing the good reasons not to use D. (We all know what the bad ones are). I don't want to get into a discussion here on them, but just wanted to make sure I cover them so I represent the state of affairs correctly. So far what comes to mind: heavy GUI stuff (so far user interface code is not what it could be); cases where you want to write quick one-off scripts that need to use a bunch of different libraries not yet available in D and where it doesn't make sense to wrap or port them; where you have a lot of code in another language (especially non C, non Python) and defining an interface is not so easy; where you have many inexperienced programmers and they need to be productive very quickly. Any other thoughts? I would advise against using D in applications where memory is essential. Idiomatic D uses a garbage collector which has a non free runtime cost.
Re: std.algorithm.startsWith only predicate
On Sunday, 18 October 2015 at 17:58:30 UTC, Meta wrote: Is this a simplified use case of some actual code you have? Otherwise, you can just do: bool iden(string str) { auto f = str.front; return f.isAlpha || f == '_'; } It's simplified, i wanted to check for empty
std.algorithm.startsWith only predicate
How do you call startsWith with only a predicate --- import std.algorithm; import std.ascii; bool iden(string str) { return str.startsWith!(a => a.isAlpha || a == '_'); } ---
Alias lamda argument vs Type template argument
There are two these different ways to pass functions as template arguments. Which is preferred? --- void funcA(alias calle)() { calle(); } void funcB(T)(T calle) { calle(); } void main() { funcA!(() => 0); funcB(() => 0); } ---
How to use std.range.interfaces in pure @safe code
How do I use http://dlang.org/phobos/std_range_interfaces.html in pure @safe code?
Range of variables
Is there a way to make a range of a variables lazily? --- int var1; int var2; void func() { int var3; auto range = /*range of var1,var2,var3*/ ; } ---
address of overloaded function
How do you take the address of a specific overloaded function. This won't compile --- import std.range; void main() { ForwardAssignable!int range; int delegate() @property get = void delegate(int) @property set = } ---
scope in function argument
What does it mean when there is a scope in a function argument. --- void func(scope int* a){} ---
Reading dmd's source code
dmd's source code is very big, are there tips for reading it(important files)?
pragma(mangle, on a template)
I can't get pragma(mangle) to work on templates(or structs). import std.stdio; struct MyStruct(T...) { int var; void func() { writeln(var); } } pragma(mangle, MyAlias) alias MyAlias = MyStruct!(a, b, c /+very long symbol bloating list+/ ); void main() { auto v = MyAlias(2); v.func(); }
Re: Pointers to Dynamic Arrays
On Monday, 17 August 2015 at 02:45:22 UTC, Brandon Ragland wrote: if(file[(*pos + i)] == '}'){ *pos += i; return; } That code doesn't do what you want it do. file is a ((char[])*) you are indexing the pointer(accessing invalid memory) and getting a char[].
Re: pragma(mangle, on a template)
On Monday, 17 August 2015 at 03:14:16 UTC, Adam D. Ruppe wrote: On Monday, 17 August 2015 at 02:46:02 UTC, Freddy wrote: Mangling is done at a different level in the compiler than aliases, so I don't think this is intended to work. Is there any way I can mangle a template struct then?
Indivisual Incremental Compalation with dub
I have a file that takes a while to compile with a static interface. Is there any way i can make dub keep the object file of only that file(for faster compilation)?
ImplicitConversionTargets opposite
std.traits has ImplicitConversionTargets. Is there any template that returns the types that can implicty convert to T?
Associative array on the heap
How do you allocate an associative array on the heap? void main(){ alias A=int[string]; auto b=new A; } $ rdmd test test.d(4): Error: new can only create structs, dynamic arrays or class objects, not int[string]'s Failed: [dmd, -v, -o-, test.d, -I.]
Re: Associative array on the heap
On Tuesday, 19 May 2015 at 00:00:30 UTC, Meta wrote: On Monday, 18 May 2015 at 23:55:40 UTC, Freddy wrote: How do you allocate an associative array on the heap? void main(){ alias A=int[string]; auto b=new A; } $ rdmd test test.d(4): Error: new can only create structs, dynamic arrays or class objects, not int[string]'s Failed: [dmd, -v, -o-, test.d, -I.] They are allocated on the heap implicitly; there's no need for `new`. You actually *can't* use new with an AA, which is what the compiler is telling you. void main() { alias A = int[string]; A b = []; //No allocation yet, b is null b[test] = 1; //b is now non-null } Sorry mis-phrased my question, Who do you allocate a pointer to an associative array(int[string]*).
Re: Adding pointers to GC with destructers
On Monday, 20 April 2015 at 02:56:35 UTC, Ali Çehreli wrote: Not automatically. Check out addRange and addRoot: http://dlang.org/phobos/core_memory.html Ali The destructor doesn't seem to be running import std.stdio; import std.c.stdlib; import core.memory; struct Test{ ~this(){ writeln(free: ,this); free(this); } } void main(){ auto ptr=cast(Test*)malloc(4); writeln(create: ,ptr); GC.addRange(ptr,0,typeid(Test)); ptr=null; GC.collect(); } $ rdmd test create: 1EEC730
Re: Adding pointers to GC with destructers
On Monday, 20 April 2015 at 22:24:53 UTC, Ali Çehreli wrote: On 04/20/2015 02:48 PM, Freddy wrote: On Monday, 20 April 2015 at 02:56:35 UTC, Ali Çehreli wrote: Not automatically. Check out addRange and addRoot: http://dlang.org/phobos/core_memory.html Ali The destructor doesn't seem to be running Sorry, I misunderstood you. You can use a RAII object as ketmar said: import std.stdio; import std.c.stdlib; struct Test{ void* ptr; ~this(){ writeln(free: ,this); free(ptr); } } void main(){ auto ptr=cast(Test*)malloc(4); writeln(create: ,ptr); auto test = Test(ptr); // -- The dtor of this object will free } Ali I believe your original understanding was right.I want to have HiddenType* be garbage collected and finalized(freed,destructed) when no more references to it are found(stack or heap). I could use reference counting but it seems inefficient for a program rarely collecting and constantly coping.
Adding pointers to GC with destructers
C libraries have a pattern of HiddenType* getObj(); void freeObj(HiddenType*); Is there any way I can make the GC search for a HiddenType* and run freeObj when the pointer is not found.
final switch on Algebraic
Is there any way to do a final switch statement in std.variant's Algebraic.
strings and array literal mutability
Why are strings immutable but array literals are not?
Comparing function pointers
import std.stdio; auto test1(){ void testFunc(){ } return testFunc; } auto test2(){ uint a; void testFunc(){ a=1; } return testFunc; } void main(){ writeln(test1()==test1());//true writeln(test2()==test2());//false } Is the intended behavior?
Why does hello world not compile in safe?
import std.stdio; @safe: void main() { writeln(Edit source/app.d to start your project.); } source/app.d(5): Error: safe function 'D main' cannot call system function 'std.stdio.writeln!(string).writeln'
How does this work?
I know what this does, but can someone explain how it works? static if((typeof((inout int=0){ })));
Re: passing duck-typed objects and retaining full type information
On Tuesday, 11 November 2014 at 19:23:39 UTC, Adam Taylor wrote: * i apologize in advance, this is my first post -- the code formatting probably wont turn out so great... I have a bunch of duck typed interfaces for containers similar to what you would find in std.range. i.e. template isContainer(C) { enum bool isContainer = is(typeof( (inout int = 0) { C c = C.init; ... })); } template canRemoveFromContainer(C) { enum bool canRemoveFromContainer = isContainer!C is(typeof( (inout int = 0) { C c = C.init; c.remove(); })); } Now what i want to do is pass some such container object to an interface function: interface MyInterface { void filterCollisions(S)(S collisionCandidates) if(canRemoveFromContainer!S) } but of coarse templates and interfaces don't get along so well. so...so far as I know i would need to do something like this: interface MyInterface { final void filterCollisions(S)(S collisionCandidates) if(canRemoveFromContainer!S) { filterCollisionsImpl(...); } void filterCollisionsImpl(...) } and pass something to filterCollisionsImpl that is a proper class or interface type. So here's the problem: many of the duck-typed interfaces cannot be converted to proper interfaces without losing something. So is there ANY way to pass in a very basic class or interface Container type and call the remove function on it? Here's what i've tried: interface Container(C) { ... } template ContainerObject(C) if (isContainer!(Unqual!C)) { static if (is(C : Container!(ElementType!C))) { alias ContainerObject = C; } else static if (!is(Unqual!C == C)) { alias ContainerObject = ContainerObject!(Unqual!C); } else { static if (__traits(compiles, { enum e = C.ValueType; })) { alias ValueType = C.ValueType; } else { alias ValueType = ElementType!C; } class ContainerObject : Container!ValueType { C _container; this(C container) { this._container = container; } static if(canRemoveFromContainer!C) { size_t remove() { return _container.remove(); } } } } } ContainerObject!C containerObject(C)(C container) if (isContainer!C) { static if (is(C : Container!(ElementType!C))) { return container; } else { return new ContainerObject!C(container); } } interface MyInterface { final void filterCollisions(S)(S collisionCandidates) if(canRemoveFromContainer!S) { auto container = containerObject(collisionCandidates); container.remove(); // works just fine -- have the complete type info at instantiation site filterCollisionsImpl(); } void filterCollisionsImpl(Container!string collisionCandidates) collisionCandidates.remove(); // error -- some type info is lost here, only have a Container!string which doesn't have a remove function. } Not entirly sure of what you asking for,but have you tried inhertance? interface Base(C){ /+...+/ } interface Derived(C):Base!C{ /+...+/ }
Re: How the memory layout of global variable is reliable ?
On Wednesday, 22 October 2014 at 20:29:58 UTC, Cjkp wrote: Hello, I have an idea about a small code tool related to the application resources. It would rely on the assumption that some global variabled, sharing the same type and attributes, declared in group, are contiguous. In short I need to know if the following assertions are always true and reliable over time: -- import std.stdio; // used as base adress static string beg = ; // arbitrary generated by a tool and mixed at compile time. static string a = ; static string b = ; static string c = ; static string d = ; static string e = ; static string f = ; void main(string args[]) { void* offs = beg; assert( a == (offs + (size_t.sizeof * 2) * 1) ); // length + ptr assert( b == (offs + (size_t.sizeof * 2) * 2) ); // length + ptr assert( c == (offs + (size_t.sizeof * 2) * 3) ); // etc. assert( d == (offs + (size_t.sizeof * 2) * 4) ); } -- In a second time I need to be sure that the return tuple of the trait allMembers follow the declarations order. The documentation says that: The order in which the strings appear in the result is not defined. But so far, it looks like it's ordered according to the declaration (at least for a module containing only some global variables). Any other remarks about the topic are welcome. Plese don't do this, it's undefined behavior and could make you code invalid with a new compiler release or different compiler. If possible use static arrays instead. int[2] arr=[1,2]; @property auto ref b(){ return arr[1]; } ---
How would you dive into a big codebase
Is there any advice/tips for reading medium/big D codebases?
Re: building shared library from D code to import into cython
On Tuesday, 7 October 2014 at 20:55:59 UTC, Laeeth Isharc wrote: Hi. I am trying to create a shared library in D linked against phobos so that I may use this in a cython extension module for Python. Ultimately I would like to be able to use a D class or struct (via the C++ interface) and call it from within cython, since cython classes cannot be instantiated without the gil (and this prevents easy parallelisation). I feel a bit foolish asking the question as there is a nice example here for working with plain C using dmd as the linker, and using dmd and gcc to create a DMD shared library statically linked to phobos. However, I have not succeeded in creating a D library statically linked to phobos that works with cython and python, http://dlang.org/dll-linux.html#dso7 I tried it first with test C code to make sure I am able to get the C library/cython/Python interaction working. pytest.c: #include stdio.h long pytest(long a) { return a+1; } int main() { long a =pytest(100); printf(%ld,a); return 0; } pytestpy.pyx: cdef extern long pytest(long a) cpdef pytestpy(): return pytest(109) setup.py: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize setup( ext_modules = cythonize([ Extension(pytestpy, [pytestpy.pyx], libraries=[pytest], ) ])) command line: gcc -shared -o libpytest.so pytest.o python setup.py build_ext -i copied libpytest.so to /usr/local/lib python import pytestpy pytestpy.pytestpy() it works now try pytest.d import std.stdio; extern (C) long pytest(long a) { return a*2; } void main() { auto a =pytest(100); writefln(%d,a); } command line: rm pytestd.o rm libpytest.so rm /usr/local/lib/libpytest.so dmd -c pytest.d -fPIC gcc -shared -o libpytest.so pytest.o -defaultlib=libphobos2.so -L-rpath=/usr/local/lib python import pytestpy Traceback (most recent call last): File stdin, line 1, in module ImportError: /usr/local/lib/libpytest.so: undefined symbol: _D3std5stdio12__ModuleInfoZ I guess it is not linking to the D runtime, but I am not sure what I should be doing to fix. Any thoughts appreciated. (The next step I was going to try when this works was C++ interface vs importing as a Cython class, but I thought best to start simple). I am running this on 64 bit Fedora 20. Thanks. Laeeth. Since when does gcc have a -defaultlib option? --- $ man gcc | grep defaultlib object-file-name -llibrary -nostartfiles -nodefaultlibs This is useful when you use -nostdlib or -nodefaultlibs but you do -nodefaultlibs is used. -nodefaultlibs -nodefaultlibs is libgcc.a, a library of internal subroutines which -nodefaultlibs you should usually specify -lgcc as well. This --- and why do you have a main function when compiling a shared library? Anyway, I think the problem is that libpytest.so can't find libphobos2.so. Try adding libphobos2.so's location (/usr/lib/x86_64-linux-gnu/libphobos2.so on my linux mint) to your -rpath .
Re: Localizing a D application - best practices?
On Sunday, 28 September 2014 at 21:29:21 UTC, Cliff wrote: Coming from the C# world, all of localization we did was based on defining string resource files (XML-formatted source files which were translated into C# classes with named-string accessors by the build process) that would get included in the final application. For log messages, exception messages (because unhandled exceptions could make it to the user in the case of a bug) and format strings used for the above we would create a string table entry and this file would eventually get localized by the appropriate team. Is there a recommended pattern for applications in D that wish to do localization? Thanks. I personally recommend you do this --- void main(){ string name=import(mylang); } --- and add a folder with mylang with -J . eg: -Jenglish -Jspanish
Re: Dynamically loading a D dynamic library from a c++ program
On Friday, 26 September 2014 at 16:43:30 UTC, Olivier Leduc wrote: Hello, I need to use a C++ SDK to create a plugin an existing closed source c++ application and I would like to know if its possible to use D for that task. Would is be possible to port the SDK header files and call the exposed functions inside the C++ program from a D dynamic library? Is it possible at all? Thank you very much! Try looking at this: http://dlang.org/dll-linux.html
Re: Dynamically loading a D dynamic library from a c++ program
On Friday, 26 September 2014 at 16:43:30 UTC, Olivier Leduc wrote: Hello, I need to use a C++ SDK to create a plugin an existing closed source c++ application and I would like to know if its possible to use D for that task. Would is be possible to port the SDK header files and call the exposed functions inside the C++ program from a D dynamic library? Is it possible at all? Thank you very much! and this: http://dlang.org/cpp_interface.html remember to be carefill with passing gc pointers
Re: with (auto p = new ...)
On Tuesday, 23 September 2014 at 15:19:59 UTC, Andre wrote: Hi, I just wonder why with (auto p = new ...) is not working. It would be some syntax sugar in this scenario: with (auto p = new Panel()) { parent = this; text = bla; with (auto b = new Button()) { parent = p; // Here p is needed text = bla2; } } source\app.d(8): Error: expression expected, not 'auto' source\app.d(8): Error: found 'p' when expecting ')' source\app.d(8): Error: found '=' instead of statement ... Kind regards André have you tried this? --- import std.stdio; struct myStruct{ int c=299792458; } void main(){ with(new myStruct()){ writeln(c); } } ---
Re: with (auto p = new ...)
On Friday, 26 September 2014 at 19:59:56 UTC, Freddy wrote: On Tuesday, 23 September 2014 at 15:19:59 UTC, Andre wrote: Hi, I just wonder why with (auto p = new ...) is not working. It would be some syntax sugar in this scenario: with (auto p = new Panel()) { parent = this; text = bla; with (auto b = new Button()) { parent = p; // Here p is needed text = bla2; } } source\app.d(8): Error: expression expected, not 'auto' source\app.d(8): Error: found 'p' when expecting ')' source\app.d(8): Error: found '=' instead of statement ... Kind regards André have you tried this? --- import std.stdio; struct myStruct{ int c=299792458; } void main(){ with(new myStruct()){ writeln(c); } } --- opps, sorry I misread the quesion.
liblzma bindings in dub
How do you include liblzma bindings(https://github.com/D-Programming-Deimos/liblzma) in a dub project?
Mutable array with fixed length
How would you create a mutable array with a fixed(compile error when trying to change) length.
Re: Identifying 32 vs 64 bit OS?
On Monday, 11 August 2014 at 05:19:01 UTC, Jeremy DeHaan wrote: I am looking at these versions as described here: http://dlang.org/version.html There are X86 and X86_64 version identifiers, but these specifically mention that they are versions for the processor type. Can they also be used to determine if the OS is running in 32 vs 64 bits? They mean what the integer(or pointer) size for the executable code generated(change able with -m(32|64)) is when compiled. If you want to check if the target OS(not your code) is running 32 vs 64 bit you have to do system call for your target OS.
opApply outside of struct/class scope
I'm trying to implement a opApply outside of struct scope struct A{ int[] arr; } int opApply(ref A a,int delegate(ref int) dg){ return 0; } void main(){ A a; foreach(i;a){//i just want it to compile } } when i try compiling, the compiler errors: test.d(9): Error: invalid foreach aggregate a Is there any why i can put a opApply outside of a struct scope,if so is there any why that the opApply can be templated
Re: Can't build phobos
On Monday, 4 August 2014 at 10:30:40 UTC, Marc Schütz wrote: On Sunday, 3 August 2014 at 23:41:27 UTC, Freddy wrote: I am currently working on a phobos fork to include associative ranges, however the unittest fail when i try to build. How am a supposed test any unittests that i add. link:https://github.com/Superstar64/phobos/tree/associative_ranges $ ../dmd/src/dmd |head -1 DMD32 D Compiler v2.066-devel-9d6cef9 0.030s PASS std.algorithm 0.023s PASS std.array 0.034s PASS std.ascii 0.001s PASS std.base64 0.006s PASS std.bigint 0.003s PASS std.bitmanip 0.000s PASS std.complex 0.002s PASS std.concurrency 0.023s PASS std.conv 0.000s PASS std.cstream 0.001s PASS std.csv ** FAIL std.datetime core.exception.AssertError@std/datetime.d(1398): [2012-Apr-30 01:00:00] [2012-Apr-30 00:00:00] generated/linux/debug/32/unittest/libphobos2-ut.so(void std.datetime.SysTime.__unittestL1363_26()+0xd08) [0x41b35ea0] generated/linux/debug/32/unittest/libphobos2-ut.so(void std.datetime.__modtest()+0xdd) [0x41d6e6ed] generated/linux/debug/32/unittest/test_runner(bool test_runner.tester()+0x104) [0x8049524] generated/linux/debug/32/unittest/libphobos2-ut.so(runModuleUnitTests+0xd1) [0x42cce4c1] generated/linux/debug/32/unittest/libphobos2-ut.so(void rt.dmain2._d_run_main(int, char**, extern (C) int function(char[][])*).runAll()+0x2d) [0x42cedd45] generated/linux/debug/32/unittest/libphobos2-ut.so(void rt.dmain2._d_run_main(int, char**, extern (C) int function(char[][])*).tryExec(scope void delegate())+0x2a) [0x42cedcea] generated/linux/debug/32/unittest/libphobos2-ut.so(_d_run_main+0x152) [0x42cedc5a] generated/linux/debug/32/unittest/test_runner(main+0x14) [0x804968c] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3) [0x430a2a83] That's curious. I cannot reproduce this... Unfortunately I don't have time to look into it right now. Is it possible that the test uses the system's timezone definitions, which might somehow be buggy on your computer? That is probably it, I am going to commentout that line not stage it.
Can't build phobos
I am currently working on a phobos fork to include associative ranges, however the unittest fail when i try to build. How am a supposed test any unittests that i add. link:https://github.com/Superstar64/phobos/tree/associative_ranges $ ../dmd/src/dmd |head -1 DMD32 D Compiler v2.066-devel-9d6cef9 0.030s PASS std.algorithm 0.023s PASS std.array 0.034s PASS std.ascii 0.001s PASS std.base64 0.006s PASS std.bigint 0.003s PASS std.bitmanip 0.000s PASS std.complex 0.002s PASS std.concurrency 0.023s PASS std.conv 0.000s PASS std.cstream 0.001s PASS std.csv ** FAIL std.datetime core.exception.AssertError@std/datetime.d(1398): [2012-Apr-30 01:00:00] [2012-Apr-30 00:00:00] generated/linux/debug/32/unittest/libphobos2-ut.so(void std.datetime.SysTime.__unittestL1363_26()+0xd08) [0x41b35ea0] generated/linux/debug/32/unittest/libphobos2-ut.so(void std.datetime.__modtest()+0xdd) [0x41d6e6ed] generated/linux/debug/32/unittest/test_runner(bool test_runner.tester()+0x104) [0x8049524] generated/linux/debug/32/unittest/libphobos2-ut.so(runModuleUnitTests+0xd1) [0x42cce4c1] generated/linux/debug/32/unittest/libphobos2-ut.so(void rt.dmain2._d_run_main(int, char**, extern (C) int function(char[][])*).runAll()+0x2d) [0x42cedd45] generated/linux/debug/32/unittest/libphobos2-ut.so(void rt.dmain2._d_run_main(int, char**, extern (C) int function(char[][])*).tryExec(scope void delegate())+0x2a) [0x42cedcea] generated/linux/debug/32/unittest/libphobos2-ut.so(_d_run_main+0x152) [0x42cedc5a] generated/linux/debug/32/unittest/test_runner(main+0x14) [0x804968c] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3) [0x430a2a83]
Is there a way to map associative arrays
#!/usr/bin/rdmd import std.algorithm; import std.stdio; uint[uint] test; void main(){ test=[0:2 ,1:3 ,2:4]; writeln(test.map!(a=a-2)); } $ ./test.d ./test.d(8): Error: template std.algorithm.map cannot deduce function from argument types !((a) = a - 2)(uint[uint]), candidates are: /usr/include/dmd/phobos/std/algorithm.d(375): std.algorithm.map(fun...) if (fun.length = 1) Failed: [dmd, -v, -o-, ./test.d, -I.]
Re: Is there a way to map associative arrays
On Friday, 1 August 2014 at 23:22:06 UTC, bearophile wrote: Freddy: uint[uint] test; void main(){ test=[0:2 ,1:3 ,2:4]; writeln(test.map!(a=a-2)); } If you need keys or values you have .keys .values, .byKey, .byValue (the first two are eager). If you need both you are out of luck, and if you want to write safe code it's better to use a foreach loop. If you want to live dangerously you can use a test.byKey.zip(test.byValue). Take a look in Rosettacode, there are examples for all of them. Bye, bearophile Sorry, i wasn't very clear. I wanted to know if there a way to lazily change the look up operation eg: assert(test[1]==1); assert(test[2]==2);