Re: How to make a struct containing an associative array to deeply copy (for repeated usage in foreach) ?

2024-03-15 Thread bachmeier via Digitalmars-d-learn

On Friday, 15 March 2024 at 20:36:56 UTC, rkompass wrote:

I'm quite new to D yet. But I have some acquaintance with 
Python.
Therefore, together with templates the discovery of the Variant 
type was inspiring me to the following:
I wanted to explore if it's possible to do sort of 
type-agnostic programming with D. This could perhaps enable a 
simpler translation of Python code to D.


Trying with a `Variant[Variant] dct;` dictionary I observed 
that even simple assignment of key:value pairs was not possible 
as the different types are not automatically cast to a Variant.


You're not the first one. There's no technical reason for the 
restriction. It's simply a matter of being opposed by those who 
make these decisions on the basis that it's the wrong way to 
program or something like that. Here is a recent thread: 
https://forum.dlang.org/post/ikwphfwevgnsxmdfq...@forum.dlang.org


Re: How to make a struct containing an associative array to deeply copy (for repeated usage in foreach) ?

2024-03-15 Thread rkompass via Digitalmars-d-learn

On Friday, 15 March 2024 at 17:15:56 UTC, monkyyy wrote:

On Friday, 15 March 2024 at 09:03:25 UTC, rkompass wrote:

@Monkyyy: I adopted your solution, it is perfect.

I only have one problem left:

The foreach loop with associative arrays has two cases:

`foreach(key, val; arr)` and `foreach(x; arr)`.
In the second case only the values are iterated.
With the present solution the iteration delivers (key, val) 
tuples.


That will not be fixed in d2 ranges and has no good solutions; 
and my affect over d3 seems to be none. You could ask around 
for the "opApply" solution but I dont know it well (and prefer 
ranges)


d2 Ranges are based on a simplification of stl's ideas and stl 
doesn't support arrays-like iteration well, I wish to change 
that and working on a proof of concept algorthims lib... but 
well, this is unlikely to work.


For d3 if changing the range interface fails, expect to see 
style guides say "prefer explict range starters" 
string.byUnicode and string.byAscii will probably be how they 
kill `autodecoding` and your data stucture having 2 range 
functions as `byKey` and `byKeyValue` will look the same.



Should I do an improvement request somewhere?


I think its been kinda of piecemeal and D1 1D(repetition 
intentional) opSlice is in limbo(it was deprecated, and then 
slightly undepercated in some random chats, its a mess)


for completeness I believe the current state of 1d op overloads 
are:


opIndex(int)
opIndex(key)
opSlice()
opSlice(int, int)
int opDollar()
dollar opDollar()
opSlice(int, dollar)
opBinararyRight("in",K)(key) (opIn was deprecated and shouldn't 
have been)


If your confident in your writing ability id suggest a clean 
slate article based on this list and what the compiler actually 
does(maybe ask around for any I missed) rather than trying to 
untangle this mess


Or write a dip thread "undeperacate d1 opOverloads that are 
still wanted by everyone") and try to bring back opIn at the 
same time and get the limboness of old technically deprecated 
1d array opOverloads officially gone


I'm quite new to D yet. But I have some acquaintance with Python.
Therefore, together with templates the discovery of the Variant 
type was inspiring me to the following:
I wanted to explore if it's possible to do sort of type-agnostic 
programming with D. This could perhaps enable a simpler 
translation of Python code to D.


Trying with a `Variant[Variant] dct;` dictionary I observed that 
even simple assignment of key:value pairs was not possible as the 
different types are not automatically cast to a Variant.


Embedded in a struct with templating and casts to Variant such a 
dict now seems possible:


The preliminary code:

```d
// implement .get .update .require

import std.stdio;
import std.typecons;
import std.range;
import std.variant;
import std.string;
import std.format;

struct dict
{
Variant[Variant] dct;

Variant opIndex(T)(T key) {
return dct[cast(Variant) key];
}
void opIndexAssign(V, T)(V val, T key) {
dct[cast(Variant) key] = cast(Variant) val;
}
auto opBinaryRight(string op : "in", T)(T lhs) {
return cast(Variant)lhs in dct;
}
@property auto keys() {
return dct.keys;
}
@property auto values() {
return dct.values;
}
auto remove(T)(T key) {
return dct.remove(cast(Variant) key);
}
@property auto dup() {
dict newd;
foreach (k; dct.keys)  // do a deep copy
newd.dct[k] = dct[k];
return newd;
}
	void toString(scope void delegate(const(char)[]) sink, 
FormatSpec!char fmt) {

put(sink, "dict([");
bool rep = false;
foreach (k; dct.keys) {
if (rep)
put(sink, ", ");
formatValue(sink, k, fmt);
put(sink, ":");
formatValue(sink, dct[k], fmt);
rep = true;
}
put(sink, "])");
}
auto opSlice(){
struct range{
Variant[Variant]* parent;
int i;
auto front()=> 
tuple(parent.keys[i],(*parent)[parent.keys[i]]);
auto popFront()=>i++;
auto empty()=>parent.keys.length<=i;
}
return range(&this.dct);
}
}

void main() {

dict d;

writeln("d: ", d);// ==> dict([])
writeln("d.keys: ", d.keys);
writeln("d.values: ", d.values);
writeln("d.keys.length: ", d.keys.length);
writeln("");

writeln("populating dict ");
d["hello"] = 2;
d[3.1] = 5;
d['c'] = 3.14;
d[2] = "freak";
d["mykey"] =

Re: Deriving a struct from another one via template: Easy way to propagate UDAs?

2024-03-15 Thread cc via Digitalmars-d-learn

On Thursday, 14 March 2024 at 23:19:37 UTC, Inkrementator wrote:
I am trying to derive a struct from another. I want to modify 
each field such that type of it goes from some T to Nullable!T, 
preserving all fieldnames and UDAs.


This is trivially easy if your types are visible at module level, 
and mixin is a fine tool for the job.  It doesn't work quite so 
well with [Voldemort 
types](https://wiki.dlang.org/Voldemort_types).


```d
struct MyUDA { int q; }
struct Foo { int f; }
struct MyStruct {
@MyUDA(3) int x;
@MyUDA(4) Foo f;
@MyUDA(5) @MyUDA(7) string s;
}
auto generateUDAs(A...)() {
string[] udaStrs;
static foreach (uda; A)
udaStrs ~= "@(" ~ uda.stringof ~ ")";
return udaStrs;
}
struct Wrapped(S) {
static foreach (idx, field; S.tupleof) {
//pragma(msg, format(... can be used to preview
		mixin(format("%s %s %s;", generateUDAs!(__traits(getAttributes, 
field)).join(' '), Nullable!(typeof(field)).stringof, 
field.stringof));

}
}
void main() {
MyStruct s;
s.x = 3;
s.f = Foo(1);
s.s = null;
Wrapped!MyStruct w;
w.x = s.x;
w.f = s.f;
w.s = s.s;
w.x.nullify;
w.f.nullify;
w.s.nullify; // strings/objects are already nullable though
	static assert(__traits(getAttributes, w.s) == 
AliasSeq!(MyUDA(5), MyUDA(7)));

}
```

If you absolutely must though, you could do something like
```d
enum WrapMixin = q{
struct Wrapped(S) {
static foreach (field; S.tupleof)
			mixin(format("%s %s %s;", 
generateUDAs!(__traits(getAttributes, field)).join(' '), 
Nullable!(typeof(field)).stringof, field.stringof));

}
};
void main() {
struct MyUDA { .
struct MyStruct { .
mixin(WrapMixin);
Wrapped!MyStruct w;
}
```


Re: dub: Could not resolve configuration for package demo

2024-03-15 Thread mw via Digitalmars-d-learn

On Friday, 15 March 2024 at 18:04:25 UTC, Inkrementator wrote:
You'll have to either fix the old vibe-d version, or fork 
msgpack-rpc to work with current vibe-d, whatever is more 
appropriate and easier.


I'm trying to fix it with the latest vibe-d 0.10.0, now the new 
error:


```
../../src/msgpackrpc/transport/tcp.d(13,8): Error: unable to read 
module `driver`
../../src/msgpackrpc/transport/tcp.d(13,8):Expected 
'vibe/core/driver.d' or 'vibe/core/driver/package.d' in one of 
the following import paths:


```

that line is:

```
import vibe.core.driver;
```

Do you know where is `vibe.core.driver` in the new version?


Re: dub: Could not resolve configuration for package demo

2024-03-15 Thread mw via Digitalmars-d-learn

On Friday, 15 March 2024 at 18:04:25 UTC, Inkrementator wrote:

On Friday, 15 March 2024 at 17:48:26 UTC, mw wrote:

```
$ dub build
Could not resolve configuration for package demo
```


Trying to build your dependency msgpack-rpc, it spits out
```
 Warning The sub configuration directive "vibe-d" -> 
[libevent] references a configuration that does not exist.

Error Could not resolve configuration for package msgpack-rpc
```


Thanks for the reply.

But where you see this warning message? I didn't see it even with 
`$ dub build -v`.




Re: dub: Could not resolve configuration for package demo

2024-03-15 Thread mw via Digitalmars-d-learn

OK, looks something wrong with dub / or vibe-d 0.10.0

https://github.com/msgpack-rpc/msgpack-rpc-d/blob/master/examples/with_http_server/dub.sdl#L5

with
```
dependency "vibe-d" version="~>0.7.25"
```

`dub build` can at least starts.

But

```
dependency "vibe-d" version="~>0.10.0"
```


```
$ dub build
Error Could not resolve configuration for package with_http_server

```



Re: dub: Could not resolve configuration for package demo

2024-03-15 Thread Inkrementator via Digitalmars-d-learn

On Friday, 15 March 2024 at 17:48:26 UTC, mw wrote:

```
$ dub build
Could not resolve configuration for package demo
```


Trying to build your dependency msgpack-rpc, it spits out
```
 Warning The sub configuration directive "vibe-d" -> 
[libevent] references a configuration that does not exist.

Error Could not resolve configuration for package msgpack-rpc
```
In version 0.7, vibe-d depended on libevent, this got removed in 
the meantime

https://github.com/vibe-d/vibe.d/commit/196096407ec27b2c107f0038c6751ce07e7a9507

Just patching msgpack-rpc dub.json to use the exact vibe-d 
version, and not a minimum, like this

```json
"dependencies": {
"msgpack-d": ">=0.9.2",
"vibe-d": "==0.7.25"
},
```
fails too, because this old vibe-d version doesn't compile 
anymore.


You'll have to either fix the old vibe-d version, or fork 
msgpack-rpc to work with current vibe-d, whatever is more 
appropriate and easier.


dub: Could not resolve configuration for package demo

2024-03-15 Thread mw via Digitalmars-d-learn

Very simple thing from https://dub.pm/getting-started/first-steps/

After I add dependencies, it cannot build:

```
$ cat dub.json
{
"authors": [
"mw"
],
"copyright": "Copyright © 2024, mw",
"description": "msgpack-rpc-d demo.",
"license": "MIT",
"name": "demo",
"dependencies": {
"msgpack-rpc": "~>0.1.3"
},
"subConfigurations": {
"msgpack-rpc": "default"
}
}

$ dub build
Could not resolve configuration for package demo
```

So what I'm missing?

Thanks.


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-15 Thread Daniel N via Digitalmars-d-learn

On Tuesday, 12 March 2024 at 05:38:03 UTC, Liam McGillivray wrote:
I am in need of a data type for holding direction information; 
one of 8 directions on a single axis. They are named in terms 
of compass directions. If D had a 4-bit datatype, I would just 
use this and do `+=2` whenever I want to change the datatype, 
but it doesn't.


Perhaps this would be a good programming challenge for someone 
more experienced than me. Make a data type (probably a struct) 
for holding one of 8 directional values using 3 bits. It should 
accept the use of increment operators to change the angle.


Ideally (but optionally), it should work as an enum of the same 
name; "Direction".


Here's a unittest that it should ideally pass:


D actually supports both 3 and 4 bit integers. People will likely 
warn you of minor portability risks... but if you target a 
limited amount of platforms and prefer concise readable code, 
then it's a text book example for bitfields. The risk can easily 
be mitigated by having an unittest to catch the error directly(if 
you try to port to some exotic platform).


dmd -preview=bitfields

(Some lines stolen from Rikki)

```d
struct Direction
{
private uint value : 3;
alias this = value;

enum Direction N  = Direction(0);
enum Direction NE = Direction(1);
enum Direction E  = Direction(2);
enum Direction SE = Direction(3);
enum Direction S  = Direction(4);
enum Direction SW = Direction(5);
enum Direction W  = Direction(6);
enum Direction NW = Direction(7);
}
```


Re: How to make a struct containing an associative array to deeply copy (for repeated usage in foreach) ?

2024-03-15 Thread monkyyy via Digitalmars-d-learn

On Friday, 15 March 2024 at 09:03:25 UTC, rkompass wrote:

@Monkyyy: I adopted your solution, it is perfect.

I only have one problem left:

The foreach loop with associative arrays has two cases:

`foreach(key, val; arr)` and `foreach(x; arr)`.
In the second case only the values are iterated.
With the present solution the iteration delivers (key, val) 
tuples.


That will not be fixed in d2 ranges and has no good solutions; 
and my affect over d3 seems to be none. You could ask around for 
the "opApply" solution but I dont know it well (and prefer ranges)


d2 Ranges are based on a simplification of stl's ideas and stl 
doesn't support arrays-like iteration well, I wish to change that 
and working on a proof of concept algorthims lib... but well, 
this is unlikely to work.


For d3 if changing the range interface fails, expect to see style 
guides say "prefer explict range starters" string.byUnicode and 
string.byAscii will probably be how they kill `autodecoding` and 
your data stucture having 2 range functions as `byKey` and 
`byKeyValue` will look the same.



Should I do an improvement request somewhere?


I think its been kinda of piecemeal and D1 1D(repetition 
intentional) opSlice is in limbo(it was deprecated, and then 
slightly undepercated in some random chats, its a mess)


for completeness I believe the current state of 1d op overloads 
are:


opIndex(int)
opIndex(key)
opSlice()
opSlice(int, int)
int opDollar()
dollar opDollar()
opSlice(int, dollar)
opBinararyRight("in",K)(key) (opIn was deprecated and shouldn't 
have been)


If your confident in your writing ability id suggest a clean 
slate article based on this list and what the compiler actually 
does(maybe ask around for any I missed) rather than trying to 
untangle this mess


Or write a dip thread "undeperacate d1 opOverloads that are still 
wanted by everyone") and try to bring back opIn at the same time 
and get the limboness of old technically deprecated 1d array 
opOverloads officially gone


Re: How to make a struct containing an associative array to deeply copy (for repeated usage in foreach) ?

2024-03-15 Thread rkompass via Digitalmars-d-learn

@Monkyyy: I adopted your solution, it is perfect.

I only have one problem left:

The foreach loop with associative arrays has two cases:

`foreach(key, val; arr)` and `foreach(x; arr)`.
In the second case only the values are iterated.
With the present solution the iteration delivers (key, val) 
tuples.


Can this somehow be detected by the opSlice or is there another 
overloading

construct to be applied for this?


Addition: I noted that in the best matching 
[docs](https://dlang.org/spec/operatoroverloading.html#slice) 
only *ordinary arrays* are covered. Your solution would make a 
very nice addition for the case of associative arrays there. I 
learn't a lot from it.

Should I do an improvement request somewhere?