Re: rotate left an array
On Mon, Oct 03, 2022 at 05:38:25PM -0700, Ali Çehreli via Digitalmars-d-learn wrote: [...] > Good catch but I think what we want is a copy of the front element, at > least for InputRanges (.save does not work for File.byLine :/). One of the things we need to settle in Phobos v2 is what to do with transient ranges like File.byLine (i.e., ranges whose .front value is invalidated by .popFront). When you don't need to access each line after calling .popFront, .byLine's current implementation reduces allocations and decreases GC pressure. However, when you do need to save it, it produces counterintuitive results, like here. > What is the generic way of copying an element? I wonder whether we > have to use isSomeString to take care of all element types. [...] This was discussed many years ago. There is no generic way to copy an element, because there is no language-wide .clone method that enforces the right semantics for every type. You cannot simply deep-copy something, as might be a tempting solution at first glance, because you cannot tell, for an arbitary type, whether a reference member is meant to be an owning reference (the referent needs to be cloned) or a non-owning reference (the referent should not be cloned). Both are valid use cases, and there is no way to distinguish between them without contextual knowledge of the type. For example, if your range is generating, say, a tree of objects each time .popFront is called, then you probably want to deep-copy the object tree when you're saving the element. However, if the range is iterating over, say, some nodes in a preexisting graph, then you probably *don't* want to be duplicating graph nodes when you save the value of .front, because in this case .front merely references these nodes, it doesn't own them. Without application-specific knowledge, you can't tell which of these cases you're dealing with. T -- Customer support: the art of getting your clients to pay for your own incompetence.
Re: rotate left an array
On Tuesday, 4 October 2022 at 00:38:25 UTC, Ali Çehreli wrote: Good catch but I think what we want is a copy of the front element, at least for InputRanges (.save does not work for File.byLine :/). What is the generic way of copying an element? I wonder whether we have to use isSomeString to take care of all element types. AFAIK there is no generic way to perform a deep copy of an arbitrary value in D. You could write a function to do it for all built-in types, but you might still run into trouble with user-defined types (e.g., how do you deep-copy a RefCounted!T without any knowledge of its specific semantics?). I guess you could use a hybrid approach; e.g., static if (isDeepCopyable!(ElementType!R)) auto fr = range.front.deepCopy; else auto fr = range.front.save; This would make it possible to accommodate some pure input ranges (including File.byLine), but would still require a forward range in the general case.
Re: rotate left an array
On 10/3/22 23:06, Ali Çehreli via Digitalmars-d-learn wrote: auto rotatedView(R)(R range) Or even more generic by chaining two slices in case the range permits it: auto rotatedView(R)(R range, long n = 1) if (...) { if (n == 0) return range; ... n %= range.length; ... return chain(slice1, slice2); } Used something like that in previous advent of code challenges where they expect you to go for doubly linked lists due to large buffer size.
Re: rotate left an array
On 10/3/22 17:00, Paul Backus wrote: > On Monday, 3 October 2022 at 21:06:36 UTC, Ali Çehreli wrote: >> On 10/3/22 13:48, Andrey Zherikov wrote: >>> a "rotated view". >> >> Without indexes: >> >> import std.range : empty; >> >> auto rotatedView(R)(R range) >> in (!range.empty) >> { >> import std.range : chain, front, only, popFront; >> const fr = range.front; >> range.popFront(); >> return chain(range, only(fr)); >> } > > Tiny nitpick: this should use > > const fr = range.save.front; > > ...to ensure that `fr` is not invaliated or overwritten by the > subsequent call to range.popFront (e.g., think of File.byLine here). Good catch but I think what we want is a copy of the front element, at least for InputRanges (.save does not work for File.byLine :/). What is the generic way of copying an element? I wonder whether we have to use isSomeString to take care of all element types. Ali
Re: rotate left an array
On Monday, 3 October 2022 at 21:06:36 UTC, Ali Çehreli wrote: On 10/3/22 13:48, Andrey Zherikov wrote: a "rotated view". Without indexes: import std.range : empty; auto rotatedView(R)(R range) in (!range.empty) { import std.range : chain, front, only, popFront; const fr = range.front; range.popFront(); return chain(range, only(fr)); } Tiny nitpick: this should use const fr = range.save.front; ...to ensure that `fr` is not invaliated or overwritten by the subsequent call to range.popFront (e.g., think of File.byLine here).
Re: rotate left an array
On 10/3/22 13:48, Andrey Zherikov wrote: a "rotated view". Without indexes: import std.range : empty; auto rotatedView(R)(R range) in (!range.empty) { import std.range : chain, front, only, popFront; const fr = range.front; range.popFront(); return chain(range, only(fr)); } void main() { import std.algorithm : equal; int[] arr1 = [ 1, 2, 3, 4 ]; assert(arr1.rotatedView.equal([ 2, 3, 4, 1 ])); // Now this is getting a little expensive! :) assert(arr1 .rotatedView .rotatedView .equal([ 3, 4, 1, 2 ])); } Ali
Re: rotate left an array
On Monday, 3 October 2022 at 18:09:05 UTC, Fausto wrote: Hello all, I am trying to rotate left an array. I found a very basic way, and I am not sure if there is something clever than this :) maybe using slices... the external for represents how many times you are rotating (in this case 2). If you don't need to add or remove the data from your array then I'd go with constant array and translating external index to an internal one for this array. So it's gonna be something like a "rotated view".
Re: csvReader: how to read only selected columns while the class Layout has extra field?
On Monday, 3 October 2022 at 18:02:51 UTC, Salih Dincer wrote: On Sunday, 2 October 2022 at 19:48:52 UTC, mw wrote: ``` text.csvReader!Layout(["b","c","a"]); // Read only these column ``` The intention is very clear: only read the selected columns from the csv, and for any other fields of class Layout, just ignore (with the default D .init value). Why don't you do this? For example you can try the following? ```d import std.csv, std.math.algebraic : abs; string str = "a,b,c\nHello,65,63.63\n➊➋➂❹,123,3673.562"; struct Layout { int value; double other; string name; } You didn't get my question, please add: ``` int extra_field; // un-comment to see the error ``` to the struct, then you will see the error.
Re: rotate left an array
On Monday, 3 October 2022 at 18:09:05 UTC, Fausto wrote: Hello all, I am trying to rotate left an array. I found a very basic way, and I am not sure if there is something clever than this :) maybe using slices... Here we can't use slice assignment instead of the inner loop because that doesn't work for an overlapping slice. (Instead there's `copy` in std.algorithm). The algorithm you wrote doesn't scale the best for speed - yours is the second one mentioned here: https://www.geeksforgeeks.org/array-rotation/ Phobos has `bringToFront(arr[0..2], arr[2..$])` which does the same thing as a `rotate(arr, 2)` function. It seems to use the third algorithm from the link (or at least has the same time and space complexity). The first algorithm may also work better in some cases, when swapping is expensive or when the result is duplicated anyway.
rotate left an array
Hello all, I am trying to rotate left an array. I found a very basic way, and I am not sure if there is something clever than this :) maybe using slices... the external for represents how many times you are rotating (in this case 2). ```d void main() { import std.range; import std.stdio: write, writeln, writef, writefln; int[] arr1 = [ 1, 2, 3, 4 ]; int t = 0; writeln(arr1); for (int j = 0;j<2;j++) { t = arr1[0]; for(int i = 0;i
Re: csvReader: how to read only selected columns while the class Layout has extra field?
On Sunday, 2 October 2022 at 19:48:52 UTC, mw wrote: ``` text.csvReader!Layout(["b","c","a"]); // Read only these column ``` The intention is very clear: only read the selected columns from the csv, and for any other fields of class Layout, just ignore (with the default D .init value). Why don't you do this? For example you can try the following? ```d import std.csv, std.math.algebraic : abs; string str = "a,b,c\nHello,65,63.63\n➊➋➂❹,123,3673.562"; struct Layout { int value; double other; string name; } auto records = csvReader!Layout(str, ["b","c","a"]); Layout[2] ans; ans[0].name = "Hello"; ans[0].value = 65; ans[0].other = 63.63; ans[1].name = "➊➋➂❹"; ans[1].value = 123; ans[1].other = 3673.562; int count; foreach (record; records) { assert(ans[count].name == record.name); assert(ans[count].value == record.value); assert(abs(ans[count].other - record.other) < 0.1); count++; } assert(count == ans.length); ``` SDB@79
Re: Is `void` the correct way to say "do not initialize this variable"?
On Monday, 3 October 2022 at 14:37:35 UTC, kdevel wrote: On Sunday, 2 October 2022 at 23:37:26 UTC, ryuukk_ wrote: I got the answer thanks to IRC chat: https://dlang.org/spec/declaration.html#void_init Quote: Implementation Defined: If a void initialized variable's value is used before it is set, its value is implementation defined. Shouldn't this read Unspecified Value: If a void initialized variable's value is used before it is set, its value is unspecified. Yes, it should. Many of the contributors to the D spec are not very well versed in the precise details of these terms, so mistakes like this occasionally slip through.
Re: Way to pass params to a function passed to a fiber?
On Monday, 3 October 2022 at 10:13:09 UTC, Rene Zwanenburg wrote: On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote: My question is whether someone has an idea for a better solution. You can pass a lambda to the fiber constructor. For example: ``` void fiberFunc(int i) { writeln(i); } void main() { auto fiber = new Fiber(() => fiberFunc(5)); fiber.call(); } ``` Oh, that simple... Thanks a lot :-).
Re: Is `void` the correct way to say "do not initialize this variable"?
On Sunday, 2 October 2022 at 23:37:26 UTC, ryuukk_ wrote: I got the answer thanks to IRC chat: https://dlang.org/spec/declaration.html#void_init Quote: Implementation Defined: If a void initialized variable's value is used before it is set, its value is implementation defined. Shouldn't this read Unspecified Value: If a void initialized variable's value is used before it is set, its value is unspecified. ?
Re: csvReader: how to read only selected columns while the class Layout has extra field?
On Sunday, 2 October 2022 at 21:18:43 UTC, mw wrote: [snipping] A CSV library should consider all the use cases, and allow users to ignore certain fields. In R, you have to force `NULL` for `colClasses` for the other columns. In other words, the user has to know the number of columns of the csv file in order to be able to skip them. https://stackoverflow.com/questions/29332713/how-to-skip-column-when-reading-csv-file
Re: Way to pass params to a function passed to a fiber?
On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote: Hello, I'm looking for a way to pass parameters to a function called by a fiber. Starting a fiber works like this: You can also make a subclass of fiber that stores them with the object.
Re: Stop writeln from calling object destructor
On 10/2/22 12:21 PM, data pulverizer wrote: I've noticed that `writeln` calls the destructor of a struct multiple times and would like to know how to stop this from happening. It has become a very serious problem when working with objects that have memory management external to D. I know you already solved the problem, but just for future reference, if you use something like `RefCounted`, you can avoid copying and destruction until everyone is done with the object. This is how my io library works, the IO objects are non-copyable, and you wrap them in `RefCounted` if you want to copy them. -Steve
Re: Way to pass params to a function passed to a fiber?
On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote: In the code above there is no way to add parameters to myFunc. The construcor of class Fiber does not allow for a function to be passed that has parameters (unlike for the spawn function when starting a thread). You try std.functional... SDB@79
Re: Is `void` the correct way to say "do not initialize this variable"?
On 10/3/22 09:35, tsbockman wrote: On Sunday, 2 October 2022 at 23:45:45 UTC, drug007 wrote: It works but not as someone could expect. In case of ```D Foo[2] arr = void; ``` `arr` value is not defined, it is not an initialized array of uninitialized elements like you want, it is just uninitialized array. This is incorrect. It is not possible to declare an uninitialized static array variable in D; only the elements are affected by `= void`. The meta data of a static array like `Foo[2] arr` (`.ptr` and `.length`) is determined statically at compile time and inserted where needed into the generated code. It is not stored in mutable memory the way a dynamic array/slice's meta data is, and does not need to be initialized at run time. You are right. I used to complex structure (with indirections) for testing and made wrong statement. By contrast, it **is** possible to declare a completely uninitialized dynamic array, or to just leave its elements uninitialized: ```D // Meta data is not initialized, and no elements are allocated. // This has no static array equivalent: int[] arrA = void; // Meta data is initialized, and elements are allocated but not initialized. // This is the dynamic equivalent of the static: // int[2] arr = void; int[] arrB = uninitializedArray!(int[])(2); ```
Re: Way to pass params to a function passed to a fiber?
On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote: My question is whether someone has an idea for a better solution. You can pass a lambda to the fiber constructor. For example: ``` void fiberFunc(int i) { writeln(i); } void main() { auto fiber = new Fiber(() => fiberFunc(5)); fiber.call(); } ```
Way to pass params to a function passed to a fiber?
Hello, I'm looking for a way to pass parameters to a function called by a fiber. Starting a fiber works like this: int main() { auto fiber = new Fiber(&myFunc); fiber.call(); fiber.call(); return 0; } void myFunc() { writeln("Fiber called"); Fiber.yield(); writeln("Fiber recalled after yielding"); } In the code above there is no way to add parameters to myFunc. The construcor of class Fiber does not allow for a function to be passed that has parameters (unlike for the spawn function when starting a thread). I ended up with something like this: class Foo { public int i; } Foo foo; static this() { foo = new Foo; } int main() { auto fiber = new Fiber(&myFunc); fiber.call(); fiber.call(); return 0; } void myFunc() { import std.stdio; writeln("foo: ", foo.i); foo.i++; Fiber.yield(); writeln("foo: ", foo.i); } But this solution is a bit clumsy. It's kind of programming with global variables. My question is whether someone has an idea for a better solution. Thank you, Bienlein
Re: Visual D doesn't work, now Visual Studio Code / D doesn't work!!!! ....
On 02/10/2022 13:00, Daniel Donnell wrote: Visual D doesn't work - it just ate my app.obj file and can't find it anymore no matter if I clean or re-order the executable paths in settings. Can you be more specific what you are doing and what is going wrong? On 02/10/2022 23:28, rikki cattermole wrote: > Visual Studio with its c++ components can debug D code, it should not > require Visual D to do so. > > Open executable as project. Or start "devenv program.exe" from the command line. Indeed, you don't have to build with Visual D to use the debugger. The C++-only native debugger works, but having Visual D installed also comes with a debugger extension that makes debugging smoother, e.g. you don't have to know the respective C++ syntax for watch expressions. BTW: Using compiler options -gf instead of -g will add more debug info and can improve the debug experience.
Re: Convert array of simple structs, to C array of values
On Monday, 3 October 2022 at 07:45:47 UTC, Chris Katko wrote: I know there's gotta be some simple one liner function in D, but I can't think of it. I don't know if you're looking for type safety, but you can just do `cast(float*) values.ptr;` or `cast(float[]) values[]`.
Convert array of simple structs, to C array of values
```D struct pair { float x; float y; } pair[10] values; import std.conv; auto valuesInCStyle = to!(const float*)(values); ``` Now that's not going to work because (I would imagine) to! doesn't understand x, and y, can be placed in order to give an array of: valuesInCStyle = [values[0].x, values[0].y, values[1].x ,values[1].y, ...] I know there's gotta be some simple one liner function in D, but I can't think of it.