Re: (Noob question) Should subclasses be defined in separate modules?
On Friday, 13 January 2023 at 05:17:59 UTC, thebluepandabear wrote: (Sorry if this is a duplicate.) If I have the following code inside of a module: ```D class Obj { private { string name = "Hi"; } } class ObjDerived : Obj { } ``` Is it best practice to define `ObjDerived` inside another module, since `ObjDerived` can still access the members of `Obj` (since `private` is only applied to modules), or does this go against the intended use of the language? As a beginner, I am having an extremely tough time understanding why you would want to place these two classes in the same module or even have this intended behavior of `private`. I am coming from Java/Kotlin which are both strictly OO language and have different ways of encapsulation. The short answer: just think of a module as a way of grouping related objects and functions. If it makes sense to you for `ObjDerived` to have access to the internals of `Obj`, then keep them in the same module. If it doesn't, then put it somewhere else. The long answer: there's no one-size-fits all here. For a short program, a script let's say, just dump everything in one module and be done with it. For a program you're writing for your own use, do whatever you feel comfortable with, even if you plan to open source it. For something you're writing for others to use, like a library, then the first priority is to think about what the public facing API should look like. From that perspective, does `ObDerived` belong in the same module, or is it unrelated enough to go into a different one? If it does fit in the same module, then that can be enough. It is for me. I'd stop there. But some people want to go one step further and ensure that `ObjDerived` can't access the internals of `Obj`. So in that case, you can put them in two separate modules and make a `package.d` file to act as the common module name for both. I think there are good reasons to do that, but most of the time it's just a matter of preference.
(Noob question) Should subclasses be defined in separate modules?
(Sorry if this is a duplicate.) If I have the following code inside of a module: ```D class Obj { private { string name = "Hi"; } } class ObjDerived : Obj { } ``` Is it best practice to define `ObjDerived` inside another module, since `ObjDerived` can still access the members of `Obj` (since `private` is only applied to modules), or does this go against the intended use of the language? As a beginner, I am having an extremely tough time understanding why you would want to place these two classes in the same module or even have this intended behavior of `private`. I am coming from Java/Kotlin which are both strictly OO language and have different ways of encapsulation.
Re: Coding Challenges - Dlang or Generic
On Thursday, 12 January 2023 at 20:28:26 UTC, Christian Köstlin wrote: For this years advent-of-code Steven Schveighoffer (https://github.com /schveiguy/adventofcode/tree/master/2022) has a complete set of dlang solutions. Kind regards, Christian Very helpful. Thanks Christian.
Re: Coding Challenges - Dlang or Generic
On 10.01.23 23:30, Paul wrote: On Tuesday, 10 January 2023 at 01:31:28 UTC, Ali Çehreli wrote: On 1/9/23 16:17, Paul wrote: > coding challenges Perhaps the following two? https://rosettacode.org/ https://adventofcode.com/ Ali Excellent. Thanks. For this years advent-of-code Steven Schveighoffer (https://github.com /schveiguy/adventofcode/tree/master/2022) has a complete set of dlang solutions. Kind regards, Christian
Re: Coding Challenges - Dlang or Generic
On 10.01.23 23:22, monkyyy wrote: On Tuesday, 10 January 2023 at 19:10:09 UTC, Christian Köstlin wrote: On 10.01.23 01:17, Paul wrote: There is also https://exercism.org/tracks/d with some tasks for dlang. Kind regards, Christian Its all converted code; worthless I was not aware, that the question was searching for solutions in dlang. At least exorcism gives a skeleton for a dlang project (including unittest) to solve the task. Kind regards, Christian
Re: Coding Challenges - Dlang or Generic
On Tuesday, 10 January 2023 at 01:22:33 UTC, H. S. Teoh wrote: Here's a challenge. Given an input year, for example, "2023", write a program that outputs (for the corresponding year): Now, I wrote a nested class using range and copying from Matheus' code. Of course not as comprehensive as [your dcal](https://github.com/quickfur/dcal/blob/master/dcal.d). I like this one and even thought of a new challenge! ```d void main() { import std.stdio, std.string : cp = capitalize; import std.range, std.conv : to; with(new MyCalendar(2023, 12)) { const title = dowToStr!2; foreach(month; range.take(6)) { const mName = date.month.to!string; year.write(" "); // current year mName.cp.writefln!"%s:"; // name of the month title.writefln!"%-(%s %)"; // days of week month.writeln; // formatted days } } class MyCalendar { import std.array, std.datetime, std.conv : to; import std.string : capitalize; Range range; Date date; int year, month; this(int year, int month) { this.month = month; this.year = year; this.date = Date(year, month, 1); this.range = new Range(); } class Range { enum empty = false; string front() { import std.format : fw = formattedWrite; auto res = appender!string; int day, dow = date.dayOfWeek; res.fw("%s", replicated(dow * 3)); // skip days for(day = 1; day <= date.daysInMonth; ++day) { if(++dow % 7) res.fw("%2s ", day); else res.fw("%2s\n", day); } if(dow % 7) res.put("\n"); return res.data; } void popFront() { month++; if(month > 12) { ++year; month = 1; } date = Date(year, month, 1); } } auto dowToStr(size_t len = 0)() { alias E = DayOfWeek; string[] result; for(E x = E.min; x <= E.max; x++) { result ~= len ? x.to!string[0..len] : x.to!string; } return result; } } ``` SDB@79
Re: Nested sibling classes
On 1/12/23 12:05 PM, seany wrote: How can I make it, that classes b and c can access each other, and create instances of each other freely? Thank you. So to just point out something that wasn't discussed by Salih: When you declare a field of a class with an initializer, *that initializer is run at compile-time*. Which means, that even if it did work, every instance of every b would start out with the same exact `C` object (not a copy, the same one). This is different than many other languages which treat initializers as part of the constructor (and run when you initialize a class). In D, the bits are simply copied into the new memory as the default state. For this reason you should almost *never* initialize a class reference in a non-static field. Consider that if you ever modified that instance named `C`, all new instances of `b` would have a reference to that modified instance! The reason the compiler doesn't like it is because it doesn't know how to initialize a `c` at compile time, since it needs the context pointer to the outer class. Just moving initialization into the constructor should fix the problem, you don't need to make them static. Now, maybe you didn't intend to have a nested class with a reference to the outer class, and in that case, you should make it static. -Steve
Re: Nested sibling classes
On Thursday, 12 January 2023 at 17:46:45 UTC, seany wrote: Please, can you explain what role "static" plays here? Thank you again Of course, there are actually 2 paragraphs of information and examples [here]( https://dlang.org/spec/class.html#nested-context): Non-static nested classes work by containing an extra hidden member (called the context pointer) that is the frame pointer of the enclosing function if it is nested inside a function, or the this reference of the enclosing class's instance if it is nested inside a class. When a non-static nested class is instantiated, the context pointer is assigned before the class's constructor is called, therefore the constructor has full access to the enclosing variables. A non-static nested class can only be instantiated when the necessary context pointer information is available. SDB@79
Re: Nested sibling classes
On Thursday, 12 January 2023 at 17:41:39 UTC, Salih Dincer wrote: On Thursday, 12 January 2023 at 17:05:04 UTC, seany wrote: How can I make it, that classes b and c can access each other, and create instances of each other freely? Thank you. Ignoring the typos you could try auto and static: ```d class a { //outer static class b { // inner 1 c C; this() { this.C = new c; //writeln(this.C.i); } } static class c { // inner 2 int i = 10; } } int main () { int[21][1] test; test[0][20] = 19; assert(test[0][20] == 19); auto B = new a.b; auto C = new a.c; assert(B.C.i == 10); assert(C.i == 10); return 0; } ``` SDB@79 Hi Moving the "new c" within the this() function indeed solved it. Thank you for pointing out the typos. Please, can you explain what role "static" plays here? Thank you again
Re: Nested sibling classes
On Thursday, 12 January 2023 at 17:05:04 UTC, seany wrote: How can I make it, that classes b and c can access each other, and create instances of each other freely? Thank you. Ignoring the typos you could try auto and static: ```d class a { //outer static class b { // inner 1 c C; this() { this.C = new c; //writeln(this.C.i); } } static class c { // inner 2 int i = 10; } } int main () { int[21][1] test; test[0][20] = 19; assert(test[0][20] == 19); auto B = new a.b; auto C = new a.c; assert(B.C.i == 10); assert(C.i == 10); return 0; } ``` SDB@79
Nested sibling classes
Please Consider the code: import std.stdio; class a { public: this(){} ~this(){} class b { public: this.outer.c C = new this.outer.c(); this() { writeln(this.C.i); } ~this() {} } class c { public: this() {} ~this() {} int i = 10; } } int main () { int [int][int] test; test[0][20] = 19; writeln(Test[0][20]); a A = new A(); a.b B = a.new a.b(); return 0; } Compiling with dmd tells me: `test.d(12): Error: undefined identifier `` this.outer.c `` ` (i used two backticks, but i can't seem tobe escaping the backtick character correctly in this forum) On fish shell we have: ❯ dmd --version DMD64 D Compiler v2.101.2 Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved written by Walter Bright If i remove the "this.outer" and just write, c C = new c(); then i have: `test.d(12): Error: cannot construct nested class ` c ` because no implicit ` this ` reference to outer class ` a ` is available` How can I make it, that classes b and c can access each other, and create instances of each other freely? Thank you.
Re: Mixin helper help
On Thursday, 12 January 2023 at 08:03:34 UTC, John Chapman wrote: I'm obviously doing something wrong, but don't quite understand. ```d mixin template helper() { mixin("writeln(12);"); } struct Foo { void opDispatch(string name)() { import std.stdio; mixin helper!(); //mixin("writeln(12);"); } } void main() { Foo.init.opDispatch!"bar"(); } ``` The compiler emits these errors about the mixin ("writeln(12);"): unexpected `(` in declarator basic type expected, not `12` found `12` when expecting `)` no identifier for declarator `writeln(_error_)` semicolon expected following function declaration declaration expected, not `)` Why does the commented code work but the mixin not? Thanks for any pointers. `mixin template` cannot be used like that. The only statement it accepts are declaration statements: Look at https://dlang.org/spec/module.html#MixinDeclaration It says it must compile to a valid DeclDef, which means you can't put code like that. Mixin templates are used only for declaring new variables, types and functions, it can't simply put call statements like that. You could do this by simply calling a function such as: ```d void helper() { writeln(12); } ``` I think you'll need to comment more on your problem if you wish specialized help
Re: Vibe.d serve files from filesystem
On Wednesday, 11 January 2023 at 18:56:47 UTC, eXodiquas wrote: Hello everyone, I build a web tool that allows people to upload some files. Those files should not be public, so I copy them into a folder hidden away on the filesystem. But, I want an authenticated user to be able to look at them. Those files are PDFs and mp3/4s. So my idea was to use an `iframe` with a `src="path/to/file"` but this is not working, because vibed wants to map it to a route but there is and there should be none. Is there a way to use iframes in this way, or do I need to approach this problem differently? Thanks in advance. eXo You will probably need to write a custom route handler that handles some authentication and returns files in response to a user. Since vibe.d routes handled in order you will need to add such route before generic '*' route. Take a look at this example https://vibed.org/docs#http-routing You can probably just write a handler like addUser for router.get('*', serveMyFiles) and write your own file handling logic. ```d // PSEUDOCODE // use this handler in router.get('*', serveMyFiles) void serveMyFiles(HTTPServerRequest req, HTTPServerResponse res) { enforceHTTP("file" in req.form, HTTPStatus.badRequest, "No file specified."); // don't just use raw input from the user, users can access your whole filesystem with some hackery!! res.writeBody(readfile("/users/"~req.form["file"])); } ```
Mixin helper help
I'm obviously doing something wrong, but don't quite understand. ```d mixin template helper() { mixin("writeln(12);"); } struct Foo { void opDispatch(string name)() { import std.stdio; mixin helper!(); //mixin("writeln(12);"); } } void main() { Foo.init.opDispatch!"bar"(); } ``` The compiler emits these errors about the mixin ("writeln(12);"): unexpected `(` in declarator basic type expected, not `12` found `12` when expecting `)` no identifier for declarator `writeln(_error_)` semicolon expected following function declaration declaration expected, not `)` Why does the commented code work but the mixin not? Thanks for any pointers.