Re: Check Instance of Template for Parameter Type/Value
On Mon, 19 Oct 2015 14:51:28 +, Stewart Moth wrote: > I'm working with a library that has template structs of mathematical > vectors that can sometimes be the type of an array I'm passing to a > function. > > The definition of the struct is like this: > > struct Vector(type, int dimension_){ ... } > > Where type is going to be an int/float/etc and dimension_ is 2/3/4. > > I could write a bunch of functions for each case, but I'd rather not... > I'd like to use something like the following: > > void foo(T)(Array!T array){ > if(isInstanceOf!(Vector, T)){ > //get type of T or check it //test if dimension_ is 2 or 3 or 4 > ... > } else { > //Non-vector stuff ... > } > } > > But to do that I need to check that parameters of T as if it were an > instantiated instance of Vector and I'm not sure how to accomplish > that... Can anyone help me out with what I need to do? Pattern matching! void foo(ArrayT : Array!VectorT, VectorT : Vector!(T, dimension), T, int dimension)(ArrayT arr) { static if (dimension >= 2 && dimension <= 4) { } else { } }
Re: Problem Benchmarking HashSet from containers-em
On Thu, 22 Oct 2015 11:55:37 +, Nordlöw wrote: > What's wrong? HashSet has a disabled default constructor; you need to supply the allocator instance to the constructor here https://github.com/nordlow/ justd/blob/master/containers_ex.d#L17
Re: Problem Benchmarking HashSet from containers-em
On Thu, 22 Oct 2015 19:41:08 +, Nordlöw wrote: > My existing call to > > auto set = HashSet!(E, Allocator)(); > > works for Mallocator as in > > https://github.com/nordlow/justd/blob/master/containers_ex.d#L17 > > but not for > > InSituRegion!(1024*1024, T.alignof) > > Why? Please, help. The HashSet defines different constructors based on the nature of tha allocator: https://github.com/economicmodeling/containers/blob/master/src/containers/hashset.d#L30 Specifically, if the allocator has zero state (like Mallocator), you do not pass an instance. If the allocator does have state, like InSituRegion, you need to pass an instance to the container's constructor.
Re: What does the -betterC switch in dmd do?
On Thu, 12 Nov 2015 19:37:41 +, TheFlyingFiddle wrote: > The description in dmd help says: omit generating some runtime > information and helper functions. > > What runtime information are we talking about here? My > understanding is that it's basically an experimental feature but > when (if) completed what subset of the language would still be > usable? I believe the purpose of the switch is to help folks who are trying to write for bare or embedded systems by not emitting references to the D runtime library and runtime module information. Whether it actually does that in its current implementation is another question.
Re: linux inotify on a std.process.ProcessPipes ?
On Mon, 16 Nov 2015 23:08:46 +, opla wrote: > Does anyone know if it's possible to monitor the events that happen on > the output stream of a piped process ? > > I'm stuck on doc: > > - https://www.win.tue.nl/~aeb/linux/lk/lk-12.html - > http://www.ibm.com/developerworks/library/l-ubuntu-inotify/ > - http://linux.die.net/man/2/inotify_add_watch > > inotify_add_watch second argument seems to be a file name. The only > thing available is a std.stdio.File with a handle. > > The goal is to create an asynchronous process with a least one > notification that would happen when the process terminates, maybe when > the output stream is written too. You can use poll on the file descriptor (which can be gotten with File.fileno). Basically something like this (untested): while (ImWaiting) { if (processPipes.stdout.eof) { // The child is done writing (has exited, generally speaking) } //TODO set up poll items pollfd pfd = { processPipes.stdout.fileno, POLLIN }; // Use 0 for timeout so that we don't wait; if you don't have anything else // to do, you can use a real timeout value if (1 == poll(&pfd, 1, 0)) { // New data is available on the child's stdout, do something with it } // Do other things, sleep, etc. }
Re: GTKD TreeView - Delete TreeView SubItem with Button?
On Fri, 20 Nov 2015 18:57:10 +, TheDGuy wrote: > Thanks for your reply, > > now it gets more clear for me but how am i able to access the TreeView > within the CustomButton-Class? If i declare TreeView and TreeStore > public i get "static variable list cannot be read at compile time"? > > auto list = new List(); > auto treeView = new LanguageTree(list); You need to declare them at the module scope but initialize them inside your main function, so: List list; LanguageTree treeView; then inside your main function: list = new List(); treeView = new LanguageTree(list);
Re: GTKD TreeView - Delete TreeView SubItem with Button?
On Fri, 20 Nov 2015 19:45:25 +, TheDGuy wrote: > So like this? > > public void remove(TreeIter iter) > { > this.remove(iter); > } > > If i do this, i get a stackoverflow error :( That's creating an infinite recursion as the method simply calls itself. Assuming the class inherits from ListStore, you can just erase the remove method entirely and let the base class handle it. If you want to do something extra, use: override void remove(TreeIter iter) { // Anything custom super.remove(iter); // Anything custom }
Re: GTKD TreeView - Delete TreeView SubItem with Button?
On Fri, 20 Nov 2015 19:34:01 +, TheDGuy wrote: > Thanks for your reply, > > is it also possible to do it like this? > Yeah, that'll work. > but now i get the error: > > "rowDeleted is not callable using argument types (TreeIter)"? rowDeleted is just to emit the signal that a row has been removed, not actually remove it. You probably want to use the ListStore's remove method.
Re: Compile time strings auto concatenation!?
On Fri, 20 Nov 2015 20:39:57 +, Ilya wrote: > Can DMD frontend optimize > string concatenation > ``` > enum Double(S) = S ~ S; > > assert(condition, "Text " ~ Double!"+" ~ ___FUNCTION__); > ``` > > to > > ``` > assert(condition, "Text ++_function_name_"); > > ``` > ? Yes this occurs as part of the constant folding I believe. $ cat test.d enum Double(string S) = S ~ S; void main(string[] args){ assert(args.length, "Text " ~ Double!"+" ~ __FUNCTION__); } $ dmd test.d $ strings test | grep Text Text ++test.main
Re: Palindromes
On Thu, 03 Dec 2015 21:40:05 +, Jim Barnett wrote: > TL;DR I couldn't figure out how to write `isPalindrome` in terms of > std.algorithm.mutation.reverse > > I recognize it's more efficient in terms of CPU time and memory than my > C++ solution, but I suspect there is a shorter expression to detect > palindromes if efficiency isn't the primary concern. So I am interested > in seeing implementations of `isPalindrome` that utilize > `std.algorithm.mutation.reverse`, or anyone who cares to enlighten me > why that might be a misguided thing to want. Thanks for reading. I don't think you want reverse because it works in-place; you'd need to make a copy to compare against. std.range.retro is probably what you're looking for: bool isPalindrome(R)(R range) if (isBidirectionalRange!R) { return range.equal(range.retro); } Obviously this does more work than strictly necessary, but has the brevity you're looking for.
Re: GC greediness
On Tue, 05 Jan 2016 16:07:36 +, Jack Applegame wrote: > On a server with 4GB of RAM our D application consumes about 1GB. > Today we have increased server memory to 6 Gb and the same application > under the same conditions began to consume about 3Gb of memory. > Does GC greediness depend on available RAM? My understanding is that the GC won't return collected memory to the OS unless a threshold relative the system total is crossed. You can use GC.minimize() from core.memory to decrease this. This could result in degraded performance.
Re: Index a parameter tuple with a run-time index
On Fri, 15 Jan 2016 20:52:46 +, Meta wrote: > And of course I'm proven wrong as soon as I post :) Sometimes I forget > how powerful D's code generation abilities are. Username doesn't check out, :(
Re: Speed of csvReader
On Thu, 21 Jan 2016 18:37:08 +, data pulverizer wrote: > It's interesting that the output first array is not the same as the > input byLine reuses a buffer (for speed) and the subsequent split operation just returns slices into that buffer. So when byLine progresses to the next line the strings (slices) returned previously now point into a buffer with different contents. You should either use byLineCopy or .idup to create copies of the relevant strings. If your use-case allows for streaming and doesn't require having all the data present at once, you could continue to use byLine and just be careful not to refer to previous rows.
Re: Temporarily protect array from garbage collection
On Thu, 24 Apr 2014 19:55:37 +, Lars T. Kyllingstad wrote: > Is it possible to temporarily prevent the garbage collector from > collecting a memory block even if there are no references to it? > > The use case is as follows: I want to call a C library function which > expects to take ownership of a buffer. It looks something like this: > > alias FreeFunc = extern(C) void function(void*, void*) > nothrow; > > extern(C) void foo(void* buf, size_t len, > FreeFunc free, void* ctx) nothrow; > > Here, 'buf' is a pointer to the buffer, 'len' is the length of the > buffer, 'free' is a function to deallocate the buffer when the library > is done with it, and 'ctx' is a user-supplied context pointer. Upon > deallocation, 'free' receives two parameters; the pointer to the buffer > and the context pointer. The latter can be anything, even null, as it > is just passed to 'free' and not used for anything else. > > Here is the problem: I want to be able to use a garbage-collected > dynamic array with this function, but I don't want to have to retain a > reference to it in my program. (I don't know when the C library will > call the free function.) In other words, I want something like this: > > extern(C) void myFree(void* ptr, void* ctx) > { > enableGCFor(ptr); > } > > auto arr = new int[123]; > disableGCFor(arr); > foo(arr.ptr, arr.length, &myFree, null); > arr = null; > > Is this at all possible? > > Thanks, > Lars You can use GC.addRoot() from core.memory before passing the pointer to the C function, then use GC.removeRoot in your myFree function.
Re: AES encryption with openssl bindings
On Fri, 25 Apr 2014 19:06:31 +, brad clawsie wrote: > hi everyone. > > I'm trying to symmetrically encrypt some text using the openssl > bindings. My code compiles and fails silently. Clearly there is > something very wrong with it - it could be my novice D skills, or my > misuse of the openssl binding. > > auto chunk = new ubyte[](16); > foreach(ref x; chunk) x = uniform!"[]"(ubyte.min, ubyte.max); > AES_KEY wctx; > AES_set_encrypt_key(chunk.ptr,128,&wctx); > > string s = "virident"; > ubyte[] b; > b = cast(ubyte[]) s; > ubyte[] e; > AES_encrypt(b.ptr,e.ptr,&wctx); > ubyte[] d; > AES_decrypt(e.ptr,d.ptr,&wctx); > writefln("%s",d); > > > Any clues? I am a D novice, so any spoonfeeding you could provide would > be helpful :) > > thanks! > Brad It doesn't look like you're allocating space for `e` or `d`, e.g. `auto e = new ubyte[](256);`, so those arrays have a length of 0, in which case the encrypt/decrypt functions are just trashing their way through memory.
Re: Socket server + thread: cpu usage
On Tue, 29 Apr 2014 17:16:32 +, Tim wrote: > Hi guys, > > I've the following snipped: > > TcpSocket oSocket = new TcpSocket(AddressFamily.INET); oSocket.bind(new > InternetAddress("127.0.0.1", 12345)); oSocket.blocking(false); > oSocket.listen(0); > > while(true) > { > try { > Socket oRequestSocket = oSocket.accept(); > > Request oRequest = new Request(oRequestSocket); > oRequest.start(); // Start request thread > } > catch (SocketAcceptException oException) > { > Thread.yield(); > } > } > > When I execute the code above, the while(true)-loop uses nearly 100% (1 > complete cpu). When I connect to the server multiple times (note that > each Request-Thread has it's own while(oRequestSocket.isAlive)-loop) the > cpu usage easily reaches 120, 130... 200 and more cpu usage. > > Is there anything I'm doing wrong? I don't want use blocking sockets... > how to handle 100 or 1000 connections when the main server thread > already consumes 1 cpu? If you use blocking sockets, you should probably spawn a new thread for each client. If you use non-blocking sockets, you need to use poll or select to wait for incoming connections or data.
Re: byCodePoint for a range of chars
On Tue, 20 May 2014 17:59:07 +, John Colvin wrote: > Given a range with element type char, what's the best way of iterating > over it by code-point, without filling an array first? > > Related to this: What's the status of std.utf and std.encoding? The > comments in std.encoding say that some functions supersede their std.utf > counterparts. Foreach on narrow strings automatically decodes, so it's as simple as: // assume UTF-8 encoded char[] myData = ... foreach (dchar codePoint; myData) ...
Re: Example of filtering a Linked List that hold a custom class (Tango)
On Thu, 05 Jun 2014 17:50:37 +, JJDuck wrote: > let say I have a Linked List(tango) that holds custom class and how do I > filter the LinkedList to extract the items that I want according to a > particular field (a integer field) from my custom class? > > Is it easier to do it using phobos' Array? > If it does, care to have an example on Phobos too? > > Thanks a lot Using Phobos this should work for any container type with a range interface: // Using a singly-linked list, but any container should work (MyClass[], RedBlackTree!MyClass, etc.) SList!MyClass slist = ... auto filtered = objs.filter!(o => o.myfield = 7);
Re: Run child process with null stdin/stdout
On Wed, 18 Jun 2014 19:37:58 +, David Nadlinger wrote: > Hi all, > > is there a platform independent way to do the equivalent of > "some_program < /dev/null > /dev/null" using std.process? > > I neither want to capture/print the standard output of the child process > nor have anything available on its input. > > Quite probably, I'm just missing something obvious… > > Cheers, > David `spawnProcess`: The optional arguments stdin, stdout and stderr may be used to assign arbitrary std.stdio.File objects as the standard input, output and error streams, respectively, of the child process. The former must be opened for reading, while the latter two must be opened for writing. For POSIX, seems like you could pass `File("/dev/null", "r")` for stdin and `File("/dev/null", "w")`. On Windows I believe you can use `File ("nul")` for the same effect.
Re: String cast error
On Thu, 19 Jun 2014 00:05:36 +, SomeRiz wrote: > Hi. > > My code running: > > http://dpaste.dzfl.pl/2183586524df > > Output: > > SerialNumber 927160020 (X = Some Numbers) > > How do I delete "SerialNumber" text? > > Example > > string SomeRiz = system(a); > > I get an error: > > b.d(10): Error: cannot implicitly convert expression (system(a)) > of type int to string > > Later; > > string SomeRiz = cast(string)system(a); > > I get an error 2: > > b.d(10): Error: cannot cast system(a) of type int to string > > > How do I delete "SerialNumber" text? > > I just, want to see the numbers: > > 927160020 > > Sorry for my bad english The problem is that `system` returns the process exit code (an integer), not the output of the process. Try using std.process.execute or std.process.executeShell.
Re: popcnt instruction
On Tue, 24 Jun 2014 16:34:42 +, Archibald wrote: > Hello, > I need to use the "popcnt" processor instruction in a performance > critical section. > Is there a way to do this in D? D's inline assembler is described here: http://dlang.org/iasm.html
Re: Converting from C const(dchar*) to dstring
On Tue, 24 Jun 2014 18:17:06 +, Danyal Zia wrote: > On Tuesday, 24 June 2014 at 17:59:41 UTC, Steven Schveighoffer wrote: >> const(dchar *)x = ...; >> >> // assuming 0 terminated dstring text = x[0..x.strlen].idup; >> >> -Steve > const(dchar)* x = "Hello\0"; > dstring text = x[0..x.strlen].idup; > writeln(text); > > Error: no property 'strlen' for type 'const(dchar)*' A dchar* strlen implementation: http://dpaste.dzfl.pl/a4053387d8a4
Re: popcnt instruction
On Tue, 24 Jun 2014 19:44:52 +, Archibald wrote: > Thanks for the answers. > Unfortunately it seems like popcnt isn't supported by D's inline > assembler. > What if I import it as an external C function, will I get optimal > performance? DMD 2.065 seems to support it. What compiler are you using and what errors are you getting?
Re: popcnt instruction
Also, see: http://forum.dlang.org/thread/alirjgygnwpifkijx...@forum.dlang.org
Re: std.algorithm.map - function by reference
On Tue, 24 Jun 2014 21:46:15 +, kuba wrote: > Hi there, > I was wondering if std.algorithm.map can take functions with > parameters passed by reference? The main point here is to avoid > unnecessary copies by perhaps I'm using the wrong tool for the > job. No, `map` is a _projection_ function and is not intended to perform modification in place. There has been discussion of an `each` function which would act as a sink and which could potentially pass by reference.
Re: Using two flags in conditonal compilation (version)
On Wed, 25 Jun 2014 20:24:30 +, Danyal Zia wrote: > Hi, In the development of my library, I'm in a position where I need to > add support for multiple compilers. For instance, supporting both the > assembly of LDC/DMD and GDC. I want to do something like: > > version(DigitalMars && LDC) > { > } > > However, it doesn't compile which forces me to rewrote the same code for > both DigitalMars and LDC > > version(DigitalMars) > { > } > > version(LDC) > { > } > > Is there a way to check both versions at the same time? (I can't seem to > find the solution through google, sorry) > > Thanks, > Danyal Zia I think you mean ||, not &&. The best way I know around this is to define enums: version (DigitalMars) enum compiler_DigitalMars = true; else enum compiler_DigitalMars = false; //... similar for LDC static if (compiler_DigitalMars || compiler_LDC) { ... } else { ... }
Re: Bidirectional PIPE, and do not wait for child to terminate
On Tue, 01 Jul 2014 13:00:47 +, seany wrote: > I read the manual here: > http://dlang.org/phobos/std_process.html#.spawnProcess > > However, I need to (I can not remember, nor can I find in the forums any > info thereon) create > > 1. Bidirectional Pipes - I would like to write something to a second > program (UNIX, resp GNU/LINUX environment) and listen to what it has to > say. > > 2. I would like to continue with my program when the child process has > spawned (the child process is guaranteed to terminate), unlike wait, and > trywait does not seem to guarantee that the parent process will > continue. > > Help? Please. A pipe can be unidirectional only, but you can use more than one. In this case, you want to create at least two files in the parent process, one open for writing and one for reading. Pass the one open for writing as the child's stdin, the one for reading as the child's stdout. This will allow you to write to and read from the child. Regarding your second question, spawnProcess is not blocking, so the parent process will continue execution immediately. Unless you mean you want the child process to outlive the parent, in which case... Having the parent terminate without causing problems for the child is a tricky issue. Here's why: when the parent terminates, the child is going to be unowned and have its stdin and stdout closed (because the parent's ends are closed). It is possible to reown the process (to nohup for instance), but I'm not sure what you can do about the closed stdin and stdout.
Re: zipWith or map
On Tue, 01 Jul 2014 17:49:53 +, Gecko wrote: > Hello, > is there a fancy way do a zipWith (map with multiple ranges). There is > no in std.algorithm, or does it have a different name? There is a zip function in std.range. It produces a range of tuples that you can then map over.
Re: Bidirectional PIPE, and do not wait for child to terminate
On Tue, 01 Jul 2014 13:00:47 +, seany wrote: > 1. Bidirectional Pipes - I would like to write something to a second > program (UNIX, resp GNU/LINUX environment) and listen to what it has to > say. BTW, for convenience, you probably want to use pipeProcess or pipeShell.
Re: Bidirectional PIPE, and do not wait for child to terminate
On Tue, 01 Jul 2014 20:42:14 +, seany wrote: > On Tuesday, 1 July 2014 at 15:32:31 UTC, Justin Whear wrote: > > >> A pipe can be unidirectional only, but you can use more than one. > > and what about FIFO or LIFO s? You can use the C mkfifo function (import core.sys.posix.sys.stat) to create new named pipes. Once created you should be able to open a FIFO with `File("blah.ipc", "rw")` in both processes. Because you aren't using the standard file descriptors, you can spawn the child process however you like.
Re: Bidirectional PIPE, and do not wait for child to terminate
On Tue, 01 Jul 2014 21:00:58 +, Justin Whear wrote: > On Tue, 01 Jul 2014 20:42:14 +, seany wrote: > >> On Tuesday, 1 July 2014 at 15:32:31 UTC, Justin Whear wrote: >> >> >>> A pipe can be unidirectional only, but you can use more than one. >> >> and what about FIFO or LIFO s? > > You can use the C mkfifo function (import core.sys.posix.sys.stat) to > create new named pipes. > > Once created you should be able to open a FIFO with `File("blah.ipc", > "rw")` in both processes. Because you aren't using the standard file > descriptors, you can spawn the child process however you like. Actually, if I recall correctly, trying to read and write a FIFO pipe from the same end is undefined behavior on Linux and illegal in Unix. If you really want a single "pipe" with two-way traffic, use a domain socket.
Re: Sparse Aggregate Assignment/Initialization (RAII)
On Mon, 07 Jul 2014 21:34:05 +, Nordlöw wrote: > However using this function through UFCS > > auto cx = new C().set!"x"(11); > > fails as > > algorithm_ex.d(1257,17): Error: template algorithm_ex.set cannot deduce > function from argument types !("x")(C, int), candidates are: > algorithm_ex.d(1242,7):algorithm_ex.set(string member, T, > U)(ref T a, in U value) if (isAggregateType!T && hasMember!(T, > member)) > > Instead I have to use > > auto c = new C(); set!"x"(c, 11); > > which is not as elegant. > > Why doesn't UCFS work here and is there a solution using DMD git master? You need to use `auto ref` to have this work with both classes and structs. A working version of your code here: auto dx = D().set!"x"(11); assert(dx.x == 11); On Mon, 07 Jul 2014 21:34:05 +, Nordlöw wrote: > Further Is there a cleverer way to do this without resorting to mixins? __traits(getMember, ...) is useful here, see this version of your code: http://dpaste.dzfl.pl/75e03fbec020
Re: Sparse Aggregate Assignment/Initialization (RAII)
On Mon, 07 Jul 2014 21:49:22 +, Justin Whear wrote: > On Mon, 07 Jul 2014 21:34:05 +, Nordlöw wrote: > >> However using this function through UFCS >> >> auto cx = new C().set!"x"(11); >> >> fails as >> >> algorithm_ex.d(1257,17): Error: template algorithm_ex.set cannot deduce >> function from argument types !("x")(C, int), candidates are: >> algorithm_ex.d(1242,7):algorithm_ex.set(string member, T, >> U)(ref T a, in U value) if (isAggregateType!T && hasMember!(T, >> member)) >> >> Instead I have to use >> >> auto c = new C(); set!"x"(c, 11); >> >> which is not as elegant. >> >> Why doesn't UCFS work here and is there a solution using DMD git >> master? > > You need to use `auto ref` to have this work with both classes and > structs. A working version of your code here: auto dx = > D().set!"x"(11); > assert(dx.x == 11); Copy and paste gone astray; should be this link: http://dpaste.dzfl.pl/3c33ad70040f
Re: Capture offset of matches in std.regex.matchAll?
On Mon, 07 Jul 2014 21:32:29 +, JD wrote: > I'm using a compile time regex to find some tags in an input string. Is > it possible to capture the offset of the matches in some way? Otherwise > I have to "calculate" the offsets myself by iterating over the results > of matchAll. > > Thanks, > Jeroen > > --- > > Example code: > > import std.stdio; > import std.regex; > > void main() > { > auto input = "{{ message }}"; > > auto ctr = ctRegex!(`(\{\{|\{\%|\{\#)?`, "s"); > > auto matches = matchAll(input, ctr); > >/* > auto offset = 0; > foreach(match;matches) > { > writeln(offset, ":", match); > ++offset; > } > */ > } What do you mean by offset? If you simply mean the index of the match, as your example seems to indicate, you can zip the matches with iota or sequence!"n". If you want the offset in the string where each match begins I think you're out of luck. I needed something similar a while ago and the best I could find was using the cumulative length of the pre property.
Re: Introspecting a Module with Traits, allMembers
On Wed, 09 Jul 2014 20:07:56 +, NCrashed wrote: > On Wednesday, 9 July 2014 at 20:04:47 UTC, Maxime Chevalier-Boisvert > wrote: >> auto members = [__traits(allMembers, "ir.ir")]; >> pragma(msg, members); > > Have you tried without quotes? > pragma(msg, __traits(allMembers, ir.ir)); Also, looks like it should be "ir.iir"
Re: Sum a lot of numbers...
On Thu, 10 Jul 2014 17:16:00 +, Alexandre wrote: > Hi :) > > I need to sum a list of numbers... but, when I calculate the sum of this > numbers, I got a simplify representation of sum: > > 2.97506e+,12 > > How I can make to get the correctly representation of this number ? A full decimal representation can be gotten with `format("%f", n);`
Re: Sum a lot of numbers...
On Thu, 10 Jul 2014 17:17:40 +, Justin Whear wrote: > On Thu, 10 Jul 2014 17:16:00 +, Alexandre wrote: > >> Hi :) >> >> I need to sum a list of numbers... but, when I calculate the sum of >> this numbers, I got a simplify representation of sum: >> >> 2.97506e+,12 >> >> How I can make to get the correctly representation of this number ? > > A full decimal representation can be gotten with `format("%f", n);` And if you need more than the default 6 digits of precision after the decimal, you can use a precision specifier, e.g. for 10 digits: `format ("%.10f", n)`
Re: Binary IO
On Thu, 17 Jul 2014 20:35:24 +, seany wrote: > Hello, > > What are the methods of unformatted binary IO in d? File.write seems to > use formatted ASCII . I would like to write a binary file that I cna > read in fortan. Similarly, I would like to write a file in Fortan, > unformatted IO, and read it using D. You have a few options: * The old std.stream -- this module is due for replacement, hopefully ASAP. * Use File.rawRead/rawWrite. These are intended for arrays, though they can be used to read single values. * Work with chunks of ubyte data and use std.bitmanip's read and write functions. The last option is probably your best option for producing good future- proof, idiomatic D code.
Re: Binary IO
On Thu, 17 Jul 2014 21:01:35 +, seany wrote: > Data is a built in type? what includefile do I need? No, just used as an example. What sort of data are reading from the binary file?
Re: Compile-Time Interfaces (Concepts)
On Thu, 17 Jul 2014 22:49:30 +, Nordlöw wrote: > AFAIK there is no compile-time variant of interfaces right? > > Why is that? > > Wouldn't it be nice to say something like > > struct SomeRange realize InputRange { > /* implement members of InputRange */ > } > > and then the compiler will statically check that that all members are > implemented correctly. > > I guess this requires some new syntax to describe what an InputRange is. > > Kind of like C++ Concepts. What benefits would accrue from adding this? Static verification that a structure implements the specified concepts? If so, you can simply do this instead: static assert(isInputRange!SomeRange);
Re: Compile-Time Interfaces (Concepts)
On Thu, 17 Jul 2014 23:06:30 +, bearophile wrote: > Justin Whear: > >> What benefits would accrue from adding this? Static verification that >> a structure implements the specified concepts? > > Not just that, but also the other way around: static verification that a > "Concept" is strictly sufficient for any instantiation of a specific > template. This is what Haskell/Rust do. > > Bye, > bearophile By this do mean replacing the template constraint `if (isInputRange!R)` syntax? If so, we need concept definition syntax, but we do not necessarily need a "struct realizes concept" syntax. And, in fact, I would argue against it as a static assert would continue to be sufficient.
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 15:15:36 +, Pavel wrote: > Ok, let me start with the sample code: > > import std.stdio; > import std.json; > > void main() { >scope(failure) writeln("FaILED!!"); >string jsonStr = `{ "name": "1", "type": "r" }`; >auto parsed = parseJSON(jsonStr); >string s = parsed["fail"].str; >writeln(s == ""); >writeln(s is null); >writeln(s); > } > > Running "rdmd app.d" doesn't produce any output. > Can anyone explain such a behavior??? > > > PS: Running dmd v2.065 on Linux x64. That's because it produces a segmentation fault, which rdmd masks for some reason. The `parsed["fail"]` should throw a range bounds exception-- not sure why it's not.
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 15:54:20 +, Pavel wrote: > On Thursday, 24 July 2014 at 15:48:32 UTC, Edwin van Leeuwen wrote: >> On Thursday, 24 July 2014 at 15:42:58 UTC, Pavel wrote: >>> On Thursday, 24 July 2014 at 15:38:06 UTC, John Colvin wrote: On Thursday, 24 July 2014 at 15:32:29 UTC, John Colvin wrote: > On Thursday, 24 July 2014 at 15:15:37 UTC, Pavel wrote: >> Ok, let me start with the sample code: >> >> import std.stdio; >> import std.json; >> >> void main() { >> scope(failure) writeln("FaILED!!"); >> string jsonStr = `{ "name": "1", "type": "r" }`; >> auto parsed = parseJSON(jsonStr); >> string s = parsed["fail"].str; >> writeln(s == ""); >> writeln(s is null); >> writeln(s); >> } >> >> Running "rdmd app.d" doesn't produce any output. >> Can anyone explain such a behavior??? >> >> >> PS: Running dmd v2.065 on Linux x64. > > It's a bug in std.json (you should get a segfault, not no output at > all) > > It is fixed now and I'm pretty sure it will be in 2.066 > > std.json has been improved a lot, but I would still recommend using > http://vibed.org/api/vibe.data.json/ instead perhaps "bug" is too strong a word, but it was a deficiency that is now corrected. You will get an exception thrown now and everything should work how you expect. >>> >>> Maybe. But still it's not the way I expect, any time you check for >>> non-existing property you must consider exception, which is very heavy >>> to deal with in such a situation. I'd rather expect to get null, >>> whenever I try to fetch non-existing property, and not an exception. >> >> You can turn your json object into an AA object and then use in to >> check for existence (I know it is not very intuitive): >> >> JSONValue[string] jsonAA = parsed.object; >> if ( "fail" in jsonAA ) >> s = jsonAA["fail"].str; >> >> >> >> >>> That's purely my point, and I don't claim to be right in this way. >>> It's up to Phobos maintainers to decide how to reprent JSON parsing >>> results. > > Guess what, here's a new snippet: > > import std.stdio; > import std.json; > > void main() { >scope(failure) writeln("FaILED!!"); >string jsonStr = `{ "name": "1", "type": "r" }`; >auto parsed = parseJSON(jsonStr).object; writeln("fail" in parsed); > } > > Output is: > null > > WAT?! > > Ofcourse, writing like: > > writeln(cast(bool)("fail" in parsed)); > > Produces "false"... but why on earth boolean expression would output > null? > > PS: Sorry, for such an emotional boom, I'm so frustrated right now. The `in` expression produces a pointer to the value in the container, not a bool. If the key is not present in the container, it returns the null pointer. So this test is working precisely as expected. Here are some common idioms for working with `in` and associative arrays: // if with declaration if (auto vptr = "fail" in parsed.object) writeln("here's the value: ", *vptr); else writeln("fail is not in the JSON"); // coerce to bool writeln(!!("fail" in parsed.object)); // get the value or a default value writeln(parsed.object.get("fail", someDefaultJson));
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 16:04:01 +, Pavel wrote: > > Thanks to all you folks who explained "in" operator for me. My bad. > Let's focus on the real problem, which is JSON wrapper class. Is it > needed? Wouldn't it be better to get AA from parseJSON? The following are valid JSON: auto json1 = parseJSON(`1`); auto json2 = parseJSON(`"foo"`); auto json3 = parseJSON(`[1, 2, 3]`); None of these fit naturally into an JSONValue[string] return type.
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 13:49:27 -0300, Ary Borenszweig wrote: > Nope, a JSON can only be an array or an object (hash). Ary, can you point out the place in the spec where this is specified? Not to be pedantic, but the spec only seems to define a "JSON value", not a "JSON document".
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 16:14:15 +, Pavel wrote: > On Thursday, 24 July 2014 at 16:09:25 UTC, Justin Whear wrote: >> On Thu, 24 Jul 2014 16:04:01 +, Pavel wrote: >>> >>> Thanks to all you folks who explained "in" operator for me. My bad. >>> Let's focus on the real problem, which is JSON wrapper class. Is it >>> needed? Wouldn't it be better to get AA from parseJSON? >> >> The following are valid JSON: >> >> auto json1 = parseJSON(`1`); >> auto json2 = parseJSON(`"foo"`); >> auto json3 = parseJSON(`[1, 2, 3]`); >> >> None of these fit naturally into an JSONValue[string] return type. > > Oh, man! You're wrong!!! Read: http://www.json.org/, and try putting "1" > or "foo" as JSON string here: http://jsonlint.com/ Nope, while the spec calls out objects and arrays as the structural elements of JSON, it never requires (anywhere that I can find) that a complete JSON document have one of these at the root. A valid JSON value is defined as "A JSON value can be an object, array, number, string, true, false, or null"[1] Thus the parseJSON function is defined as parsing as JSONValue. 1 http://www.ecma-international.org/publications/files/ECMA-ST/ ECMA-404.pdf, p2
Re: How to copy an object to separate allocated memory?
On Thu, 24 Jul 2014 17:05:17 +, Gary Willoughby wrote: > I was reading Ali's book (http://ddili.org/ders/d.en/index.html) > and saw this piece of code on how to get the true size of an object: > > MyClass* buffer = cast(MyClass*)GC.calloc(__traits(classInstanceSize, > MyClass) * 10); > > That got me thinking, how would i actually 'fill' this memory with > instances of that class? std.conv.emplace: http://dlang.org/phobos/std_conv.html#.emplace
Re: How to copy an object to separate allocated memory?
On Thu, 24 Jul 2014 17:07:29 +, Justin Whear wrote: > On Thu, 24 Jul 2014 17:05:17 +, Gary Willoughby wrote: > >> I was reading Ali's book (http://ddili.org/ders/d.en/index.html) >> and saw this piece of code on how to get the true size of an object: >> >> MyClass* buffer = cast(MyClass*)GC.calloc(__traits(classInstanceSize, >> MyClass) * 10); >> >> That got me thinking, how would i actually 'fill' this memory with >> instances of that class? > > std.conv.emplace: http://dlang.org/phobos/std_conv.html#.emplace Wow, the ninja'ing is strong today.
Re: Mocking serial device
On Thu, 24 Jul 2014 17:15:02 +, Alfredo Palhares wrote: > Hello, > > I am writing an application that connects to a serial device in > /dev/ttyUSB0 and trows some binary data back and forth. > > > How can i mock and run some unit testing without having to connect to > the device every time? How about capturing some data from the device and writing it to a file? When you want to test, open the test data file instead of the device file.
Re: D JSON (WAT?!)
On Thu, 24 Jul 2014 22:00:43 +, Pavel wrote: > On Thursday, 24 July 2014 at 16:09:25 UTC, Justin Whear wrote: >> On Thu, 24 Jul 2014 16:04:01 +, Pavel wrote: >>> >>> Thanks to all you folks who explained "in" operator for me. My bad. >>> Let's focus on the real problem, which is JSON wrapper class. Is it >>> needed? Wouldn't it be better to get AA from parseJSON? >> >> The following are valid JSON: >> >> auto json1 = parseJSON(`1`); >> auto json2 = parseJSON(`"foo"`); >> auto json3 = parseJSON(`[1, 2, 3]`); >> >> None of these fit naturally into an JSONValue[string] return type. > > Now we figured it out about JSON, but in that case: > Why not just use std.variant.Variant construct instead of JSONValue? While I suspect the reason is simply historical, it might be a type- safety/information problem as well. Variant can store values of essentially any type whereas JSON is strictly limited to a handful of simple types. Going from a JSON string to Variant might not be troublesome, but going from Variant to JSON string almost certainly would. That said, if you think it's worth it, I'd be up for reviewing a revamped std.json.
Re: pointer array?
On Wed, 30 Jul 2014 14:33:51 +, seany wrote: > In Ali's excllent book, somehow one thing has escaped my attention, and > that it the mentioning of pointer arrays. > > Can pointers of any type of pointed variable be inserted in an int > array? Using to!(int) perhaps? If not directly, then what else would > achieve the same effect? You can use an array of void*: http://dpaste.dzfl.pl/0d3ee1723192
Re: pointer array?
On Wed, 30 Jul 2014 15:44:14 +, seany wrote: > However some code is in C, legacy code, and for speed resons. So in some > cases, I would like to send a bunch of variables , ints, dubles and > floats to an external C function. The thing is, I do not always know the > number of variables, so my idea was to make an array of pointers (call > it stack), and then send the pointer to the stack itself to the C > function. Can you post the signatures of some of the C functions you're trying to interface with?
Re: Max/Min values in an associative array
On Wed, 06 Aug 2014 17:57:54 +, TJB wrote: > I am trying to find the max and min values in an associative array. Say > I have: > > double[char] bids; > bid['A'] = 37.50; > bid['B'] = 38.11; > bid['C'] = 36.12; > > How can I find the max and min values. I am thinking that I need to use > max and min functions from std.algorithm, but not sure how to. > > Thanks! > TJB Do you just need the min and max values or do you also need the keys of those values? If the former, here's a paste: http://dpaste.dzfl.pl/0bbf31278a25
Re: Very Stupid Regex question
On Thu, 07 Aug 2014 16:05:16 +, seany wrote: > obviously there are ways like counting the match length, and then using > the maximum length, instead of breaking as soon as a match is found. > > Are there any other better ways? You're not really using regexes properly. You want to greedily match as much as possible in this case, e.g.: void main() { import std.regex; auto re = regex("ab(cd)?"); assert("PREabcdPOST".matchFirst(re).hit == "abcd"); assert("PREabPOST".matchFirst(re).hit == "ab"); }
Re: Very Stupid Regex question
On Thu, 07 Aug 2014 10:22:37 -0700, H. S. Teoh via Digitalmars-d-learn wrote: > > So basically you have a file containing regex patterns, and you want to > find the longest match among them? > // Longer patterns match first patterns.sort!((a,b) => a.length > > b.length); > > // Build regex string regexStr = "%((%(%c%))%||%)".format (patterns); > auto re = regex(regexStr); This only works if the patterns are simple literals. E.g. the pattern 'a +' might match a longer sequence than 'aaa'. If you're out for the longest possible match, iteratively testing each pattern is probably the way to go.
Re: D JSON (WAT?!)
On Fri, 08 Aug 2014 14:07:33 +, Pavel wrote: > > I know that as per JSON spec there's no boolean type specified, only > separate true and false values, which are specified as type in > http://dlang.org/library/std/json/JSON_TYPE.html, so I guess the only > way to check boolean in JSONValue it is to write: > > if (json4.type == JSON_TYPE.True) { > } else { > } > > Am I right? That's right. Perhaps we need an `asBool` function or even an opCast!bool that returns false on FALSE, NULL, and possibly empty strings/ objects/arrays.
Re: Separate Printing Mantissa and Exponent of a Floating Point
On Mon, 11 Aug 2014 13:47:13 +, Nordlöw wrote: > Is there a way to separately stringify/print the mantissa and exponent > of a floating point? > > I want this in my pretty-printing module to produce something like > > 1.2 \cdot 10^3 > > instead of > > 1.2e3 > > I could of course always split on the e but that is kind of non-elegant, > I believe. If you're writing your own pretty-printer, you can extract those pieces using FloatRep[1] and print them however you like. 1. http://dlang.org/phobos/std_bitmanip.html#.FloatRep
Re: String Prefix Predicate
On Thu, 14 Aug 2014 17:17:11 +, Nordlöw wrote: > What's the preferrred way to check if a string starts with another > string if the string is a > > 1. string (utf-8) BiDir 2. wstring (utf-16) BiDir 3. dstring (utf-32) > Random std.algorithm.startsWith? Should auto-decode, so it'll do a utf-32 comparison behind the scenes.
Re: Ropes (concatenation trees) for strings in D ?
On Thu, 14 Aug 2014 05:57:17 +, Carl Sturtivant wrote: > This is the idea I mean. > http://citeseer.ist.psu.edu/viewdoc/download? doi=10.1.1.14.9450&rep=rep1&type=pdf > Here's a C++ implementation supported I think by gcc. > http://www.sgi.com/tech/stl/Rope.html > > Is there a D implementation of a rope out there somewhere? > > How is unicode handled? Just by using dchar? I was working on a D Rope implementation years ago (now lost to time), when I came across this article and ditched it: http://scienceblogs.com/goodmath/2009/02/18/gap-buffers-or-why-bother- with-1/ The short version is that while Ropes are interesting theoretically, they have a bad implementation complexity compared to much simpler structures which give more than adequate results for most tasks.
Re: iterate traits ?
On Tue, 19 Aug 2014 18:15:33 +, ddos wrote: > since i need to setup vertexpointers for opengl at runtime my next > question? - is it possible to evaluate the traits also at runtime? but > i'd also like to know how i can iterate them at compiletime > > thx in advance :) Take a look at this example: http://dpaste.dzfl.pl/2fdea78a49b6 A foreach becomes compile-time whenever the aggregate is a purely compile- time construct such as a tuple.
Re: Can you explain this?
On Wed, 20 Aug 2014 20:01:03 +, Colin wrote: > It looks veryhacky. > > I see 3 distinct parts playing a role in my confusion: > A) The 'is' keyword. What does it do when you have is(expression); > B) typeof( expression ); whats this doing? Particularly when the > expression its acting on is a closure that returns nothing? (at least as > far as I can see) > C) The closure expression: > (inout int = 0) { > // Check to see if I can do InputRangy stuff... > } > Why is there a need for that inout int = 0 clause at the start of it? > > Sorry for the long question! > > Thanks, > Colin Before the introduction of __traits(compiles, ...), `is(typeof(...))` was used. It works because the is expression evaluates to false if the contents don't have a type or are semantically invalid. So this code creates a delegate to test the various properties--if it would compile, the delegate has a type and `is` returns true. The inout int parameter is very hacky, see this thread: http://forum.dlang.org/thread/opykgvxbqqeleuikt...@forum.dlang.org#post-mailman.102.1396007039.25518.digitalmars-d-learn:40puremagic.com
Re: commercial application with D
On Mon, 15 Sep 2014 20:02:37 +, Andrey wrote: > Can I develop commercial application with D programming language? There isn't anything in licensing of DMD, GDC, LDC, or the standard library which would prevent you from using them to create commercial applications.
Re: sort using delegate as predicate
On Tue, 16 Sep 2014 16:19:10 +, Simon Bürger wrote: > The following code does not compile, because the custom predicate of > std.algorithm.sort is a template parameter, and therefore can only be a > function, but not a delegate. In C++, there is a variant of sort taking > a function-object as a second (run-time) parameter, but phobos does not > seems to have such a thing. It seems like a pretty common problem to me, > so does anyone have a solution? Bit of a workaround, but this should do it: sort!((a,b) => f.cmp(a, b))(data);
Re: sort using delegate as predicate
On Tue, 16 Sep 2014 16:38:04 +, Simon Bürger wrote: > >> sort!((a,b) => f.cmp(a, b))(data); > > does in fact compile, so i guess problem is solved. Thanks guys. Yes, this compiles because the lambda forms a closure over f. In some respects this might even be better than the C++ as there is the possibility for inlining because the lambda literal is passed by alias.
Re: Is there a function that reads the entire contents of a std.stdio.File?
On Tue, 16 Sep 2014 14:37:05 +, Jay wrote: > all the functions/methods i've come across so far deal with either > streams or just file names (like std.file.read) and there doesn't seem > to be a way to wrap a std.stdio.File in a stream (or is there?). i need > a function that takes a std.stdio.File and returns a string or byte > array. The short answer is no. I usually use something like this: // Lazy auto stream = stdin.byChunk(4096).joiner(); You can make it eager by tacking a `.array` on the end. Functions used are from std.stdio, std.algorithm, std.array.
Re: GC-less Hash-Tables (AA)
On Wed, 17 Sep 2014 10:39:05 +, Nordlöw wrote: > Have anybody cooked any GC-less variants of hash-tables (associative > arrays) that take keys and values with value semantics only. > > Similar to how > > X[] > > relates to > > std.containers.Array!X > > I need this to index my nodes in graphs with tens of millions of nodes. See our hashmap and hashset implementations here: https://github.com/economicmodeling/containers/tree/master/src/containers These containers are all certified GC-free.
Re: Function parameters from TypeTuple
On Fri, 17 Oct 2014 17:44:47 +, Tofu Ninja wrote: > Basicly what I am trying to do is have a function template that will > generate its parameters to be arrays of the types of a type tuple. > > So for instance the parameters of f!(int, char) would be (int[], > char[])... > > No matter what I try, the compiler vomits all over me... This what you're thinking of? http://dpaste.dzfl.pl/724bd2573e98
Re: Function parameters from TypeTuple
On Fri, 17 Oct 2014 11:56:31 -0700, Ali Çehreli wrote: > You want to write a function that takes an index and a number of arrays; > and returns an N-ary Tuple where N matches the number arrays passed to > the function: :p http://dlang.org/phobos/std_range.html#transversal
Re: Function parameters from TypeTuple
On Fri, 17 Oct 2014 20:25:26 +, Tofu Ninja wrote: > Yeah, the part that fixed it was Tuple! to tuple. Thanks for the help. I > think this fixes my problem. I think std.range.transversal already provides the functionality you're looking for. http://dlang.org/phobos/std_range.html#transversal
Re: Removing whitespace duplicates
On Mon, 20 Oct 2014 22:21:09 +, bearophile wrote: > Use std.string.tr. > > Bye, > bearophile std.string.squeeze might be more appropriate.
Re: Basic DerelictOrg and Deimos question
On Fri, 24 Oct 2014 18:04:13 +, WhatMeWorry wrote: > Just for clarity's sake, should I consider the DerelictOrg and Deimos > (packages, projects, or libraries) as separate from one another? Or > does DerelictOrg use Deimos behind the scenes? They are quite different. The Deimos packages are static bindings to the C libraries--requiring you to statically link. This, incidentally is why there is no Deimos binding for OpenGL: it cannot be statically linked (unless you go with a software implementation like MESA) because libGL is provided by the end user's video hardware drivers. If you're writing games or similar that you want to distribute, definitely go with the dynamic bindings that Derelict provides. It allows the end-user to use whatever version they already have installed.
Re: Need assistance translating this C++ template
On Mon, 27 Oct 2014 22:43:22 +, John wrote: > void opAssign(T2 val) Without looking at the rest of your code, looks like this line needs to be void opAssign(T2)(T2 val)
Re: readln with buffer fails
On Wed, 29 Oct 2014 23:10:10 +, dcrepid wrote: > On Wednesday, 29 October 2014 at 21:19:25 UTC, Peter Alexander wrote: >> You need to take a slice of the buffer: >> >> char[] buf = Input[]; >> readln(buf); >> // line now in buf >> >> The reason for this is because you need to know where the string ends. >> If you just passed in Input, how would you know how long the line read >> was? > > Thanks, that solves the problem. I guess what confuses me is that Input > isn't a slice, or at least not implicitly convertible to one. > > Also, I've tried using Input[] directly at the callsite but apparently > that would be an rValue, and D doesn't do rValues yet. Part of what readln does is *modify* the slice itself, not just the pointed-to characters. In particular it alters the length member so that you know how much input was actually read. This is also why the rvalue reference shouldn't work. Remember, D chose not to repeat C's mistake of relying on null terminators.
Re: Curiously Cyclic Template Pattern causes segfault?
On Wed, 05 Nov 2014 20:48:06 +, Patrick Jeeves wrote: > When I tried to test out the following code the compiler segfaulted: > > Is there some rule against doing this or is it a glitch? Please file a bug report on issues.dlang.org --any compiler crash is a bug regardless of whether the source is valid D code or not.
Re: undefined reference to `_D5xxxx6yyyyy12__ModuleInfoZ'
On Wed, 05 Nov 2014 23:48:21 +, bioinfornatics wrote: > Dear, > > maybe I'm too tired to see my errors or they are a bug. See below > > I have this: > . > |-- fasta.d `-- src > `-- nicea > |-- metadata.d |-- parser.d `-- range.d > > when I try to build it: > > $ dmd -I./src/ ./fasta.d 2>&1 fasta.o:(.rodata+0x1f8): undefined > reference to `_D5nicea6parser12__ModuleInfoZ' > collect2: error: ld returned 1 exit status --- errorlevel 1 > > If I merge all files in one that build! > > What is it ? > > I tried to minimize the problem with dustmite but it give to me at end > an empty file … > > thanks You have dmd only building the fasta.d file and the linker doesn't know where to find the other objects. If you've compiled the contents of nicea to a static library (.a) with -lib, then you need to link that library by tacking a `-Llibnicea.a` onto your compilation command.
Re: transversal sum
On Thu, 06 Nov 2014 16:57:48 +, Marc Schütz wrote: > On Thursday, 6 November 2014 at 15:53:27 UTC, Jack Applegame wrote: >> I have rectangular forward range of forward ranges (not arrays): >> [ >> [a11, a12, ... a1N], >> [a21, a22, ... a2N], >> ... >> [aM1, aM2, ... aMN] >> ] >> >> I need lazy forward range: >> [ >> a11 + a21 + ... aM1, >> a12 + a22 + ... aM2, >> ... >> a1N + a2N + ... aMN >> ] >> Range of sum elements of every columns; >> >> M, N - runtime values; >> >> Is there a way to do this using only Phobos algorithms and range >> functions? > > Untested: > > import std.algorithm: map, sum; > auto rangeOfSums = rectangularRange.map!(r => r.sum); This would sum along the wrong dimension. I think the correct solution will make use of std.range.frontTraversal, but it will be a bit more complex due to needing to sum every column. std.range.traversal would make it easy, but it requires random access.
Re: transversal sum
On Thu, 06 Nov 2014 17:08:23 +, Justin Whear wrote: > I think the correct solution > will make use of std.range.frontTraversal, but it will be a bit more > complex due to needing to sum every column. std.range.traversal would > make it easy, but it requires random access. That should be std.range.frontTransversal and transversal.
Re: is there any reason UFCS can't be used with 'new'?
On Mon, 10 Nov 2014 19:07:38 +, Suliman wrote: > I can't understand how to use UFCS with instance of class: > > void main() > { > > string name = "Suliman"; > userName username = new userName(name); > > /// How to use UFCS here? > userName.name.sayHello(); > /// > } > > class userName { > string name; > > this(string name) > { > this.name = name; > } > > void sayHello(string name) > { > writeln(name); > } > } This has nothing to do with new--you're trying to use a virtual function scoped to class userName with a string. Rewrite it to a static module-scoped function: class userName { string name; this(string name) { this.name = name; } } void sayHello(string name) { writeln(name); } void main() { string name = "Suliman"; userName username = new userName(name); userName.name.sayHello(); }
How to share modules when using -shared?
I'm trying to build components that I can dynamically link and keep running into an issue with sharing modules between the host and the pluggable components. Assuming a layout like this: host.d -- loads components at runtime a.d -- a module that builds to `a.so` b.d -- a module that builds to `b.so` common.d If a.d and b.d both import common.d, all is well. If host.d imports common.d as well, I get this at runtime: Fatal Error while loading 'a.so': The module 'common' is already defined in 'host'. Test session with sources here: http://pastebin.com/LxsqHhJm Some of this can be worked around by having host.d use its own extern definitions, but how does this work with interfaces? My tests thus far have resulted in object invariant failures.
Re: Conditional functions
On Mon, 05 Jan 2015 17:47:09 +, Dominikus Dittes Scherkl wrote: > Is it possible to use static if in a template structure to have some > member functions only for specific types? Yep. This is actually a frequently used pattern in functions that return ranges.
Re: string concatenation with %s
On Wed, 07 Jan 2015 16:38:23 +, Suliman wrote: > I except that writefln have some behavior as string concatenation, but > it does not. > > IS there any way to put needed values in place of %s in string? std.string.format interpolates string with the same behavior as writefln but returns the resulting string instead of printing it.
Re: For those ready to take the challenge
On Fri, 09 Jan 2015 13:50:28 +, eles wrote: > https://codegolf.stackexchange.com/questions/44278/debunking- stroustrups-debunking-of-the-myth-c-is-for-large-complicated-pro Was excited to give it a try, then remembered...std.xml :(
Re: For those ready to take the challenge
On Fri, 09 Jan 2015 17:18:42 +, Adam D. Ruppe wrote: > Huh, looking at the answers on the website, they're mostly using regular > expressions. Weaksauce. And wrong - they don't find ALL the links, they > find the absolute HTTP urls! Yes, I noticed that. `http://app.js"`>` isn't a "hyperlink". Wake up sheeple!
Re: generate an array of 100 uniform distributed numbers
On Thu, 22 Jan 2015 19:26:44 +, ddos wrote: > hi guys, firstly this has no direct application, i'm just playing around > and learning > > i want to create 100 uniform distributed numbers and print them my first > attempt, just written by intuition: > [0 .. 100].map!(v => uniform(0.0, 1.0).writeln); > > i found out i can't write [0 .. 100] to define a simple number range, > but is there a function to do so? The iota function from std.range: iota(0, 100).map!(...) > > second attempt, replacing the range with an simple array [0,1,2].map!(v > => uniform(0.0,1.0).writeln); > this does compile and run, but doesn't print anything, just an empty > string, why is that? Two issues: 1) The function supplied to map should be a projection function, e.g. it takes a value and returns a value. Your lambda returns void (the result of writeln). 2) map is lazy--it doesn't do any work until something consumes it. This is awesome for many reasons (e.g. you can process infinite ranges). Nothing in your code is causing the result of map to be consumed, so it does no work. > finally i got it working with this: > auto t = [0,1,2].map!(v => uniform(0.0,1.0)); > writeln(t); This works because writeln eagerly consumes the result of map, causing the work to actually be done. If you like, you can tack the writeln to the end of the pipeline: auto t = [0,1,2].map!(v => uniform(0.0,1.0)).writeln;
Re: About variant
On Tue, 27 Jan 2015 20:46:59 +, bioinfornatics wrote: > void main(){ > auto a = Alpha!(int)( 6); > auto b = Alpha!(string)( "hello"); The Alpha struct is not a template, only the constructor is. Remove the explicit instantiations and IFTI does the work: > void main(){ > auto a = Alpha( 6); > auto b = Alpha( "hello");
Re: Float to string with more digits?
On Tue, 24 Feb 2015 20:04:04 +, Almighty Bob wrote: > Is there a more accurate way to do a float and or double to string > than... > > to!string(float); > > As that seems to limit itself to 6 digits. Use std.string.format or std.format.formattedWrite. std.format contains a description of the various format specifiers. You'll probably want something like "%.12f", which formats a floating point number with 12 digits of precision.
Re: ctags
On Mon, 20 Apr 2015 20:14:34 +0200, Robert M. Münch wrote: > Hi, is there anything for D that supports generating tags files like > ctags does for C etc. ? Dscanner: https://github.com/Hackerpilot/Dscanner#ctags-output
Re: Duplicate another function's parameters in a template function
On Mon, 20 Apr 2015 22:50:52 +, Tofu Ninja wrote: > I am trying to write a template function that can take another function > as an alias template argument and duplicate its parameters for it self. > > I tried.. > > auto pass(alias f, T...)(T t) > { > // other stuff... return f(t); > } > > but that does not work if there is a ref parameter. > > Thanks See std.functional.forward: http://dlang.org/phobos/std_functional.html#.forward
Re: Structural exhaustive matching
On Tue, 21 Apr 2015 15:36:27 +, Jadbox wrote: > What's the best equivalent to Rust's structural enum/pattern (match)ing? > Is it also possible to enforce exhaustive matches? > Basically, I'm curious on what the best way to do ADTs in D. std.variant.Algebraic implements ADTs: import std.variant, std.string; struct Foo { ... } alias A = Algebraic!(int, double, Foo); A a = 1; // std.variant.visit enforces that all possible types are handled, so this // is an error: auto res = a.visit!( (int x) => format("Got an int: %s", x), (double x) => format("Got a double: %s", x), (Foo x) => "Got a Foo" ); You can also dispatch to a function with the appropriate overloads/ template instantiations like so: foreach (T; A.AllowedTypes) if (a.type is typeid(T)) myfunc(a.get!T); This also exhaustively guarantees that myfunc can be called with all possible types of a.
Re: Readonly-to-outside variable
On Tue, 28 Apr 2015 19:30:04 +, tcak wrote: > Is there any way to define a variable or an attribute as read-only > without defining a getter function/method for it? > > Thoughts behind this question are: > 1. For every reading, another function call process for CPU while it > could directly read the value from memory. > > 2. Repetition of same name for variable and getVariableName. (Some might > not agree with this but I like the code when it looks nice.) 1. I wouldn't worry too much about the performance--compiling with gdc or ldc with inlining should reduce it to a simple access. 2. You can clean it up if it annoys you with something like this: mixin template readonly(T, string name) { mixin(`private T _`~name~`;T `~name~`()@property{return _`~name~`;}`); } Use it like: class Foo { // injects a private int _x, public int x() mixin readonly!(int, "x"); }
Re: Create a case-insensitive startsWith
On Tue, 28 Apr 2015 21:45:07 +, PhilipDaniels wrote: > Beginner question. Given > >if (startsWith(input, "0x", "0X")) > > How do I turn that into a case-insensitive startsWith? startsWith says > it takes a predicate but I can't figure out how to pass it one. The > examples all use "a == b" !? These attempts below, and other things I > have tried, fail with "cannot deduce function from argument types". > >if (startsWith!"icmp(a, b) == 0"(input, "0x")) >if (startsWith!"std.uni.icmp(a, b) == 0"(input, "0x")) >if (startsWith!((a,b) => icmp(a,b) == 0)(input, "0x")) The issue is that those icmp functions take strings as arguments while startsWith expects the predicate to take individual characters. I believe the best solution here is to use the lazy toLowerCase function in std.uni and the default predicate: if (startsWith(input.toLowerCase, "0x".toLowerCase))
Re: Create a case-insensitive startsWith
Note that my solution relies on the pre-release version of std.uni, those lazy functions aren't in the latest release.
Re: Example from d-idioms is incorrect
On Thu, 30 Apr 2015 21:30:34 +, TheGag96 wrote: > Was the behavior of the remove() function changed recently? Thanks guys. I believe remove has always worked this way. What you're seeing is explained by this note in the documentation for remove: > The original array has remained of the same length because all > functions in std.algorithm only change content, not topology. The value > 8 is repeated because std.algorithm.move was invoked to move elements > around and on integers move simply copies the source to the > destination. To replace a with the effect of the removal, simply assign > a = remove(a, 1). The slice will be rebound to the shorter array and > the operation completes with maximal efficiency.
Re: Linker command
On Wed, 06 May 2015 19:52:42 +, Paul wrote: > On Wednesday, 6 May 2015 at 19:30:33 UTC, anonymous wrote: >> On Wednesday, 6 May 2015 at 19:26:40 UTC, Paul wrote: >>> but I don't understand the syntax. dmd --help mentions -Llinkerflag >>> but what is '-L-L.' doing?? >> >> Passes '-L.' to the linker. > > :D I can see that, but what does '-L.' mean exactly? It adds '.' to the list of directories which the linker will search when looking for the required libraries.
Re: Bitfield-style enum to strings?
On Thu, 07 May 2015 16:55:42 -0400, Nick Sabalausky wrote: > // There's gotta be a better way to convert EnumMembers!T // to a > range, right? But std.range.only() didn't work, // due to a > template instantiation error. > T[] members; > foreach(m; EnumMembers!(T)) > members ~= m; T[] members = [ EnumMembers!T ];
Re: Baffled by compilation error for formattedRead
On Thu, 07 May 2015 23:10:26 +, PhilipDaniels wrote: > Why do the first two fail to compile but the last one does?! I cannot > see any difference between the 's2' case and the second case, it is a > completely mechanical source code transformation I have made. formattedRead takes its input by ref and consumes it. Your first two attempts are both passing the result of functions (dropExactly and opSlice) which are temporary rvalues and can thus not be passed by reference. Here's more reading on the subject of rvalues: http:// ddili.org/ders/d.en/lvalue_rvalue.html
Re: Casting MapResult
On Mon, 15 Jun 2015 15:10:20 +, jmh530 wrote: > So I suppose I have two questions: 1) am I screwing up the cast, or is > there no way to convert the MapResult to float[], 2) should I just not > bother with map (I wrote an alternate, longer, version that doesn't use > map but returns float[] properly). MapResult is a wrapper around your original range that performs the mapping operation lazily. If you want eagerly evaluate and get back to an array use the std.array.array function: import std.array : array; auto y = x.map!(a => exp(a)).array; Or if you have already allocated an array of the appropriate size you can use std.algorithm.copy: import std.algorithm : copy; float[] y = new float[](appropriate_length); x.map!(a => exp(a)).copy(y);
Re: Process a TypeTuple
On Mon, 15 Jun 2015 04:06:12 +, Baz wrote: > On Monday, 15 June 2015 at 03:53:35 UTC, Yuxuan Shui wrote: >> Is it possible to apply some operation on every member of a TypeTuple, >> then get the result back? >> >> Say I have a TypeTuple of array types, and I want a TypeTuple of their >> element types, how could I do that? For this particular example you use std.range.ElementType: import std.typecons, std.range; alias Elements = staticMap!(ElementType, MyRangeOrArrayTypes);
Re: Return types of the methods of a struct
On Fri, 19 Jun 2015 13:27:13 +, Quentin Ladeveze wrote: > > Is there any way to have a asTuple method in this struct that would > returns something like : > > Tuple!(int, "a", float, "b", string, "c") > > and that will contain the values of the methods of the struct ? > > Thanks. You'll want to work your way through this example carefully as it's basically template-based functional programming, but I think does what you want: http://dpaste.dzfl.pl/b048ea3adb93
Re: Why aren't Ranges Interfaces?
On Fri, 26 Jun 2015 19:26:56 +, Jack Stouffer wrote: > Thanks for the reply! I understand the reasoning now. > > On Friday, 26 June 2015 at 18:46:03 UTC, Adam D. Ruppe wrote: >> 2) interfaces have an associated runtime cost, which ranges wanted to >> avoid. They come with hidden function pointers and if you actually use >> it through them, you can get a performance hit. > > How much of a performance hit are we talking about? Is the difference > between using an interface and not using one noticeable? For some real numbers, a while back I wrote up several variations on a "big data" type process for a presentation on memory performance and the importance of cache hits. The classic Java-style class-based version ran in 4 seconds while the lazy range struct version ran in 0.83 seconds. Using LDC to inline (impossible with interfaces) brought the runtime down to 0.38 seconds.