Re: dlang.org/spec/function.html#pure-functions example

2023-10-16 Thread Paul via Digitalmars-d-learn
On Thursday, 12 October 2023 at 21:20:44 UTC, Jonathan M Davis 
wrote:

look like?

Types can have static members.

Basically what it comes down to is that outside of immutable 
data, pure functions only have access to their arguments and to 
what they can access via their arguments (be it by getting 
pointers from those arguments or calling other pure functions 
on them).


- Jonathan M Davis


Can I say in the general sense that when the word static is used 
it means that something is defined/declared at compile time?




Re: dlang.org/spec/function.html#pure-functions example

2023-10-16 Thread Paul via Digitalmars-d-learn
On Thursday, 12 October 2023 at 21:20:44 UTC, Jonathan M Davis 
wrote:


Thanks Jonathan




Re: extern (c)

2023-10-11 Thread Paul via Digitalmars-d-learn

On Wednesday, 11 October 2023 at 12:54:53 UTC, user1234 wrote:


`extern(C)` on module level functions affect the mangling and 
the calling convention.


- Mangling is used by the linker to link symbols between 
objects.
- Calling convention affects the compiler backend in how code 
is generated for a CALL instruction.


So C doesn't use name mangling and extern (C) in a D prog would 
turn off D mangling thereby allowing C and D object files to be 
linked together?


I didn't know C and D had different calling conventions...i.e. 
different ABI's?





extern (c)

2023-10-11 Thread Paul via Digitalmars-d-learn

What does the extern (c) attribute(?) do?
Does it tell the compiler/linker to build the function like a C 
compiler would build a C function? If so what does that mean?
Does it tell the compiler/linker to let C functions know it 
exists? If so what does that mean?

Is it meant for the compiler or linker or both?

Thanks for any assistance.


Re: "macro" expansion to build switch case code

2023-07-03 Thread Paul via Digitalmars-d-learn
On Sunday, 2 July 2023 at 20:27:47 UTC, Steven Schveighoffer 
wrote:

On 7/2/23 1:02 PM, Paul wrote:

[...]


Use a static foreach:

```d
import std.traits; // for FieldNameTuple. there are other ways, 
but this is the most straightforward

switchlabel: // this is needed for break inside a static foreach
final switch(s) {
   static foreach(mem; FieldNameTuple!myS) {
 case mem ~ mem:
__traits(getMember, this, mem) += n;
break switchalbel;
   }
}
```

-Steve


Perfect.  Thanks Steve!


"macro" expansion to build switch case code

2023-07-02 Thread Paul via Digitalmars-d-learn
I have a struct similar to the following example.  I'd like to 
build an adder method without having to code the whole method.  
How do I use the D language to do this?  Template, mixins, 
CTFE..all of them?


```d
struct myS {
int a, b, c, d, e, f, g, h, i;
adder(string s, int n) {
final switch (s) {
case "aa" :
a += n; break;
case "bb" :
b += n; break;
   ...
```
Thanks for any assistance.


Re: key membership in multi-dimensional assoc. array

2023-06-14 Thread Paul via Digitalmars-d-learn
On Thursday, 15 June 2023 at 02:21:16 UTC, Steven Schveighoffer 
wrote:


Not in as short code. You could write a helper though:

```d
auto deepIn(V, K, Keys...)(V[K] aa, Keys keys) if (Keys.length
> 0)
{
   auto v = keys[0] in aa;
   static if(keys.length == 1)
 return v;
   else
 return v ? deepIn(*v, keys[1 .. $]) : null;
}

if(auto v = cubelist.deepIn(xKey, yKey, zKey)) { // v now 
points at the value

}
```

-Steve

Thanks Steve.



key membership in multi-dimensional assoc. array

2023-06-14 Thread Paul via Digitalmars-d-learn

I found I can check for key membership in a multi-D aa...
```d
byte zKey = someval;
byte[byte][byte][byte] cubelist;

foreach(byte xK, yzcubelist; cubelist) {
  foreach(byte yK, zcubelist; yzcubelist) {
foreach(byte zK, val; zcubelist) {
```
with this expression...
```d
if(zKey in cubelist[xK][yK])
```
Is there a way to check for membership in the x & y dimensions?
```d
if(yKey in cubelist[xK] ??? [zK])
```
*Thanks in advance for any ideas or solutions.*


Re: Union with bits ?

2023-06-14 Thread Paul via Digitalmars-d-learn

On Wednesday, 14 June 2023 at 22:44:41 UTC, Ali Çehreli wrote:
By the way, the string that bitfields() generates can be 
visualized by simply printing it:


const code =
bitfields!(
ubyte, "A", 1,
ubyte, "B", 1,
ubyte, "C", 1,
ubyte, "padding", 5,);
writeln(code);

The output is not pretty for the human eye but those are 
basically the getters and setters that Adam D Ruppe mentioned.


Ali


Excellent help.  Thanks Adam and Ali.


Re: Union with bits ?

2023-06-14 Thread Paul via Digitalmars-d-learn

On Wednesday, 14 June 2023 at 14:43:58 UTC, Ali Çehreli wrote:
D's string mixin syntax may not be the best, the implementation 
may be slower than necessary, and the concept may be strange 
(not macros but very similar) but I still find phobos's 
bifields to be brilliant.


  https://dlang.org/phobos/std_bitmanip.html#bitfields

import std.bitmanip;

struct MyStruct {
union {
ubyte status;
mixin(bitfields!(
  ubyte, "A", 1,
  ubyte, "B", 1,
  ubyte, "C", 1,
  ubyte, "padding", 5,));
}
}

void main() {
auto m = MyStruct();
m.B = 1;
assert(m.status == 2);
}

Ali


Thanks Ali!  I believe this is what I'm looking for.  I searched 
our website and library but somehow missed this.


Question: Why do you say "may be slower than necessary"?  Do you 
mean compile or runtime or both?


Union with bits ?

2023-06-13 Thread Paul via Digitalmars-d-learn
I would like to have labeled bits in a union with a ubyte.  
Something like this:

```d
struct MyStruct {
union {
ubyte status;
bit A, B, C…etc
}
}
```
Is something like this possible?

Thanks



Re: regex matching but not capturing

2023-04-06 Thread Paul via Digitalmars-d-learn

On Thursday, 6 April 2023 at 16:27:23 UTC, Alex Bryan wrote:

My understanding browsing the documentation is the matchAll 
returns a range of Captures (struct documented at 
https://dlang.org/phobos/std_regex.html#Captures). In your for 
loop I think c[0] will contain the current full match (current 
line that matches), c[1] will contain the first captured match 
("AA" for first line), c.front[2] will contain "0" for first 
line, etc.




Thanks Alex.  Read some more and tried some different ways to 
access those repetitive ", cc" s on the end.  I don't think my 
regex is capturing them.





regex matching but not capturing

2023-04-06 Thread Paul via Digitalmars-d-learn
My regex is matching but doesnt seem to be capturing.  You may 
recognize this from the AOC challenges.


file contains...
**Valve AA has flow rate=0; tunnels lead to valves DD, II, BB**
**Valve BB has flow rate=13; tunnels lead to valves CC, AA**
**Valve CC has flow rate=2; tunnels lead to valves DD, BB**
**... etc**

```d
auto s = readText(filename);
auto ctr = ctRegex!(`Valve ([A-Z]{2}).*=(\d+).+valves(,* 
[A-Z]{2})+`);

foreach(c;matchAll(s, ctr)) {
fo.writeln(c);
}
```

produces...
**["Valve AA has flow rate=0; tunnels lead to valves DD, II, BB", 
"AA", "0", ", BB"]**
**["Valve BB has flow rate=13; tunnels lead to valves CC, AA", 
"BB", "13", ", AA"]**
**["Valve CC has flow rate=2; tunnels lead to valves DD, BB", 
"CC", "2", ", BB"]**


what I'm attempting to achieve and expect is, for instance, on 
the 1st line...
[lead to valves DD, II, BB", "AA", "0", **", DD", ", II", ", 
BB"]**


Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-06 Thread Paul via Digitalmars-d-learn

On Thursday, 6 April 2023 at 01:44:15 UTC, H. S. Teoh wrote:



D ranges are conceptually sequential, but the actual underlying 
memory access patterns depends on the concrete type at runtime. 
An array's elements are stored sequentially in memory, and 
arrays are ranges.  But a linked-list can also have a range 
interface, yet its elements may be stored in non-consecutive 
memory locations.  So the concrete type matters here; the range 
API only gives you conceptual sequentiality, it does not 
guarantee physically sequential memory access.


Very helpful Teoh.  Thanks again.


Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-05 Thread Paul via Digitalmars-d-learn

On Wednesday, 5 April 2023 at 23:06:54 UTC, H. S. Teoh wrote:

So your data structures and algorithms should be designed in a 
way that takes advantage of linear access where possible.



T


Yes I understand, basically, what's going on in hardware.  I just 
wasn't sure if the access type was linked to the container type.  
It seems obvious now, since you've both made it clear, that it 
also depends on how I'm accessing my container.


Having said all of this, isn't a D 'range' fundamentally a 
sequential access container (i.e popFront) ?


Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-05 Thread Paul via Digitalmars-d-learn

On Tuesday, 4 April 2023 at 22:20:52 UTC, H. S. Teoh wrote:


Best practices for arrays in hot loops:
- Avoid appending if possible; instead, pre-allocate outside 
the loop.
- Where possible, reuse existing arrays instead of discarding 
old ones

  and allocating new ones.
- Use slices where possible instead of making copies of 
subarrays (this

  esp. applies to strings).
- Where possible, prefer sequential access over random access 
(take

  advantage of the CPU cache hierarchy).


Thanks for sharing Teoh!  Very helpful.

would this be random access? for(size_t i; iusing indices?

...and this be sequential foreach(a;arr) ?

or would they have to be completely different kinds of containers?
a dlang 'range' vs arr[]?




Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-04 Thread Paul via Digitalmars-d-learn
On Monday, 3 April 2023 at 23:50:48 UTC, Steven Schveighoffer 
wrote:


So what you need is inside `createSpansOfNoBeacons`, take as a 
reference a `ref Span[MAX_SPANS]`, and have it return a 
`Span[]` that is a slice of that which was "alocated".


See if this helps.


Well Steven just making the change you said reduced the execution 
time from ~6-7 secs to ~3 secs.  Then, including the 'parallel' 
in the foreach statement took it down to ~1 sec.


Boy lesson learned in appending-to and zeroing dynamic arrays in 
a hot loop!




Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-03 Thread Paul via Digitalmars-d-learn
On Monday, 3 April 2023 at 23:13:58 UTC, Steven Schveighoffer 
wrote:


Yeah, please post.

```d
module aoc2215b2;

import std.stdio;
import std.file: readText;
import std.conv: to;
import std.math: abs;
import std.traits;
import std.parallelism;
import std.range;
import core.time: MonoTime;

// Timed main() 
vvv

void main(string[] args) {
auto progStartTime = MonoTime.currTime;
//-
string filename = args.length > 1 ? args[1] : "aoc2215a.data";
CommPair[] commPair;
ulong x,y;

	// read file that has data sets in the form of x,y coordinate 
pairs
	// for each sensor-beacon pair.  Create on array of structs to 
hold

// this information.
loadFileDataIntoArrayOfStructs(commPair, filename);

foreach(int lineOfInterest;parallel(iota(0,4_000_001))) {
		Span[] span; // A section of line-of-interest coordinates where 
no other beacons are present.

const spanReserve = span.reserve(50);
createSpansOfNoBeacons(lineOfInterest,commPair,span);

// if spans overlap, combine them into a single span and mark
// the other spans !inUse.
combineOverlappingSpans(span);

		// look for a line that doesn't have 4,000,001 locations 
accounted for

if(beaconFreeLocations(span) < 4_000_001) {

// find the location that is not accounted for
foreach(ulong i;0..4_000_000) {
bool found = false;
foreach(sp;span) {
if(i >= sp.xLow && i <= sp.xHigh) {
found = true;
break;
}
}
if(!found) {
x = i; y = lineOfInterest;
break;
}
}
}
}
writeln(x," ",y);

//-
auto progEndTime = MonoTime.currTime;
writeln(progEndTime - progStartTime);
}
// Timed main() 
^^^




struct CommPair {
int sx,sy,bx,by;
int manhattanDistance;
}

void loadFileDataIntoArrayOfStructs(ref CommPair[] commPair, 
string filename) {

import std.regex;
auto s = readText(filename);
	auto ctr = ctRegex!(`x=(-*\d+), y=(-*\d+):.*x=(-*\d+), 
y=(-*\d+)`);

CommPair cptemp;
foreach (c; matchAll(s, ctr)) {
cptemp.sx = to!int(c[1]);
cptemp.sy = to!int(c[2]);
cptemp.bx = to!int(c[3]);
cptemp.by = to!int(c[4]);
		cptemp.manhattanDistance = abs(cptemp.sx-cptemp.bx) + 
abs(cptemp.sy-cptemp.by);

commPair ~= cptemp;
}
}

struct Span {
int xLow, xHigh;
bool inUse = true;
}

void createSpansOfNoBeacons(int lineOfInterest, CommPair[] 
commPair,ref Span[] span) {

foreach(size_t i,cp;commPair) {
int distanceToLineOfInterest = abs(cp.sy - lineOfInterest);
if(cp.manhattanDistance >= distanceToLineOfInterest) {
			int xLow  = cp.sx - (cp.manhattanDistance - 
distanceToLineOfInterest);
			int xHigh = cp.sx + (cp.manhattanDistance - 
distanceToLineOfInterest);

span ~= Span(xLow,xHigh);
}
}
}

void combineOverlappingSpans(ref Span[] span) {
bool combinedSpansThisCycle = true;
while(combinedSpansThisCycle) {
combinedSpansThisCycle = false;
for(size_t i=0; i < span.length-1; i++) {
if(!span[i].inUse) continue;

for(size_t j=i+1; j < span.length; j++) {
if(!span[j].inUse) continue;

// if one span overlaps with the other, combine them into one 
span
if(spanIContainedInSpanJ(span[i],span[j]) || 
spanJContainedInSpanI(span[i],span[j])) {
	span[i].xLow  = span[i].xLow  < span[j].xLow  ? span[i].xLow 
 : span[j].xLow;
	span[i].xHigh = span[i].xHigh > span[j].xHigh ? 
span[i].xHigh : span[j].xHigh;

span[j].inUse = false;
combinedSpansThisCycle = true;

// after combining two spans, perform 
bounds checking
// 15 part b limits the search between 
0 and 4,000,000
	span[i].xLow  = span[i].xLow  < 0 ? 0 : 
span[i].xLow;
	span[i].xHigh = span[i].xHigh > 4_000_000 ? 4_000_000 : 
span[i].xHigh;

 

Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-03 Thread Paul via Digitalmars-d-learn
On Monday, 3 April 2023 at 22:24:18 UTC, Steven Schveighoffer 
wrote:




If your `foreach` body takes a global lock (like 
`writeln(i);`), then it's not going to run any faster 
(probably slower actually).

**Ok I did have some debug writelns I commented out.**


And did it help?

**No**

My program is about 140 lines Steven.  Its just one of the Advent 
of Code challenges.  Could I past the whole program here and see 
what you think?


Thanks for your assistance...much appreciated.





Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-03 Thread Paul via Digitalmars-d-learn
On Sunday, 2 April 2023 at 15:32:05 UTC, Steven Schveighoffer 
wrote:




It's important to note that parallel doesn't iterate the range 
in parallel, it just runs the body in parallel limited by your 
CPU count.

**?!?**

If your `foreach` body takes a global lock (like 
`writeln(i);`), then it's not going to run any faster (probably 
slower actually).

**Ok I did have some debug writelns I commented out.**

If you can disclose more about what you are trying to do, it 
would be helpful.
**This seems like it would be a lot of code and explaining but 
let me think about how to summarize.**



Also make sure you have more than one logical CPU.

**I have 8.**




Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-01 Thread Paul via Digitalmars-d-learn
On Saturday, 1 April 2023 at 18:30:32 UTC, Steven Schveighoffer 
wrote:

On 4/1/23 2:25 PM, Paul wrote:

```d
import std.range;

foreach(; iota(0, 2_000_000).parallel)
```

-Steve


Is there a way to tell if the parallelism actually divided up the 
work?  Both versions of my program run in the same time ~6 secs.


Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-01 Thread Paul via Digitalmars-d-learn

```d
import std.range;

foreach(; iota(0, 2_000_000).parallel)
```

-Steve


Is there a way to verify that it split up the work in to 
tasks/threads ...?  The example you gave me works...compiles w/o 
errors but the execution time is the same as the non-parallel 
version.  They both take about 6 secs to execute.  totalCPUs 
tells me I have 8 CPUs available.




Re: foreach (i; taskPool.parallel(0..2_000_000)

2023-04-01 Thread Paul via Digitalmars-d-learn

Thanks Steve.




foreach (i; taskPool.parallel(0..2_000_000)

2023-04-01 Thread Paul via Digitalmars-d-learn

Thanks in advance for any assistance.

As the subject line suggests can I do something like? :
```d
foreach (i; taskPool.parallel(0..2_000_000))
```
Obviously this exact syntax doesn't work but I think it expresses 
the gist of my challenge.


New to profiling: dmd -profile; ldc2 --fdmd-trace-functions

2023-03-31 Thread Paul via Digitalmars-d-learn

Thanks in advance for any assistance.

As the subject line states I'm just now trying to learn 
profiling.  I have a very small program with 1/2 dozen functions 
and would like to see where the cpu is spending the most time.


I've tried both of these lines with identical results:
**ldc2 --fdmd-trace-functions myprog.d**
**dmd -profile myprog.d**

The result is that no 'trace' files are generatedas far as I 
can tell.  When I run myprog.exe it generates no errors, runs 
very quickly, and does not do what it previously was doing.


**ldc2 --version**
**LDC - the LLVM D compiler (1.30.0-git-5fd86e5):**
**based on DMD v2.100.1 and LLVM 14.0.3**

**dmd --version**
**DMD64 D Compiler v2.100.2-dirty**


Re: Read a text file at once for regex searching

2023-03-20 Thread Paul via Digitalmars-d-learn

On Monday, 20 March 2023 at 17:47:19 UTC, Adam D Ruppe wrote:

On Monday, 20 March 2023 at 17:42:17 UTC, Paul wrote:

Do we have some such function in our std library?


Try

static import std.file;
string s = std.file.readText("filename.txt");


http://phobos.dpldocs.info/std.file.readText.html


Thanks Adam.


Read a text file at once for regex searching

2023-03-20 Thread Paul via Digitalmars-d-learn
I've been looking through our Library documentation and having 
trouble finding what I want.  **I'd like to read a text file in 
all at once** and do some searching and analytics on it instead 
of reading it bit by bit or line by line.  Do we have some such 
function in our std library?


Thanks in advance.


Re: Assign to Array Column

2023-01-31 Thread Paul via Digitalmars-d-learn

On Wednesday, 1 February 2023 at 03:45:11 UTC, Salih Dincer wrote:

On Tuesday, 31 January 2023 at 01:04:41 UTC, Paul wrote:
Can I perform a similar assignment to the column?  This, 
myArr[][0] = 5, doesn't work.


Of course, this question has a short answer and a long answer. 
So the issue is more about column-major. I am someone who likes 
to talk with codes. In fact, everything is side by side in 
memory. This example (something like array) covers the issue:


Thanks Salih.  Much appreciated.


Re: Address of a class object

2023-01-31 Thread Paul via Digitalmars-d-learn

On Thursday, 5 January 2023 at 05:59:26 UTC, Ali Çehreli wrote:

On 1/4/23 20:04, Paul wrote:
>> (Again, there is no problem here; we are just learning.)
>> Ali
>
> Do I have this much right?

> ..with this output?

Looks good to me.

While we're here, you can force the class objects to be on the 
stack as well:


scope MyClassVar1 = new MyClass();

I replaced 'auto' with 'scope'.

Ali


I was tinkering with this use of 'scope' and the math for pointer 
location, object size, and alignment started working out.


Assign to Array Column

2023-01-30 Thread Paul via Digitalmars-d-learn

Greetings,

for an array byte[3][3] myArr, I can code myArr[0] = 5 and have:
5,5,5
0,0,0
0,0,0

Can I perform a similar assignment to the column?  This, 
myArr[][0] = 5, doesn't work.


Thanks!


Re: Coding Challenges - Dlang or Generic

2023-01-12 Thread Paul via Digitalmars-d-learn
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

2023-01-10 Thread Paul via Digitalmars-d-learn

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.


Re: Coding Challenges - Dlang or Generic

2023-01-10 Thread Paul via Digitalmars-d-learn
On Tuesday, 10 January 2023 at 06:45:40 UTC, Siarhei Siamashka 
wrote:

...


What kind of D class is that? Are you learning D language in a 
school or university? Or is it some kind of online language 
course?

...
I don't know if there are rules about sharing links and such but 
its a site called https://www.educative.io/learn.  There are two 
D courses.  I just finished the second class.  The business model 
on 'Educative' is by subscription with maybe one week or month 
free trial.  So you can get as many certificates as you can 
complete during your subscription.  So I don't know how much 
weight the certificates carry but I have two D course 
certificates.





Re: Coding Challenges - Dlang or Generic

2023-01-10 Thread Paul via Digitalmars-d-learn

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):



...


Code will be graded on readability, unittest coverage, and 
reusability (how many functions have wide applicability outside 
of this challenge).


;-)


T


I think you must have done a blog post or tutorial or something, 
Teoh, because I've seen this before.  Don't let this go to your 
head :), but I was blown away by the presentation and solution!  
BTW where is it posted?




Coding Challenges - Dlang or Generic

2023-01-09 Thread Paul via Digitalmars-d-learn

Greetings Dlang-ers
I was wondering if anyone knew of any coding challenges available 
where the input and output are specified and its left to the 
programmer to find a solution?  Free would be nice but even paid 
services would be worth considering.  I'm taking a D class right 
now and it has little challenges in the lessons where much of the 
work is done for you, but I'm thinking of a site/service that is 
dedicated to these types of challenges (without doing any work 
for you).


I wonder if a site dedicated to Dlang challenges would 'fly'?  It 
would be quite interesting and instructive to see how different 
coders solved a particular coding problem.  Statistics could be 
generated for each solution (e.g. compile time, execution time, 
source code size, executable size, @safe, @nogc, readability of 
source code, helpfulness of comments, etc.).  With D's 
multi-paradigm power it could be fascinating.  I know.  Someone's 
going to say why don't YOU do it:)


regards,


Re: Address of a class object

2023-01-05 Thread Paul via Digitalmars-d-learn

On Thursday, 5 January 2023 at 05:59:26 UTC, Ali Çehreli wrote:

While we're here, you can force the class objects to be on the 
stack as well:


scope MyClassVar1 = new MyClass();

I replaced 'auto' with 'scope'.

Ali


Very interesting.  Thanks Ali.




Re: Address of a class object

2023-01-04 Thread Paul via Digitalmars-d-learn

(Again, there is no problem here; we are just learning.)
Ali


Do I have this much right?
```d
import std.stdio, std.traits;
class MyClass {char c;}

void main() {
auto MyInt = 1;
writeln("The address of MyInt is  :  ",," (stack)");
auto MyClassVar1 = new MyClass();
writeln("The address of MyClassVar1 is:  ",," 
(stack)");

auto MyClassVar2 = new MyClass();
writeln("The address of MyClassVar2 is:  ",," 
(stack)");


writeln;

auto MyClassObj1 = cast(void*)MyClassVar1;
writeln("The address of MyClassObj1 is: ",MyClassObj1," 
(heap)");

auto MyClassObj2 = cast(void*)MyClassVar2;
writeln("The address of MyClassObj2 is: ",MyClassObj2," 
(heap)");

}
```
..with this output?
```
The address of MyInt is  :  1CA1CFFB1C (stack)
The address of MyClassVar1 is:  1CA1CFFB10 (stack)
The address of MyClassVar2 is:  1CA1CFFB08 (stack)

The address of MyClassObj1 is: 1EB93212000 (heap)
The address of MyClassObj2 is: 1EB93212020 (heap)
```



Re: Address of a class object

2023-01-03 Thread Paul via Digitalmars-d-learn

matheus, using dmd64 on my laptop to compile and run this:
```d
import std.stdio, std.traits;

class MyClass {char[16] c;}

void main() {
writeln(" Size  Alignment  Type\n",
"=");

size_t size = __traits(classInstanceSize, MyClass);
size_t alignment = classInstanceAlignment!MyClass;
writefln("%4s%8s  %s",size, alignment, MyClass.stringof);

// my test code added
auto MyClassO1 = new MyClass();
auto MyClassO2 = new MyClass();
writeln("\nMyClassObj1 MyClassObj2");
writeln(cast(void*)MyClassO1,"\t",cast(void*)MyClassO2);
}
```
I get this:
```
 Size  Alignment  Type
=
  32   8  MyClass

MyClassObj1 MyClassObj2
21EF8E22000 21EF8E22020
```
If I change this line to:
```
class MyClass {char[1] c;}
```
I get this:
```
 Size  Alignment  Type
=
  17   8  MyClass

MyClassObj1 MyClassObj2
27727202000 27727202020
```
If my size is 17 bytes and my alignment is 8 bytes, shouldn't my 
MyClassObj2 in this example be @ 277272020**18** ?


Re: Address of a class object

2023-01-02 Thread Paul via Digitalmars-d-learn

Thank you, Teoh, Ali, & Matheus




Re: Address of a class object

2023-01-01 Thread Paul via Digitalmars-d-learn
Thanks all. Yes it seems my understanding and "D" vocabulary are 
still a bit confused.


So I'm taking a D course online and was trying to verify what I 
was learning. The course example printed out the size and 
alignment of types...something close to this:

```d
import std.stdio;
import std.traits;

class MyClass {char c;}

void main() {
writeln(" Size  Alignment  Type\n",
"=");

size_t size = __traits(classInstanceSize, MyClass);
size_t alignment = classInstanceAlignment!MyClass;

writefln("%4s%8s  %s",size, alignment, MyClass.stringof);

// my test code added
MyClass MyClassO1;
MyClass MyClassO2;
writeln("\n",,"\t",);
}
```
...on my laptop it prints...
```
 Size  Alignment  Type
=
   9   4  MyClass

4FFB20  4FFB24
```

If the size of MyClass is 9 bytes why do MyClassO1 & O2 addresses 
only differ by 4 bytes?


Because those addresses(4FFB20  4FFB24) are the addresses of the 
class **variables**, not the addresses of the **objects** 
themselves?


So, I guess my question is actually how do I print out the 
addresses of the MyClassO1 & O2 objects themselves?

```


Address of a class object

2022-12-31 Thread Paul via Digitalmars-d-learn

Hello.  Thanks for any assistance.

Can I acquire the address of a class object, not a class variable 
(i.e. the instantiations of the class) but the object definition 
itself?


```d
class MyClass {char c}
...
MyClass MyClassVar;

writeln(); // this compiles
writeln();// this does not
```


Re: _Symbols _with _leading _underscores

2022-12-19 Thread Paul via Digitalmars-d-learn

Much appreciated...


_Symbols _with _leading _underscores

2022-12-16 Thread Paul via Digitalmars-d-learn
I see code like this from time to time.  Are the leading 
underscores significant, in general, in the D language?  Is it 
just programmer preference? Is it a coding practice, in general, 
that is common...even outside of D?  Thanks for any assistance.


From: 
http://dpldocs.info/this-week-in-d/Blog.Posted_2022_10_10.html#hello-arduino


```d
import ldc.llvmasm;

// Ports from the delay_basic.h in the thing
void _delay_loop_1(ubyte __count) {
// this template param is required to avoid
	// assertion `!Call.getType()->isVoidTy() && "Bad inline asm!"' 
failed.


__asm!ubyte (
"1: dec $0\n\tbrne 1b",
"=r,0", (__count)
);
}
void _delay_loop_2(ushort __count) {
__asm!ushort (`
1: sbiw $0,1
brne 1b
`,
`=w,0`,
__count);
}

// port from delay.h in arduino thing
enum F_CPU = 1_000_000UL;

// this was _delay_ms but i did something wrong and changed 
double to int and i still don't love it

void _delay(int __ms) {
ushort __ticks;
ulong __tmp = (F_CPU * __ms) / 4000;
if(__tmp < 1)
__ticks = 1;
else if(__tmp > 65_535) {
__ticks = cast(ushort) (__ms * 10.0);
while(__ticks) {
_delay_loop_2(cast(ushort) (((F_CPU) / 4e3) / 10));
__ticks--;
}
return;
} else
__ticks = cast(ushort) __tmp;
_delay_loop_2(__ticks);
}
```


Re: Convert int to dchar

2022-10-05 Thread Paul via Digitalmars-d-learn

On Wednesday, 5 October 2022 at 17:16:29 UTC, H. S. Teoh wrote:



For the former:

dchar ch = '0' + intValue;



This! Thanks Teoh.




Re: Convert int to dchar

2022-10-05 Thread Paul via Digitalmars-d-learn

Thanks Steve.  I need to covert something like this:
int myvar = 5;
How would I convert myvar to a dchar?


Convert int to dchar

2022-10-05 Thread Paul via Digitalmars-d-learn
   I'm sure I'm making this more difficult than it needs to be.  
I'm trying to convert an integer to a dchar.  The solution below 
works but seems like overkill.


dstring dstrValue = to!dstring(5);
dchar dcharValue = to!dchar(dstrValue);

... this,

dchar dcharValue = to!dchar(5);

... writes out '\x005' ..or something close to that.


Re: write struct as raw data to file

2021-09-27 Thread Paul via Digitalmars-d-learn

Vitaliy,

Thanks for your assistance.  I was looking at your serialization 
package.  Is your example correct?


struct MyStruct {
ubyte mybyte1;
@NoCereal uint nocereal1; //won't be serialised
@Bits!4 ubyte nibble;
@Bits!1 ubyte bit;
@Bits!3 ubyte bits3;
ubyte mybyte2; }

assert(MyStruct(3, 123, 14, 1, 42).cerealise == [ 3, 0xea /*1110 
1 010*/, 42]);


   mybyte1   =   3 ?
   nocereal1 = 123 ?
   nibble=  14 ?
   bit   =   1 ?
   ??? bits3 = ___ ???
   mybyte2   =  42 ?


Re: write struct as raw data to file

2021-09-26 Thread Paul via Digitalmars-d-learn

Finished product...
~15k samples x 2 sin() waves/composite wave x 16 DTMF tones = 16 
DTMF wave files in ~40ms!


I love D.




Re: write struct as raw data to file

2021-09-26 Thread Paul via Digitalmars-d-learn


What's with the 4 bytes of zero?


I miss-counted.  All is well!

Thanks Ali / Steven



Re: write struct as raw data to file

2021-09-26 Thread Paul via Digitalmars-d-learn
Hmm...well this is what I did and sort of got what I wanted; it 
did compile and write data!


auto myStruct = new mystruct[1];
File f = File("myFile.wav", "wb");
f.rawWrite(myStruct);   //this is 44 bytes
f.rawWrite(shortWaveArray);

What I got in the file was this:
-my 44 byte myStruct data + (4 bytes of zero)!
-then, my shortWaveArray data

What's with the 4 bytes of zero?

Thanks


write struct as raw data to file

2021-09-26 Thread Paul via Digitalmars-d-learn
I'm building a binary file.  I can write my 'short[] myArray' 
directly to the file using: File f = File( "myFile.wav", "wb" ); 
f.rawWrite(myArray); It doesn't write any array formatting stuff 
(i.e. '[ ,  , ]'); it just moves the data into myFile like I want.


I can't seem to do this with myStruct? myStruct is just a 
declaration and initialization of a dozen atomic types (e.g uint 
WAVE_Id = 0x45_56_41_57).  When I issue f.rawWrite(myStruct), it 
writes "myStruct(...,...,etc. ) instead of just writing the data.


Is there way to write the myStruct data to the file in a single 
statement...or two?


Thanks for any assistance.



Re: associative array with element type struct ?

2021-09-23 Thread Paul via Digitalmars-d-learn

Of course! And it's very common. <= lol


Thanks Ali.  Much appreciated!






associative array with element type struct ?

2021-09-23 Thread Paul via Digitalmars-d-learn
Can I have an associative array with the element type being a 
struct?

..this
26  // simple dual tone key struct
27  struct keytones { ushort rowFreq; ushort colFreq; }
28
29  // keypad associative array
30  keytones[string] keypad;
31  keypad["1"].rowFreq = 697; keypad["1"].colFreq = 1209;

...gets this response from DMD compiler

aaa.d(30): Error: undefined identifier `keypad`
aaa.d(30): Error: declaration `aaa.main.keytones` is already 
defined

aaa.d(27):`struct` `keytones` is defined here

thanks for any assistance!


DMD32 D Compiler v2.097.2-dirty ?

2021-09-06 Thread Paul via Digitalmars-d-learn
I like to write CLEAN code:)  Why does my DMD installation say 
v2.097.2-dirty?


Re: Assigning to class struct member leading to unexpected behavior.

2021-01-27 Thread Paul via Digitalmars-d-learn

On Thursday, 28 January 2021 at 02:03:40 UTC, Paul Backus wrote:
The braced-initializer syntax only works in declarations, not 
assignments.


Oh, I see, I'm guessing that explains the (sadly unfinished) 
In-place struct initialization

DIP of wilzbach.
(https://github.com/dlang/DIPs/pull/71)

Kind of sad so many DIP's seem to end up stranded :/


Assigning to class struct member leading to unexpected behavior.

2021-01-27 Thread Paul via Digitalmars-d-learn
I'm experiencing a compile error, but for the life of me, I 
cannot figure out what is wrong.


I'll try to keep it short but the code is roughly as follows:

class Window{
   Screen screen;
   alias screen this;

this() {
Screen s = {bottom_f: {[0, 1]}};
this.screen = s; // Works
this.screen = {bottom_f: {[0, 1]}}; // Leads to the 
list of errors below

}
...
}



struct Screen{
Vec!(2, int) bottom_f;
...
}



alias Vec(uint size, Type) = Mat!(size, 1, Type);

struct Mat(uint rows, uint columns = rows, Type = float) {
private enum uint size = rows * columns;
union{
Type[columns][rows] mat;
Type[size] vec;
}
static if (columns == 1) alias vec this;
else alias mat this;
. . .
}



List of errors:
1. "Label "bottom_f" is not used."
2. "expected ; instead of }"
3. "found `}` when expecting `;` following statement"
4. "use `{ }` for an empty statement, not `;`"
5. "found `void` when expecting `;` following statement" (later 
at function below constructor)


Why would assigning to a member variable lead to errors when 
using an intermediate variable of the same type does not?
I tried tweaking a lot but I just can't figure it out. Am I doing 
something wrong?


Re: Template argument deduction not working with template specialization

2021-01-17 Thread Paul via Digitalmars-d-learn
I just figured out half of my frustration is caused by a 
collision between the 'alias this'd template possibillity and the 
normal one.

For example:


struct Bar(uint size, V) {
V[size] blup;
alias blup this;
}

void foo(S : T[], T)(S a) {
pragma(msg, "first");
}

void foo(S : Bar!(T, U), uint T, U)(S a) {
pragma(msg, "second");
}



Bar!(2, int) bar;
foo(bar);


Will cause "called with argument types `(Bar!(2u, int))` matches 
both:DUB"
(And "undefined identifier `T`DUB", "undefined identifier 
`U`DUB", but thats a false positive :/)
While removal of either will make it work fine, as would removal 
of the alias.


Templating:
The template picked to instantiate is the one that is most 
specialized that fits the types of the TemplateArgumentList.

Alias this:
If an aggregate declaration defines an opCmp or opEquals 
method, it will take precedence to that of the aliased this 
member.


I was of the impression D only defaulted to the alias when the 
original implementation of a (member) function was missing / 
disfunctional. Shouldn't aliasing also follow this logic when 
using template specializations? (Even though it may not be a 
member function)


Re: Template argument deduction not working with template specialization

2021-01-17 Thread Paul via Digitalmars-d-learn
On Sunday, 17 January 2021 at 16:42:27 UTC, Steven Schveighoffer 
wrote:
I've always hated that aspect of specialization. I don't really 
understand why it's valid (how can T be T[]?)


I totally agree with that, that confuses me as well.


This works:

void TFoo(T : U[], U)(T a)


Oh cool, that's surprising to say the least. Thanks! This indeed 
works with argument deduction :)


Template argument deduction not working with template specialization

2021-01-17 Thread Paul via Digitalmars-d-learn
While trying to use template specializations I noticed the 
argument deductions do not yield the same version as the ones 
yielded when being explicit.

Example:


uint a = 1;
uint[] b = [2];
TFoo(a);
TFoo!(uint[])(b);



void TFoo(T)(T a) {
pragma(msg, "T: " ~ T.stringof);
}

void TFoo(T : T[])(T[] a) {
pragma(msg, "T[]: " ~ T.stringof);
}


I noticed that an automatically deduced TFoo call always yields 
the first, while TFoo!(uint[]) yields the array version if 
present, and defaults to the first elsewise.


Am I incorrect in expecting the same behavior when (ab)using 
argument deduction or does my usage make sense? I tried searching 
for this combination (deduction & specialization) but couldn't 
find another forum post / documentation example.


Re: Template alias as template specialisation not recognized.

2021-01-15 Thread Paul via Digitalmars-d-learn

On Saturday, 16 January 2021 at 01:38:38 UTC, Paul Backus wrote:

You have encountered issue 1807:

https://issues.dlang.org/show_bug.cgi?id=1807


Ah I see, thank you, sad to see several DIP's I'd be interested 
in are postponed :(

Thanks for the workaround hint, I'll probably be using that.


Template alias as template specialisation not recognized.

2021-01-15 Thread Paul via Digitalmars-d-learn
I'm having issues when trying to use a template alias as a 
template specialisation.

When using the following:

alias Vec(uint size, Type) = Mat!(size, 1, Type);


void setUniform(V : Vec!(L, bool), int L)(string name, V value) 
{...}



Vec!(4, bool) a;
setUniform("test", a);


I get the following error:
template `shader.Shader.setUniform` cannot deduce function from 
argument types `!()(string, Mat!(4u, 1u, bool))`, candidates 
are:DUB
shader.d(43, 7): `setUniform(V : Vec!(L, bool), uint L)(string 
name, V value)`


Meanwhile, when using the following, I have no issues:
void setUniform(V : Mat!(L, 1, bool), int L)(string name, V 
value) {}


Re: opCast / operator overloading with additional template arguments

2021-01-10 Thread Paul via Digitalmars-d-learn
On Monday, 11 January 2021 at 00:48:49 UTC, Steven Schveighoffer 
wrote:

I would think though, that this should work:

T opCast(T : Vec!(vecsize, S), S)()


Oh wouw, this seems to work perfectly! Awesome thanks ^^

Any Idea why

T opCast(T, S)() const if (is(T : Vec!(grootte, S))) {

yields the error
template instance opCast!(Vec!(2, double)) does not match 
template declaration opCast(T, S)()
while your suggestion does not? It seems to me it should match 
equally well.


Also I had no clue types inferred in constraints were 
inaccessibly, I'll try to keep that in mind, though I wonder, is 
there is any specific reason for that? Then again since your 
example works inferred values shouldnt be necessary in 
constraints anyway.
(On that note, is there per chance something like the underscore 
'_' as in python? In some cases I don't care for all the template 
arguments inside an is expression (with the (a:b, c) version))


Re: opCast / operator overloading with additional template arguments

2021-01-10 Thread Paul via Digitalmars-d-learn

On Monday, 11 January 2021 at 02:37:24 UTC, Ali Çehreli wrote:

>> T opCast(T)() const if (is(T : Vec!(size, S2), S2)) {


The is expression can be so complicated that I used a different 
approach below.



  if (isInstanceOfVec!T &&
  T.init.content.length == size) {
// ADDED:
alias S2 = typeof(T.init.content[0]);


Is it ok to use .init even though we don't need an instantiated 
value?


Re: opCast / operator overloading with additional template arguments

2021-01-10 Thread Paul via Digitalmars-d-learn

On Monday, 11 January 2021 at 00:25:36 UTC, Ali Çehreli wrote:
You don't show complete code; so, I hope I came up with 
something that reflects your case.


Thank you, sadly S (S2 now) is not any specific type, sorry I'll 
paste more of my file, I hope that's ok. (Sidenote, I'm not sure 
it's the most elegant approach to have a templated union like 
this, and I left out some unnecessary stuff like 'opBinary')



version (HoekjeD_Double) {
private alias standard_accuracy = double;
} else {
private alias standard_accuracy = float;
}

struct Vec(int size, S = standard_accuracy) {
union {
S[size] content;
static if (size >= 1) {
struct {
S x;
static if (size >= 2) {
S y;
static if (size >= 3) {
S z;
static if (size >= 4)
S w;
}
}
}
}
}

T opCast(T)() const if (is(T : Vec!(size, S2), S2)) {
T converted;
static foreach (i; 0 .. size)
converted.content[i] = cast(S2) content[i];
return converted;
}
}


opCast / operator overloading with additional template arguments

2021-01-10 Thread Paul via Digitalmars-d-learn
Is there a way to have additional template arguments in operator 
overloads?
The problem I'm having is mostly caused by casting a templated 
struct to other templated structs. I had the following code;



T opCast(T)() const if (is(T : Vec!(vecsize, S), S)) {
T converted;
static foreach (i; 0 .. vecsize)
converted.content[i] = cast(S) content[i];
return converted;
}


When I try to use this, I get the error 'undefined identifier S'.
Alternatively using:

T opCast(T, S)() . . .
causes the error 'template instance opCast!(Vec!(2, double)) does 
not match template declaration opCast(T, S)()'


I found using 'alias S = typeof(content[0])' works as a kind of 
ducttape alternative, however this seems like a codesmell to me, 
and I fear it won't scale well either.


Am I missing a simple solution? And why is there no automatic 
argument deduction in this scenario when compared to normal 
function calls? (if the above opcast is translated to 
'foo.opCast!T`)


Conflict when using stderr with import.

2021-01-04 Thread Paul via Digitalmars-d-learn
I'm trying to use stderr.writefln, while using the 
'bindbc-opengl' package, but when I try to I get the message:


source\app.d(13,2): Error: function 
std.stdio.makeGlobal!"core.stdc.stdio.stderr".makeGlobal at 
C:\D\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(4853,20) 
conflicts with variable core.stdc.stdio.stderr at 
C:\D\dmd2\windows\bin\..\..\src\druntime\import\core\stdc\stdio.d(908,18)
source\app.d(13,8): Error: template makeGlobal(StdFileHandle 
_iob)() does not have property writeln

C:\D\dmd2\windows\bin\dmd.exe failed with exit code 1.


This only happens when I import the 'bindbc.opengl' module I 
need, and importing less or being more specific also seems to 
leads to issues.
Is there a way to prevent things like this / am I doing something 
wrong? Or is the issue more on the package's side? (In which case 
I may be asking at the wrong address)


Re: Tuple enumeration without integers or strings

2021-01-03 Thread Paul via Digitalmars-d-learn

On Sunday, 3 January 2021 at 06:05:48 UTC, frame wrote:

The hash is also generated at compile time.


Is there an easy way for me to know when code is assessed / 
generated at compile time?
For example, is indexing a constant compile time array compile 
time or run time?
Or how about functions? The hashOf documentation does not seem to 
hint to being done at compile time.


Re: Tuple enumeration without integers or strings

2021-01-02 Thread Paul via Digitalmars-d-learn

On Sunday, 3 January 2021 at 02:17:43 UTC, frame wrote:

Besides the problem with equal values, what's wrong with that:

alias Thing = Tuple!(int, int);
enum Wind {
A = Thing(0, 1),
B = Thing(0, 2),
C = Thing(0, 2)
}

void some_function(Wind w) {
switch (w.hashOf) {
case Wind.B.hashOf:
break;

default:
assert(0);
}
}

void main() {
some_function(Wind.B);
writefln("%d%d", Wind.C.expand);
}


I haven't used hashOf before, though assuming no  equal values, 
which I generally wouldn't do, I take it this is reliable? I 
haven't tried it before, and I dont know how to effectively 
compare it to using 'switch(w.to!string)' & 'case 
Wind.B.stringof' (regarding speed/reliability).


Re: Tuple enumeration without integers or strings

2021-01-02 Thread Paul via Digitalmars-d-learn

On Saturday, 2 January 2021 at 21:48:04 UTC, Paul Backus wrote:
Yes, but this will be true of any approach you choose. If two 
enum members have exactly the same value, there is no way to 
distinguish between them, either at compile time or at runtime.


Oh I see, thanks!
A bit of a bummer as I guess that means you're pretty much 
required to use an additional seperate structure like an array or 
map/associative array, the latter making the use of an enum 
instead of string names slightly pointless in this scenario, 
thank you nontheless .


Re: Tuple enumeration without integers or strings

2021-01-02 Thread Paul via Digitalmars-d-learn

On Saturday, 2 January 2021 at 03:20:29 UTC, Paul Backus wrote:
D's switch statement only works on strings and integers. For 
more complex values, the easiest thing is to just use an 
if-else chain.


If you really want to use a switch statement, you can do it by 
defining a function that maps each of your enum values to a 
unique integer; for example:


Im afraid that would still result in issues when duplicate enum 
vlues are at play right?

(This issue would maybe warrant a compile time warning imho)


Re: Tuple enumeration without integers or strings

2021-01-01 Thread Paul via Digitalmars-d-learn
It seems w.to!string works in conjunction with Wind.N.stringof, 
though I wonder about the efficiency/wastefulness of this method.
Sadly this also leads to very funny behavior when some of the 
enums have the same value, as to!string(Enum) will yield the name 
of the first of these enums having the same values.



alias Thing = Tuple!(int, int);
enum Enum {
A = Thing(0, 1),
B = Thing(0, 2),
C = Thing(0, 2)
}
void main(){
Enum.C.to!string.writeln;
}


For example, the code above will print 'B' (I'm slightly curious 
how & why std.conv uses the Enum name when converting to string, 
instead of using the value, especially since I didn't see this 
pitfall coming partly due to this)


So this neither seems a satisfiable solution to me :/


Re: New integer promotion rules

2021-01-01 Thread Paul via Digitalmars-d-learn

On Thursday, 18 January 2018 at 16:31:02 UTC, ag0aep6g wrote:
I'm interpreting that to mean that it will become an error for 
some time, but later it will be allowed again with the new 
behavior. And then you can throw away `-transition=intpromote`.


Seeing as it's almost 3 years later, I'd like to ask, is there an 
indication of when this will happen? It seems to still be around.


Re: Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

On Wednesday, 28 October 2020 at 15:27:04 UTC, H. S. Teoh wrote:


foreach (key; aa.keys.sort!((a,b) => aa[a] < aa[b])) {
writeln(key);


This solution worked perfectly without modifying any of my other 
code.  I don't fully understand it but can study up on the syntax.


Re: Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

On Wednesday, 28 October 2020 at 15:40:23 UTC, aberba wrote:

Have you tries .values() function? dictionary.values.sort()


Thanks aberba. Yes, that was my first attempt!

If my terminology is correct that gives me a "range" of sorted 
VALUES.
I think I can't "iterate"(foreach) through an array of VALUE[KEY] 
using the VALUE.  I can only iterate over the KEYS...maybe?


If my array is of type int[string] I can do:

foreach(word-STRING, range-of-STRINGS) 
writeln(dictionary[word-STRING]);


but not:

foreach(value-INT, range-of-VALUES) 
writeln(dictionary[value-INT]<- wrong type);






Re: Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

On Wednesday, 28 October 2020 at 15:25:26 UTC, Paul Backus wrote:


auto sorted = dictionary.byPair.array.sort!((a, b) => a.value < 
b.value)


It seems this method produces a ?sorted array of tuples?
[..Tuple!(string, "key", uint, "value")("Program", 74),
   Tuple!(string, "key", uint, "value")("rd", 74)..]
I guess I would just have to iterate through the tuples.



Re: Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

Thanks Teoh




Re: Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

On Wednesday, 28 October 2020 at 15:25:26 UTC, Paul Backus wrote:

On Wednesday, 28 October 2020 at 15:15:40 UTC, Paul wrote:

per the D sample wc2.d
size_t[string] dictionary;  <-is printed by...
.
foreach (word1; dictionary.keys.sort) writef etc

I want to print the dictionary sorted by value not key.  I can 
write an algorithm but is there a library method(s) I can use 
to iterate through the array sorted by decreasing values?


Thanks for your time.


import std.array, std.algorithm;

auto sorted = dictionary.byPair.array.sort!((a, b) => a.value < 
b.value)


Thanks Paul


Print int[string] sorted by Value

2020-10-28 Thread Paul via Digitalmars-d-learn

per the D sample wc2.d
size_t[string] dictionary;  <-is printed by...
.
foreach (word1; dictionary.keys.sort) writef etc

I want to print the dictionary sorted by value not key.  I can 
write an algorithm but is there a library method(s) I can use to 
iterate through the array sorted by decreasing values?


Thanks for your time.




Compile and run in Win10-VSCode

2020-09-25 Thread Paul via Digitalmars-d-learn

Hi Community,

I'm Win10: I have VSCode installed.  I have DMD installed and can 
compile examples from a Win CMD console.


1) How do I compile and run from within VSCode?
2) VSCode Extensions:
  Do I need them?
  One kept generating errors and a note said it was not under 
active development so I

 uninstalled it.
  The remaining two are by WebFreak.  Are they working?  Do I 
need them?


Thanks for your time.


Re: Example uses "volatile"; compiler says "undefined identifier volatile"

2019-08-01 Thread Paul via Digitalmars-d-learn

Thank you.  I'll try that.




Example uses "volatile"; compiler says "undefined identifier volatile"

2019-07-31 Thread Paul via Digitalmars-d-learn
I'm trying to build a Bare Bones 'OS' via example.  Example says 
to compile with
"gdc -c kernel.main.d -o kernel.main.o -g"  I'm having trouble 
getting GDC all set up..as I'm a rank amateur.  So, I tried 
compiling the example below with DMD.  DMD spits out exceptions 
to the use of 'volatile'. DIP62 on D wiki says status:REJECTED 
for volatile.
Whats my work around here?  This is what I'm trying to do-> 
https:// wiki.osdev.org / D_Bare_Bones


Thanks for any help.

module kernel.main;

extern(C) void main(uint magic, uint addr) {
int ypos = 0; //Starting points of the cursor
int xpos = 0;
const uint COLUMNS = 80; //Screensize
const uint LINES = 25;

	ubyte* vidmem = cast(ubyte*)0x_8000_000B_8000; //Video 
memory address


	for (int i = 0; i < COLUMNS * LINES * 2; i++) { //Loops through 
the screen and clears it

volatile *(vidmem + i) = 0;
}

	volatile *(vidmem + (xpos + ypos * COLUMNS) * 2) = 'D' & 0xFF; 
//Prints the letter D
	volatile *(vidmem + (xpos + ypos * COLUMNS) * 2 + 1) = 0x07; 
//Sets the colour for D to be light grey (0x07)


for (;;) { //Loop forever. You can add your kernel logic here
}
}


Re: Moving location of dub packages?

2019-07-21 Thread Paul via Digitalmars-d-learn

On Sunday, 21 July 2019 at 09:42:15 UTC, Andre Pany wrote:

On Sunday, 21 July 2019 at 09:20:52 UTC, Andre Pany wrote:

On Saturday, 20 July 2019 at 12:47:59 UTC, Paul wrote:
I'd like to move where dub has stored packages to a shorter 
path, is there a procedure for this?


Thanks in advance!


Maybe the custom cache paths could help you here:
https://dub.pm/settings.html

Kind regards
Andre


Or you can set the environment variables before calling dub. 
The actual environment variables depends on your operation 
system.


Please see here:
https://github.com/dlang/dub/blob/master/source/dub/dub.d#L272

Kind regards
Andre


I don't think those options change where dub saves newly 
downloaded packages but it's good to know the options available.


Thanks for the help!

Paul


Moving location of dub packages?

2019-07-20 Thread Paul via Digitalmars-d-learn
I'd like to move where dub has stored packages to a shorter path, 
is there a procedure for this?


Thanks in advance!


Re: Quotes inside wysiwyg strings, or alternative solution?

2019-07-18 Thread Paul via Digitalmars-d-learn

All string literals may span multiple lines.


Ah, I didn't know that. Thanks for the detailed reply!


Quotes inside wysiwyg strings, or alternative solution?

2019-07-18 Thread Paul via Digitalmars-d-learn

Hi,

I have searched, but can't find a solution. In C++ and Rust there 
is the option of enclosing a string in a sequence of chars (after 
R/r) to allow quotation marks in multiline string literals.


What is the solution in D for wysiwyg strings (or similar) 
spanning multiple lines containing quotes and apostrophes?


Thanks!

(also, how can I put formatted code in a post?)


Re: How to concatenate a tuple of strings at compile time?

2018-01-06 Thread paul via Digitalmars-d-learn

Thanks for the input.

Unfortunately I still can't convince the compiler. __traits 
allMembers includes functions. Trying to filter those with 
std.traits.isCallable, it complains about strings that can't be 
read or fields that can't be accessed at compile time. Affected 
are both solutions.


So any insight in why mixin(fullyQualifiedName!T ~ "." ~ item) 
produces a compiler error saying that string can't be accessed at 
compile time would be very appreciated.


Same goes for [tuple(..)].filter!(item => 
!isCallable!(mixin(fullyQualifiedName!T ~ "." ~ item))).join;





How to concatenate a tuple of strings at compile time?

2018-01-06 Thread paul via Digitalmars-d-learn

Hi!

How to concatenate  a tuple of strings at compile time?

Appending to an enum or an immutable string in a static foreach 
doesn't work. (And shadowing the thing doesn't work either) a)
Calling a function recursively doesn't work because I had to turn 
the tuple into an array which cannot be read at compile time. b)


a)
enum/immutable string connected;
static foreach(item; __traits(something))
  connected ~= item;

b)
string concat(string[] a, string b = "", index i = 0)
{
  if (s.length - 1 == index)
  {
 return b ~ a[$-1];
   } else {
 return concat(a,b[index],index+1);
   }
}
concat([__traits(something)]);

An internet search didn't reward any solution but probably I'm 
just missing something very trivial.

Any clues would be very appreciated. Thanks.

On a different note, what I want to achieve is to automatically 
generate a function call that hides the fact of a struct being 
initialized.


something like this:

struct X
{
  int a;
  string b;
}

class C
{
  X _x;

  this(int a, string b)
  {
_x = X(a, b);
  }
}



Re: Initialise dynamic array in array of structures

2016-06-22 Thread Paul via Digitalmars-d-learn

On Tuesday, 21 June 2016 at 19:33:31 UTC, cym13 wrote:
... but “trackTemplates[0].coords = [{0, 9}, {1, 1},
{3, 6}];” is an assignment so the compiler can infer as much 
and doesn't understand that each of those list of values are 
really CoordLists.


I see, but it seems a bit strange given that they are being 
assigned to .coords[] which is already defined as of type 
CoordList.


trackTemplates[0].coords = [CoordList(0, 9), CoordList(1, 1), 
CoordList(3, 6)];” would have worked as expected.


I'd want to avoid this wordy explicit way as the list can extend 
to several hundred pairs. Most likely I need a better way to 
store the information.


@ketmar:

Why is initialisation via {} bad (in simple terms please :D)? I 
noticed while working on this bit of code that I could initialise 
simple struct variables with {} but couldn't do the same with an 
array of structs. I guess this is for the same or similar reason 
to the above.


Thanks both for the help.


Initialise dynamic array in array of structures

2016-06-21 Thread Paul via Digitalmars-d-learn

Given these structures and declaration:

struct CoordList{
int x, y;
}

struct Part{
int x, y;
CoordList[] coords;
int nextNode, prevNode;
string nextEnter, prevEnter;
}

Part[10] trackTemplates;


Can someone please tell me why I can't initialise Part[0].coords 
like this:


trackTemplates[0].coords = [ {0, 9}, {1, 1}, {3, 6} ];

but I can do this:

CoordList[] temp = [ {0, 9}, {1, 1}, {3, 6} ];
trackTemplates[0].coords = temp;

Many thanks!






Re: ref parameter qualifier and static arrays

2015-09-10 Thread Paul via Digitalmars-d-learn

On Wednesday, 9 September 2015 at 20:35:53 UTC, anonymous wrote:

When you pass a slice (without ref), what's actually passed is 
a pointer and length. The contents are not copied. That means, 
when you alter an array element, the change will be done the 
original, even without ref:


Thanks both.

I see, temporary variable and no ref will do the job and I 
suppose it's better than just using a global...




ref parameter qualifier and static arrays

2015-09-09 Thread Paul via Digitalmars-d-learn


Is it possible to call a function like this...

void foo(ref int[] anArray)

...with slices of static arrays? I thought I might be able to use 
[0..$-1] but to no avail - I get an error like this (which is 
confusing!):


(ref int[] anArray) is not callable using argument types (int[])

I've modified the function declaration and used .ptr when calling 
it but it seems like a retrograde step for a modern language - 
although I suppose ref is pretty much the same thing.


In practice I'm using arrays of structs (which are of various 
fixed sizes and known at compile time) that are currently global 
in scope - something that I'd like to avoid.


I suppose I could just ask, what is the 'best' way to give access 
to variously sized static arrays between different modules?





Re: Superfluous code in switch statement

2015-09-05 Thread Paul via Digitalmars-d-learn

On Friday, 4 September 2015 at 21:20:11 UTC, Timon Gehr wrote:

On 09/04/2015 11:12 PM, anonymous wrote:

On Friday 04 September 2015 23:04, Timon Gehr wrote:


DMD never warns about dead code.


It warns here:


import std.stdio;
void main()
{
 return;
 writeln("hi"); /* Warning: statement is not reachable */
}




You are right, it does. Then I suppose there is no reason why 
it shouldn't warn in the switch case.


I see, thanks.


Superfluous code in switch statement

2015-09-04 Thread Paul via Digitalmars-d-learn
I discovered the other day (during a cut and paste malfunction!) 
that it's possible to have code before the first case in a 
switch. Google tells me that it's legal C code and something I 
read said it could be used for initialization but was rather 
vague.


void main()
{
import std.stdio;

int a=1;

switch(a)
{
a=2;
writeln("hello");

case 1:
break;
case 2:
break;
default:

}
writeln(a);

}

The code before the 'case' has to be legal D code to pass 
compilation but it seems to have no effect (which is probably a 
good thing!). I was a bit surprised that the compiler (dmd) 
didn't generate a warning when using the -w option.


Can someone explain what's going on here please?



Re: tkd - basic compilation problem

2015-07-02 Thread Paul via Digitalmars-d-learn

On Thursday, 2 July 2015 at 17:41:45 UTC, Gary Willoughby wrote:


This is exactly why you use dub, so you don't have to worry 
about all this!


You're right, there's sufficient information there if using dub.


Re: tkd - basic compilation problem

2015-07-01 Thread Paul via Digitalmars-d-learn

On Wednesday, 1 July 2015 at 09:38:05 UTC, Marc Schütz wrote:
Someone more familiar with Debian/Ubuntu than me may be able to 
help you here, sorry.


I was hoping to keep a tight rein on what was required to be 
installed to simplify deployment but its spiraling out of 
control again LOL.


The -dev packages are only required during development 
(specifically at link time), the resulting binary only needs 
the normal packages installed.


Thanks Marc, I found the required packages... it threw me because 
they don't have any version number in the repo ... and the 
example works just fine now.


Re: tkd - basic compilation problem

2015-07-01 Thread Paul via Digitalmars-d-learn

On Wednesday, 1 July 2015 at 17:43:11 UTC, Gary Willoughby wrote:

On Tuesday, 30 June 2015 at 12:58:21 UTC, Paul wrote:

...


I really don't understand posts like this when literally all 
information needed is in the README file:


https://github.com/nomad-software/tkd

Just read RTFM.


I read that before posting, specifically the parts that say:

Tkd requires version 8.6 (or greater) of the Tcl/Tk libraries 
installed. A small exception is when creating a self-contained 
installation on Windows. See details below. Tcl/Tk itself 
requires the x11 libraries installed on Linux only.


and

On Linux and Mac OSX things are a little easier as both 
operating systems have Tcl/Tk installed by default. If however 
they do not have the latest version, the libraries can be updated 
via their respective package managers. The linked libraries are 
libtcl and libtk.


I can't see how they answer the questions I've asked (which 
admittedly are more related to the distro that D per se).






Re: tkd - basic compilation problem

2015-07-01 Thread Paul via Digitalmars-d-learn

On Wednesday, 1 July 2015 at 18:38:27 UTC, Jordi Sayol wrote:


For shared linking against libphobos2.so and libtkd.so:
$ dmd `pkg-config --cflags --libs tkd` 
-J/usr/share/libtkd-doc/example/media/ 
/usr/share/libtkd-doc/example/example.d


For static linking against libphobos2.a and libtkd.a:
$ dmd `pkg-config --cflags --libs tkd-static` 
-J/usr/share/libtkd-doc/example/media/ 
/usr/share/libtkd-doc/example/example.d



Thank you Jordi, I've got everything installed ok now but those 
linking instructions might come in very handy!


Re: tkd - basic compilation problem

2015-07-01 Thread Paul via Digitalmars-d-learn

On Tuesday, 30 June 2015 at 16:06:41 UTC, Marc Schütz wrote:

On Tuesday, 30 June 2015 at 15:25:27 UTC, Alex Parrill wrote:

On Tuesday, 30 June 2015 at 14:28:49 UTC, Paul wrote:

Using dub I get this during linking:

Building tkd-test ~master configuration application, build 
type debug.

Compiling using dmd...
Linking...
/usr/bin/ld: cannot find -ltcl
/usr/bin/ld: cannot find -ltk

...any suggestions please?


You need to install the libraries. Ex `sudo apt-get install 
libtcl8.5 libtk8.5`


Or the corresponding -dev packages.


Hmmm, I have libtcl8.6 and libtk8.6 installed already. The only 
dev packages I see are tclcl and tclap - I can't find any libtk 
-dev package.


I was hoping to keep a tight rein on what was required to be 
installed to simplify deployment but its spiraling out of control 
again LOL.


Re: tkd - basic compilation problem

2015-06-30 Thread Paul via Digitalmars-d-learn

On Tuesday, 30 June 2015 at 13:22:43 UTC, Paul wrote:

On Tuesday, 30 June 2015 at 13:19:25 UTC, Marc Schütz wrote:
If you don't want to use DUB, you need to download the other 
two packages from code.dlang.org and specifiy 
-I/path/to/tcltk -I/path/to/x11 -I/path/to/tkd in the DMD 
invocation.


Thank you, I'll try that.


Added info: I wanted to avoid using dub so I could manually 
figure out what would be required to distribute the application.


Re: tkd - basic compilation problem

2015-06-30 Thread Paul via Digitalmars-d-learn

On Tuesday, 30 June 2015 at 13:19:25 UTC, Marc Schütz wrote:
If you don't want to use DUB, you need to download the other 
two packages from code.dlang.org and specifiy -I/path/to/tcltk 
-I/path/to/x11 -I/path/to/tkd in the DMD invocation.


Thank you, I'll try that.


  1   2   >