Re: Challenge Tuples

2024-04-26 Thread matheus via Digitalmars-d-learn

On Friday, 26 April 2024 at 13:25:34 UTC, Salih Dincer wrote:

...


Very nice, for your first example I need to think a bit because 
I'm bit rusty in C#, but I think it will not be as easier as D 
version.


For the bonus part:

private static void Main(string[] args){
var a = (1,2,3,(1,3),5);
var t = a as ITuple;
var xx = new List();

for(var i=0;i   if(t[i].GetType() == 
typeof(System.ValueTuple)){

  var t2 = (t[i] as ITuple);
  var s = 0;
  for(var j=0;jAgain I'm rusty in C#... but so far yes it's more verbose than 
the D version.


Matheus.


Re: How to make fields inaccessible (unreadable and unachangeable) outside of the structure?

2024-03-29 Thread matheus via Digitalmars-d-learn

On Saturday, 30 March 2024 at 02:11:25 UTC, zjh wrote:
On Friday, 29 March 2024 at 22:50:53 UTC, curiousprogramma08 
wrote:



you can use openD.


Wait a minute, they already added this modification into their 
language?


Interesting!

Matheus.


Re: How to make fields inaccessible (unreadable and unachangeable) outside of the structure?

2024-03-29 Thread matheus via Digitalmars-d-learn
On Friday, 29 March 2024 at 22:50:53 UTC, curiousprogramma08 
wrote:

...


If I'm not mistaken, like in classes "private" is module based: 
https://wiki.dlang.org/Access_specifiers_and_visibility


Matheus.


Re: Why is this code slow?

2024-03-24 Thread matheus via Digitalmars-d-learn

On Sunday, 24 March 2024 at 19:31:19 UTC, Csaba wrote:

...

Here are the results:

C: 0.04s
Python: 0.33s
D: 0.73s

...


I think a few things can be going on, but one way to go is trying 
using optimization flags like "-O2", and run again.


But anyway, looking through Assembly generated:

C: https://godbolt.org/z/45Kn1W93b
D: https://godbolt.org/z/Ghr3fqaTW

The Leibniz's function is very close each other, except for one 
thing, the "pow" function on D side. It's a template, maybe you 
should start from there, in fact I'd try the pow from C to see 
what happens.


Matheus.


Re: Alguien me dice como podria conectarme a una base de datos en SQL server?

2024-03-14 Thread Matheus via Digitalmars-d-learn

On Thursday, 14 March 2024 at 17:08:17 UTC, dany wrote:

...
queria conectarme a SQLserver :'(


You will need an ODBC driver (Bindings):

https://code.dlang.org/packages/arsd-official%3Amssql

Matheus.


Re: The difference between the dates in years

2024-02-10 Thread matheus via Digitalmars-d-learn

On Saturday, 10 February 2024 at 22:11:48 UTC, Brad Roberts wrote:
Back when I was doing lots of software developer interviews, 
one of my frequent questions involved date math.  This wasn't 
because it's difficult from a coding standpoint, but that it's 
NOT a coding problem. The key part of the question is 
realization that it's a requirements question.  The thing that 
makes dates complicated is defining what the question actually 
is.


The topic _seems_ like it should be simple, but the deeper you 
dig the more you realize it's anything but simple.




Interesting but I have a doubt, they (Interviewees) should do the 
test with already existing Date Functions of given language or 
write new ones?


Matheus.


Re: The difference between the dates in years

2024-02-10 Thread matheus via Digitalmars-d-learn
On Saturday, 10 February 2024 at 19:16:35 UTC, Alexander Zhirov 
wrote:

...


Maybe this will help: I think if you will divide it can't be 365, 
but 365.242199.


About your code: I having tested fully, but I found a few 
problems and I wrote (Again without further tests) as below:


import std;

int getDiffYears(string date) {
auto currentDate = cast(Date)Clock.currTime();
auto startDate = Date.fromISOExtString(date);
auto currentDay = currentDate.dayOfYear;
auto startDay = startDate.dayOfYear;
auto currentMonth = currentDate.month;
auto startMonth = startDate.month;
auto diffDays = currentDate - startDate;
auto diffYears = diffDays.total!"days"().to!int / 365;
return currentMonth >= startMonth && currentDay >= startDay ? 
diffYears : diffYears - 1;

}

int getDiffYears2(string date) {
auto now  = cast(Date)Clock.currTime();
auto from = Date.fromISOExtString(date);
auto dy = now.year-from.year;
auto dm = (from.month-now.month);
auto dd = (dm == 0 && from.day>now.day);
return dy - 1 * (dm > 0 || dd);
}

void main(){
writeln("2001-02-09 is ", getDiffYears("2001-02-09"));
writeln("2001-02-10 is ", getDiffYears("2001-02-10"));
writeln("2001-02-11 is ", getDiffYears("2001-02-11"));
writeln("2001-03-01 is ", getDiffYears("2001-03-01"));
writeln("");
writeln("2001-02-09 is ", getDiffYears2("2001-02-09"));
writeln("2001-02-10 is ", getDiffYears2("2001-02-10"));
writeln("2001-02-11 is ", getDiffYears2("2001-02-11"));
writeln("2001-03-01 is ", getDiffYears2("2001-03-01"));
}

Output:

2001-02-09 is 23
2001-02-10 is 23
2001-02-11 is 22
2001-03-01 is 21

2001-02-09 is 23
2001-02-10 is 23
2001-02-11 is 22
2001-03-01 is 22

Matheus.


Re: Would you recommend TDPL today?

2024-01-16 Thread matheus via Digitalmars-d-learn

On Tuesday, 16 January 2024 at 02:25:32 UTC, matheus wrote:

...


I'll reply to myself but I just would like to say thanks to 
Jonathan M Davis and Mike Shah.


I started with TDPL but I'll fill my knowledge with the other 
suggestions you gave me.


Thanks again,

Matheus.


Would you recommend TDPL today?

2024-01-15 Thread matheus via Digitalmars-d-learn
Hi, I'm mostly a lurker in these Forums but sometimes I post here 
and there, my first language was C and I still use today together 
with my own library (A Helper) which is like a poor version of 
STB (https://github.com/nothings/stb).


I usually use D language sometimes as C on steroids, using AA and 
GC and some other features, but I never entered in this realm 
very deeply.


I always wanted to dive in and I always postponed, but I decided 
to go a littler deeper, and I thought about going with The D 
Programming Language, but as I see it is from 2010, and I wonder 
if is it a good resource to go currently?


I don't care about the age of the book, since I learned C in late 
90's with Kernighan and Ritchie "The C Programming Language", but 
at time C was "stable", now I think D maybe has evolved much more 
in these 14 years, so I'm a bit on the fence.


Any thoughts or recommendations?

Thanks,

Matheus.


Re: Doubt about Struct and members

2024-01-08 Thread matheus via Digitalmars-d-learn

On Monday, 8 January 2024 at 17:56:19 UTC, H. S. Teoh wrote:

...
It's not recommended to use initializers to initialize mutable 
array-valued members, because it probably does not do what you 
think it does.  What the above code does is to store the array 
["ABC"] somewhere in the program's pre-initialized data segment 
and set s to point to that by default. It does NOT allocated a 
new array literal every time you create a new instance of S; 
every instance of S will *share* the same array value unless 
you reassign it.  As such, altering the contents array may 
cause the new contents to show up in other instances of S.


This behaviour is generally harmless if your array is 
immutable. In fact, it saves space in your executable by 
reusing the same data for multiple instances of s. It also 
avoids repeated GC allocations at runtime.

...


First of all thanks for replying,

Yes I understood the behavior since I even looked the code 
generated: https://godbolt.org/z/xnsbern9f


=]

Maybe my question was poorly written (I'm ESL), but you answered 
in the other Topic:


"(Whether the current behaviour should be changed is up for 
debate, though. This definitely isn't the first time users have 
run into this. In fact just today somebody else asked the same 
question on D.learn. So it's definitely in the territory of 
"does not do the expected thing", which is an indication that 
the default behaviour was poorly chosen.)"


I was in doubt about if this was intended or not... and it seems 
the case.


I'm not saying it is wrong by any means, I just found a bit 
tricky based on the two ways it could change the value pointed by 
the address and/or the address of the member itself.


Again thanks,

Matheus.


Doubt about Struct and members

2024-01-08 Thread matheus via Digitalmars-d-learn

Hi,

I was doing some tests and this code:

import std;

struct S{
string[] s = ["ABC"];
int i = 123;
}

void foo(bool b, string str){
S t1;

writeln("t1.s: ", t1.s, ", t1.s.ptr: ", t1.s.ptr, " t1.i: ", 
t1.i);


if(b){
t1.s[0] = str;
}else{
t1.s = [str];
}

t1.i = 456;
S t2;

writeln("t1.s: ", t1.s, ", t1.s.ptr: ", t1.s.ptr, " t1.i: ", 
t1.i);


writeln("t2.s: ", t2.s, ", t2.s.ptr: ", t2.s.ptr, " t2.i: ", 
t2.i);

writeln("");
}

void main(){
foo(false, "DEF");
foo(true, "DEF");
foo(false, "XYZ");
}

Outputs:

t1.s: ["ABC"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["DEF"], t1.s.ptr: 7EFC725E6000 t1.i: 456
t2.s: ["ABC"], t2.s.ptr: 56421C6D7010 t2.i: 123

t1.s: ["ABC"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["DEF"], t1.s.ptr: 56421C6D7010 t1.i: 456
t2.s: ["DEF"], t2.s.ptr: 56421C6D7010 t2.i: 123

t1.s: ["DEF"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["XYZ"], t1.s.ptr: 7EFC725E6020 t1.i: 456
t2.s: ["DEF"], t2.s.ptr: 56421C6D7010 t2.i: 123

As you can see:

t1.s = [str];

Just changed generated a new address only for t1.s, on the other 
hand:


t1.s[0] = str;

Changed the value pointed by S.s entirely (The other "instance" 
t2 since points to the same address now has the new value too).


Is this intended?

Matheus.


Re: Advent of Code 2023

2023-12-03 Thread matheus via Digitalmars-d-learn
On Saturday, 2 December 2023 at 13:33:33 UTC, Johannes 
Miesenhardt wrote:
On Friday, 1 December 2023 at 01:01:31 UTC, Siarhei Siamashka 
wrote:
Advent of Code 2023 starts in a few hours from now. I suggest 
to discuss D language solutions here.
But to avoid spoilers, it's best to do this with a 24h delay 
after each puzzle is published.


Day 1 solution

```d
version = Part2;

import std.stdio;
import std.algorithm;
import std.array;
import std.format;
import std.conv;
import std.string;
...


Why do you do multiple imports instead of one import std;?

I means is there any difference in CT?

Matheus.


Re: Weird bug in std.logger? Possible memory corruption

2023-11-01 Thread matheus via Digitalmars-d-learn
On Wednesday, 1 November 2023 at 17:26:42 UTC, Christian Köstlin 
wrote:

...
It's really weird: https://run.dlang.io/is/fIBR2n


Interesting because I wrote a similar test as you did. And that 
increment (Or lack of) called my attention, If I can I'll try and 
take a look at that (std.logger) info() Implementation later 
after work.


Matheus.


Re: Weird bug in std.logger? Possible memory corruption

2023-11-01 Thread matheus via Digitalmars-d-learn

On Tuesday, 31 October 2023 at 21:19:34 UTC, Arafel wrote:

...

Assigning the value to a variable works as expected:

```d
import std.logger : info;

void main() {
auto s = foo();
info(s);
}

auto foo() {
info("In foo");
return "Hello, world.";
}
```
...


Unless you do:

string s;
info(s=foo());

I think this is a bug, or at least very weird behavior.

Matheus.


Re: Want to try out string interpolation in D?

2023-10-23 Thread matheus via Digitalmars-d-learn

On Friday, 20 October 2023 at 16:41:40 UTC, Imperatorn wrote:

Here's a script to get you started
...
Now try string interpolation:

```d
import std.stdio;

void main()
{
string name = "Johan";
int age = 37;
int iq = 8001;
int coffees = 1000;

writeln(i"Your name is $name and you're $age years old");
	writeln(i"You drink $coffees cups a day and it gives you 
$(coffees + iq) IQ");

}
```

Output:
```
Your name is Johan and you're 37 years old
You drink 1000 cups a day and it gives you 9001 IQ
```


First of all thanks for writing this.

Well this seems pretty nice... What DIP number is this? - I'd 
like to read why it was rejected.


Matheus.


Re: Indenting standards religions K, whitesmiths etc

2023-05-31 Thread matheus via Digitalmars-d-learn

On Wednesday, 31 May 2023 at 16:24:38 UTC, Cecil Ward wrote:

...
So my question: would I get lynched for the following? (below)
...


I don't know nothing about all this but looking your example 
code, I write and I'd prefer to read something like this (Editing 
your own code):



pure nothrow etc T foo(T, T2)(in T param x,in T2 param y)
if (template-qualification-whatever) in {
static assert(…);
}
out (ret){
…
assert(test ret);
}do{
   blah
   if (test) {
  if-body
  …
   }
   back to main block
   …
   …
}

Matheus.


Re: Any working REPL program on windows? DREPL doesn't compile

2023-03-23 Thread matheus via Digitalmars-d-learn

On Thursday, 23 March 2023 at 09:39:40 UTC, John Xu wrote:
Anybody know any working REPL program? I failed to find a 
working one.


https://github.com/dlang-community/drepl
can't compile on my Windows 10, dub reports:
...


According to their Readme:


Supported OS


Works on any OS with full shared library support by DMD 
(currently linux, OSX, and FreeBSD).


Matheus.


Re: Need some technical help an object oriented wrapper I am creating for bindbc.sfml

2023-01-26 Thread matheus via Digitalmars-d-learn
On Tuesday, 24 January 2023 at 03:42:34 UTC, thebluepandabear 
wrote:

... if not please tell me and I will remove this...


How you would do that?

Matheus.


Re: Coding Challenges - Dlang or Generic

2023-01-18 Thread matheus via Digitalmars-d-learn

On Wednesday, 18 January 2023 at 04:51:11 UTC, Salih Dincer wrote:

On Tuesday, 17 January 2023 at 21:50:06 UTC, matheus wrote:
Have you compared the timings between this way (With ranges) 
and a normal way (Without ranges)?


Of course it is possible to speed it up.  However, even as it 
is, it is enough to see the power of intervals.  I would argue 
that you'll get fast results even with DMD Compiler!


```d
...


Well I'll need to check this, because your version is slightly 
different than mine and this one 
(https://github.com/quickfur/dcal/blob/master/dcal.d), It prints 
only one column. I'll change mine to do this and compare, I can't 
do this right now because I'm at work.


But unfortunately I can't use xTest = 1200 on these online 
compilers, only 10 or they will stop.


Could you please run your version vs mine (Changing to print one 
column, line 70: draw_year(2023,1); ) and tell us the result?


Matheus.


Re: Coding Challenges - Dlang or Generic

2023-01-18 Thread matheus via Digitalmars-d-learn
On Wednesday, 18 January 2023 at 01:05:58 UTC, Siarhei Siamashka 
wrote:

On Tuesday, 17 January 2023 at 23:27:03 UTC, matheus wrote:
I ran in two sites: https://onecompiler.com/d and then 
https://godbolt.org/, with the latter I set LDC with -O2.


My version (Source in the end) ran about 2x faster than the 
version with ranges.


Well, the use of ranges is not the only difference.
...


What are the other differences?

Just remember what I said above:

I ran my version against the one with ranges (From: 
https://github.com/quickfur/dcal/blob/master/dcal.d), and I 
modified to just print the calendar for some year.


Again I ran both versions with/without ranges only generating and 
printing the months.


Matheus.


Re: Coding Challenges - Dlang or Generic

2023-01-17 Thread matheus via Digitalmars-d-learn
On Tuesday, 17 January 2023 at 23:08:19 UTC, Siarhei Siamashka 
wrote:

On Tuesday, 17 January 2023 at 21:50:06 UTC, matheus wrote:
Question: Have you compared the timings between this way (With 
ranges) and a normal way (Without ranges)?


If you are intensively using ranges, UFCS or the other 
convenient high level language features, then the compiler 
choice does matter a lot. And only LDC compiler is able to 
produce fast binaries from such source code.

...


I ran in two sites: https://onecompiler.com/d and then 
https://godbolt.org/, with the latter I set LDC with -O2.


My version (Source in the end) ran about 2x faster than the 
version with ranges.



...

I'm using D Online Compiler from different platforms but 
unfortunately I can't loop too much because they don't accept, 
but anyway a normal version runs almost twice faster than this 
version (With ranges).


Can you try to run the following diagnostics program on this D 
Online Compiler platform? 
https://gist.github.com/ssvb/5c926ed9bc755900fdaac3b71a0f7cfd


https://onecompiler.com/d/3yv7t9ap9

Gives me:

HelloWorld.d(43): Error: undefined identifier `volatileStore`
HelloWorld.d(44): Error: undefined identifier `volatileLoad`




If you like I could send or post here a version without ranges 
to try out.


Please post it. This is interesting.


Like I said above I ran my version against the one with ranges 
(From: https://github.com/quickfur/dcal/blob/master/dcal.d), and 
I modified to just print the calendar for some year.


With godbolt.org LDC -O2 my version ran 2x faster, and here is 
the source:


import std.stdio, std.string, std.conv, std.range, std.datetime;
import std.datetime.stopwatch : benchmark, StopWatch;

void draw_months(int year ,int month, int columns){
  int i;

  if(month>12){return;}

  auto columspace = " ".replicate(columns);

  write("\n");
  for(i=0;i12){break;}
write("   " ~ " ".replicate(11*(i>0))  ~ 
columspace,capitalize(to!string(Date(year,month+i,1).month)));

  }

  write("\n");
  auto m = new string[][](columns);
  for(int j=0;j12){return;}
for(i=1;i<8;++i){
write(to!string(Date(1899,1,i).dayOfWeek)[0..2], " ");
}

int c = DW[to!string(Date(year,month+j,1).dayOfWeek)];
auto dm = Date(2023,month+j,1).daysInMonth;

for(i=0;i

Re: Coding Challenges - Dlang or Generic

2023-01-17 Thread matheus via Digitalmars-d-learn

On Friday, 13 January 2023 at 21:12:17 UTC, Salih Dincer wrote:

On Friday, 13 January 2023 at 18:59:01 UTC, matheus wrote:

Unfortunately it's not working for me


Yeah, it was an old development version. I also implemented 
another version the same day:


* [Nested 
Class](https://forum.dlang.org/thread/vkjhkftvyprsivozy...@forum.dlang.org)
* [Only One 
Struct](https://forum.dlang.org/post/thxvuddjimgswalzo...@forum.dlang.org)


SDB@79

Sory...


No problem. =]

Question: Have you compared the timings between this way (With 
ranges) and a normal way (Without ranges)?


I'm using D Online Compiler from different platforms but 
unfortunately I can't loop too much because they don't accept, 
but anyway a normal version runs almost twice faster than this 
version (With ranges).


If you like I could send or post here a version without ranges to 
try out.


Matheus.


Re: How to access private variable of outer class from an inner struct

2023-01-15 Thread matheus via Digitalmars-d-learn
On Sunday, 15 January 2023 at 12:44:51 UTC, thebluepandabear 
wrote:

...
How will the variable `outer` become the reference to the 
current `X` object (if that makes sense?). Does the compiler do 
it automatically?


I think you'll need to do this:

class X {
private int num;

struct Y {
X outer;
int fun() { return outer.num; }
}

Y y;
this(){
y = Y(this);
}
}

void main(){
import std.stdio : writeln;
auto x = new X();
x.num = 10;
writeln(x.num);
writeln(x.y.fun());
}

Prints:

10
10

Matheus.


Re: Coding Challenges - Dlang or Generic

2023-01-13 Thread matheus via Digitalmars-d-learn

On Thursday, 12 January 2023 at 19:06:49 UTC, Salih Dincer wrote:

...

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!


...


Hi Salih,

Unfortunately it's not working for me:

.d(79): Error: found `End of File` when expecting `}` following 
compound statement


So I think it's missing a "}" in main, and after I added that, it 
gives:


.d(46): Error: undefined identifier `replicated`, did you mean 
template `replicate(S)(S s, size_t n) if (isDynamicArray!S)`?


Matheus.


Re: Coding Challenges - Dlang or Generic

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

On Tuesday, 10 January 2023 at 22:10:57 UTC, Paul wrote:

...
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?


ITT: https://forum.dlang.org/post/tpjhr3$2ilc$1...@digitalmars.com

drug007 wrote:

[To clarify the 
situation](https://wiki.dlang.org/Component_programming_with_ranges)

(H S Teoh is the author of this article)


Matheus.


Re: Coding Challenges - Dlang or Generic

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

On Tuesday, 10 January 2023 at 11:23:15 UTC, drug007 wrote:

10.01.2023 13:57, matheus пишет:
...
[To clarify the 
situation](https://wiki.dlang.org/Component_programming_with_ranges)

(H S Teoh is the author of this article)


Hmm very interesting (I'm at work and I just gave it a glimpse). 
But since I'm a C programmer who just play with D as hobby I 
would need more time to digest it.


I'll try to read it later.

Matheus.


Re: Coding Challenges - Dlang or Generic

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

On Tuesday, 10 January 2023 at 07:38:31 UTC, Salih Dincer wrote:

On Tuesday, 10 January 2023 at 03:18:54 UTC, matheus wrote:
...`
You don't need validDate.  Because there is daysInMonth:
...


That's really better. thanks for the info.

Matheus.


Re: Coding Challenges - Dlang or Generic

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

On Tuesday, 10 January 2023 at 05:21:15 UTC, H. S. Teoh wrote:


Printing it in this format is trivial, and not very 
interesting.  The interest in the challenge is to lay it out 
like I posted, side-by-side,...


Like I said I did it over D online compiler which unfortunately I 
couldn't validate the output because it "wraps" the text, and the 
font wasn't monospace.


But It just a case of changing the loop in a way to print 3 
groups of months.


... and to do so in a way that the code is clean, maintainable, 
and consists of reusable components. ...


Talking about modularity and reusable components, I really think 
it depends, because if that's was really the case, then I would 
think of using the OS functions to move the cursor around (If 
console/terminal) to print a given month in some location or side 
by side until reach some horizontal limit (Terminal), then it 
could be 1 column only (Like I did), 2, 3 and maybe 4 columns if 
the terminal/resolution permit, and for that I would use ARSD. :]


But I think this would be too much for this kind of thing writing 
on online compiler.



... That's where the challenge lies.


To be honest when I saw your proposal, I really thought that the 
real challenge would be to write my own algo to handle the date, 
and I was pretty sure after posting above, you would say that, 
but not about the layout or printing in groups. =]


Matheus.


Re: Coding Challenges - Dlang or Generic

2023-01-09 Thread matheus 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):

...


The layout isn't like yours, I wrote this using a D Online 
compiler and I'm very sleepy right now:


import std.stdio, std.string, std.conv, std.datetime;

bool validDate(int y,int m,int d){
   try{
   Date(y,m,d);
   return true;
   }catch(Exception e){}
   return false;
}

void main(){
int[string] dow;
int i, y = 2023, m = 1, d = 1;

for(i=1;i<8;++i){
dow[to!string(Date(1899,1,i).dayOfWeek)]=i;
}

for(m=1;m<13;++m){

write("\n\n\t\t",capitalize(to!string(Date(y,m,1).month)),"\n");


for(i=1;i<8;++i){
write(to!string(Date(1899,1,i).dayOfWeek)[0..2], " ");
}

writeln();
int c = dow[to!string(Date(y,m,1).dayOfWeek)];

for(i=1;i

Re: Why does this code only work with `std.conv.to` whilst not with `cast`?

2023-01-08 Thread matheus via Digitalmars-d-learn

On Sunday, 8 January 2023 at 12:39:37 UTC, thebluepandabear wrote:

...
The `foreach` worked for that case since `bark` is a method of 
`IDog`. `update` is not so a conversion to `Button[]` is needed.




In that case, you could do a casting like this:

import std.stdio, std.conv;

interface IDog {
void bark();
}

class Dog: IDog{
string s;
this(string _s){s = _s;}
void bark(){writeln(s);}
void update(string _s){ s ~= " - " ~ _s; }
}

class List{
IDog[] dogs;
void add(T)(T d){ dogs ~= d;  }
}

void main(){
auto d1 = new Dog("meaw!");
auto d2 = new Dog("wof!");
auto l = new List();
l.add(d1);
l.add(d2);

foreach(i,d; l.dogs){ // I'm using 'i' just to show each 
update.

(cast(Dog)d).update(to!string(i));
d.bark();
}
}

Prints:

meaw! - 0
wof! - 1

Matheus.


Re: Why does this code only work with `std.conv.to` whilst not with `cast`?

2023-01-08 Thread matheus via Digitalmars-d-learn

On Sunday, 8 January 2023 at 11:29:10 UTC, thebluepandabear wrote:

...


There is an explanation here: 
https://forum.dlang.org/post/tqukutfzeaxedunuv...@forum.dlang.org


But in any case I'd like to point it out that I think you could 
do that foreach without casting or std.conv by just omitting the 
type of the variable you're iterating:


import std.stdio, std.conv;

interface IDog {
void bark();
}

class Dog: IDog{
string s;
this(string _s){s = _s;}
void bark(){writeln(s);}
}

class List{
IDog[] dogs;
void add(T)(T d){ dogs ~= d;  }
}

void main(){
auto d1 = new Dog("meaw!");
auto d2 = new Dog("wof!");
auto l = new List();
l.add(d1);
l.add(d2);

foreach(d; l.dogs){ // No type informed for "d"
d.bark();
}
}

Prints:

meaw!
wof!

Matheus.


Re: Address of a class object

2023-01-01 Thread matheus via Digitalmars-d-learn

On Sunday, 1 January 2023 at 09:01:24 UTC, Paul wrote:

...
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?


Because MyClass01 and MyClass02 are pointers and in your case 
they differ 4 bytes each other.


Now you could do this:

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
MyClass MyClassO1;
MyClass MyClassO2;
writeln("\n",,"\t",);
writeln("\n",&(MyClassO1.c),"\t",&(MyClassO2.c));
MyClassO1 = new MyClass();
MyClassO2 = new MyClass();
writeln("\n",,"\t",);
writeln("\n",&(MyClassO1.c),"\t",&(MyClassO2.c));
}

In this machine it will print:

 Size  Alignment  Type
=
  32   8  MyClass

7FFD890C64107FFD890C6418 <-  
10	10   <- Note here  [&(MyClassO1.c), 
&(MyClassO2.c)]

7FFD890C64107FFD890C6418 <-   (Same address)
7FD0435D8010	7FD0435D8030 <- Now after instantiation! 
[&(MyClassO1.c), &(MyClassO2.c)]


Finally as you can see I changed your:

class MyClass {char c;}

to:

class MyClass {char[16] c;}

Because from char[1] to char[16] it will keep the address 
difference for [&(MyClassO1.c), &(MyClassO2.c)] by 0x20 (32):


7FD0435D80107FD0435D8030

If I change to char[17]

The difference goes up from 0x20 (32) to 0x30 (48), and keeps 
that way until char[32]:


7FD0435D80107FD0435D8040

char[33] will increase again by 16 bytes and so on.

Matheus.


Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 22:02:41 UTC, Ali Çehreli wrote:

On 12/30/22 13:54, matheus wrote:

> But yes I think it will generate a copy (mutable) based on
this test:

In this case it does copy but in the case of dchar[] to 
dchar[], there will be no copy. Similarly, there is no copy 
from immutable to immutable.


Very interesting I did some testing and you are right. So better 
to stick with .dup!


Thanks for the info,

Matheus.



Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 15:28:05 UTC, Salih Dincer wrote:
... In this case, std.conv.to can be used for mutable dchars, 
right? For example, is this solution the right approach?


```d
auto toDchar(S)(inout S str) {
  import std.conv : to;
  return str.to!(dchar[]);
}

void main() {
  auto str3 = "ÜÇ ON "d;
  auto str4 = "BİR İKİ BEŞ "d.dup;
  auto str5 = "DÖRT ALTI YEDİ ".toDchar;

  //str5.fun(5);
}
```


Unfortunately I can't say because I'm not a skilled D programmer, 
I use mostly as a C on steroids.


But yes I think it will generate a copy (mutable) based on this 
test:


void main(){
import std.stdio;
import std.conv;

auto str1 = "BİR İKİ BEŞ ";
auto str2 = str1;
auto str3 = str2.to!(dchar[]);

writeln(str1, ", ", str1.ptr);
writeln(str2, ", ", str2.ptr);
writeln(str3, ", ", str3.ptr);
str3[0] = 'A';
writeln(str3, ", ", str3.ptr);

}

It prints:

BİR İKİ BEŞ , 5641226D8200
BİR İKİ BEŞ , 5641226D8200
BİR İKİ BEŞ , 7FB466EAE000
AİR İKİ BEŞ , 7FB466EAE000

So for str2 = str1 it is just a case of passing the reference, 
and both are pointing to the same address, while in the case of: 
"str3 = str2.to!(dchar[]);", the address is different, and 
accepts changing its content (str3[0] = 'A').


In the docs: https://dlang.org/phobos/std_conv.html#to

"String to string conversion works for any two string types 
having (char, wchar, dchar) character widths and any combination 
of qualifiers (mutable, const, or immutable)."


But I couldn't find if the target will be mutable, but I think it 
will be, unless explicitly otherwise with a cast I believe.


Anyway I would wait and see if someone more skilled could shed a 
light.


Matheus.


Re: dChar Error

2022-12-30 Thread matheus via Digitalmars-d-learn

On Friday, 30 December 2022 at 10:03:20 UTC, Salih Dincer wrote:

On Friday, 30 December 2022 at 09:29:16 UTC, novice2 wrote:
On Friday, 30 December 2022 at 04:43:48 UTC, Salih Dincer 
wrote:

  ...
  // example one:
  char[] str1 = "cur:€_".dup;
  ...
  // example two:
  dchar[] str2 = cast(dchar[])"cur:€_"d;
  ...
SDB@79


why you use .dup it example one, but not use in example two?

dchar[] str2 = cast(dchar[])"cur:€_"d.dup;


If I do not use .dup in the 1st example and convert as 
cast(char[]), it gives an error. However, in the 2nd example 
using .dup does nothing. It's not working anyway!

...


Are you sure about that?

Because replacing this:

dchar[] str2 = cast(dchar[])"cur:€_"d;

with this:

dchar[] str2 = (cast(dchar[])"cur:€_").dup;

Worked for me:

8: [€_]
[cur:$  _]
6: [€_]
[cur$ _]

A small example of the problem:

import std.stdio;

void main(){
  dchar[] str1 = (cast(dchar[])"cur:€_").dup;
  dchar[] str2 = (cast(dchar[])"cur:€_");

  str1[0] = '1';
  //str2[0] = '1'; // this will give: Error: program killed by 
signal 11

}

Matheus.


Re: How Can i see associative array implement , is where has pseudocode write in Dlang?

2022-12-29 Thread matheus via Digitalmars-d-learn

On Thursday, 29 December 2022 at 11:24:38 UTC, lil wrote:
How Can i see associative array  implement , is where  has 
pseudocode write in Dlang?


Maybe this will help: 
https://github.com/dlang/phobos/blob/master/std/array.d


Matheus.


Re: Thinking about the difference between fixed and 'dynamic' arrays.

2022-11-29 Thread matheus via Digitalmars-d-learn

On Tuesday, 29 November 2022 at 23:25:46 UTC, DLearner wrote:
On Tuesday, 29 November 2022 at 19:06:20 UTC, rikki cattermole 
wrote:

[...]

Please see the following example:
...


I think this was discussed before a few weeks ago here (But I 
don't remember the thread), and this is a design choice, for 
example this:


VarArr2 = VarArr1;

VarArr2 is just pointing to the same address of VarArr1 as you 
can see by:


   writeln(VarArr1.ptr);
   writeln(VarArr2.ptr);

To do what you want, you need to use "dup":

   VarArr2 = VarArr1.dup;

Now it will work as you expect.

I think this is confusing but in the end it's a design choice, 
instead of copy just point, and if you need to copy, you need to 
it explicitly.


Matheus.


Re: Is defining get/set methods for every field overkill?

2022-11-18 Thread matheus via Digitalmars-d-learn

On Friday, 18 November 2022 at 09:42:21 UTC, []() {}() wrote:

...


I think you missed the point of that video very badly.

By the way just a few points from that video:

Around: 2:32 -> "Never ever put in an 'accessor' until it 
actually does something...".


Around: 3:10 -> "If there is an 'accessor' it had better do 
something in there...".


Matheus.


Re: Is defining get/set methods for every field overkill?

2022-11-17 Thread matheus via Digitalmars-d-learn
On Thursday, 17 November 2022 at 04:39:35 UTC, thebluepandabear 
wrote:

...
It's not a lot of code that has been added but if you have a 
class with say 10 different fields, adding getter methods would 
definitely increase the code size by a lot, so what are you 
guys thoughts on this?


Food for thought:

https://yewtu.be/watch?v=_xLgr6Ng4qQ

or

https://www.youtube.com/embed/_xLgr6Ng4qQ

Matheus.


Re: Why am I getting different array size depending where I calling?

2022-11-14 Thread matheus via Digitalmars-d-learn

On Monday, 14 November 2022 at 21:07:42 UTC, Adam D Ruppe wrote:

On Monday, 14 November 2022 at 21:00:38 UTC, matheus wrote:

void[] getFoo(){
writeln(cast(int[])bar);
auto foo = getFoo();
writeln(foo);

Prints:

[1, 0]
[2, 0, 0, 0, 0, 0, 0, 0]

Looking through godbolt.org the ASM generated with both

So why the array generated from getFoo() is 4 times bigger 
than the other?


It isn't. You're casting one to int[] and not casting the 
other, leaving it as void[], which writeln will interpret as 
just raw bytes.


Since an int is 4x bigger than a byte, casting it to int shows 
1/4 the number of ints.


But the actual array is the same.


Oh my, you're absolutely right... I can't believe I missed that.

Thanks Adam,

Matheus.


Why am I getting different array size depending where I calling?

2022-11-14 Thread matheus via Digitalmars-d-learn

Hi all,

Well my doubt is pretty much the title for the snippet below:

import std.stdio;

void[] getFoo(){
   void[] _ = new void[int.sizeof*2];
   (cast(int[])_)[0] = 2;
   return _;
}

void main() {
void[] bar = new void[int.sizeof*2];
(cast(int[])bar)[0] = 1;
writeln(cast(int[])bar);
auto foo = getFoo();
writeln(foo);
return;
}

Prints:

[1, 0]
[2, 0, 0, 0, 0, 0, 0, 0]

Looking through godbolt.org the ASM generated with both

void[] bar = new void[int.sizeof*2];

or

void[] _ = new void[int.sizeof*2];


is the same:

mov rdi, qword ptr [rip + TypeInfo_Av.__init@GOTPCREL]
mov esi, 8
call_d_newarrayT@PLT
mov qword ptr [rbp - 16], 8
mov qword ptr [rbp - 8], rdx


So why the array generated from getFoo() is 4 times bigger than 
the other?


Thanks in advance,

Matheus.


Re: Comparison of two 'dynamic arrays'.

2022-11-13 Thread matheus. via Digitalmars-d-learn

On Sunday, 13 November 2022 at 17:10:23 UTC, DLearner wrote:

...
The slight generalisation shown at bottom also worked.

However, is there a way of avoiding the for-loop?
...


I don't have too much knowledge in D, but I think so. (My main 
language is C).


Well, one way to make things "better" would be creating a 
constructor inside that struct with opCall, something like this:


import std.stdio;

void main() {
   struct test_struct {
  char[] Txt;
  static test_struct[] opCall(test_struct[] e){
auto _ = e.dup;
foreach(i,v; e[0].Txt){
_[0].Txt = e[0].Txt.dup;
}
return _;
}
   }
   test_struct[] A;
   A.length = 1;
   A[0].Txt.length = 1;
   A[0].Txt[0] = 'X';
   writeln(A);
   auto B = test_struct(A);
   writeln(A, B);
   A[0].Txt[0] = 'Y';
   writeln(A, B);
}

There still a loop over there, so let's wait for some advanced 
users to destroy this. :)


Matheus.


Re: Comparison of two 'dynamic arrays'.

2022-11-13 Thread matheus. via Digitalmars-d-learn

On Sunday, 13 November 2022 at 15:45:40 UTC, DLearner wrote:
On Sunday, 13 November 2022 at 14:39:26 UTC, Siarhei Siamashka 
wrote:

On Sunday, 13 November 2022 at 14:28:45 UTC, DLearner wrote:

Creating a step 1.5:
```
int[] B = A;
```


```D
auto B = A.dup;
```

This will create a copy of A rather than referencing to the 
same buffer in memory.


Tested:

```
void main() {

   import std.stdio;


   struct test_struct {
  char[] Txt;
   }

   test_struct[] A;


   A.length = 1;
   A[0].Txt.length = 1;
   A[0].Txt[0] = 'X';

   writeln(A);


   auto B = A.dup;

   writeln(A, B);

   A[0].Txt[0] = 'Y';

   writeln(A, B);
}

```

Got:
```
[test_struct("X")]
[test_struct("X")][test_struct("X")]
[test_struct("Y")][test_struct("Y")]
```

Expected last line to be Y,X not Y,Y.


You should add the code below after "auto B = A.dup;":

   B[0].Txt = A[0].Txt.dup;

The "Txt" property inside B is still referencing A without the 
above.


Matheus.


Re: What's the correct way of creating an instance of class in D?

2022-11-02 Thread matheus via Digitalmars-d-learn
On Thursday, 3 November 2022 at 04:41:14 UTC, Siarhei Siamashka 
wrote:

...


https://dlang.org/spec/class.html

Matheus.


Re: Is "auto t=T();" not the same as "T t;"?

2022-10-25 Thread matheus via Digitalmars-d-learn

On Tuesday, 25 October 2022 at 20:12:25 UTC, Paul Backus wrote:

On Tuesday, 25 October 2022 at 17:54:16 UTC, Salih Dincer wrote:

On Tuesday, 25 October 2022 at 17:18:35 UTC, Paul Backus wrote:
It's not a bug. They're pointing to the exact same instance 
of `A` in memory:


I don't understand?  So I don't understand why it causes 
problems with dynamic arrays!  So why is there nothing wrong 
with the static array in the example below?


Static arrays are value types. When you copy a static array, 
the copy's data is stored in a separate block of memory from 
the original:


```d
int[1] a = [1];
int[1] b = a;

assert([0] !is [0]); // different memory
```

Dynamic arrays are reference types. When you copy a dynamic 
array, both copies point to the same block of memory:


```d
int[] a = [1];
int[] b = a;

assert([0] is [0]); // same memory
```

In order to create a copy of a static array with its own block 
of memory, separate from the original, you have to use the 
built-in `.dup` method:


```d
int[] a = [1];
int[] b = a.dup;

assert([0] !is [0]); // different memory
```


This is interesting, I understand the point of "reference vs 
copy", and I'm OK with this design choice of, but I wonder in the 
case of newcomers if this is a case the generate more problem 
understanding this rules, like we are having here.


Matheus.


Re: Design question regarding saving changes in the original array and/or returning a new set

2022-10-23 Thread matheus via Digitalmars-d-learn

On Sunday, 23 October 2022 at 17:36:25 UTC, Paul Backus wrote:

On Sunday, 23 October 2022 at 13:32:44 UTC, matheus wrote:

...


You say your idea is "like passing some argument", so why not 
actually pass an argument?


For example:
...


Hi, thanks for the example, and yes I'd like to do that, but I'm 
looking for this "chaining"  things which seems to be some sort 
of pattern these days.


Like I said to Sergey, I think I'll use the library as example, 
except that I think that I'd do the otherwise, calling just 
"sort()" would give a duplicate, and chaining with "save()", 
"inplace()" or whatever name is would sort in place (Caller).


Thanks,

Matheus.




Re: Design question regarding saving changes in the original array and/or returning a new set

2022-10-23 Thread matheus via Digitalmars-d-learn

On Sunday, 23 October 2022 at 16:16:55 UTC, Sergey wrote:

On Sunday, 23 October 2022 at 15:47:27 UTC, matheus wrote:

Hi H. S. Teoh,

I think you misunderstood my question, since English is not my 
first language maybe this was a problem from my part, but 
anyway, I'm not talking about "sort" from main library.


This example was if I had designed my "own version".

Matheus.


Hi, Matheus. I'm not an expert in programming :)
But I believe it should be up to you. How you make your 
function...


Hi, yes I know but I'd like to know what is the most "common way" 
of doing this. I think I'll use the library as example, except 
that I think that I'd do otherwise, calling "sort()" would give a 
duplicate, and chaining with "save()" or "inplace()" would sort 
the caller.


Thanks,

Matheus.


Re: Design question regarding saving changes in the original array and/or returning a new set

2022-10-23 Thread matheus via Digitalmars-d-learn

Hi H. S. Teoh,

I think you misunderstood my question, since English is not my 
first language maybe this was a problem from my part, but anyway, 
I'm not talking about "sort" from main library.


This example was if I had designed my "own version".

Matheus.


Design question regarding saving changes in the original array and/or returning a new set

2022-10-23 Thread matheus via Digitalmars-d-learn

Hi,

I have a design question and I'd like to hear some advice. Let's 
say that I want to create a method to sort an array:


arr.sort(asc);

I think usually this would usually return a new set of that array 
but now sorted.


But If I want to do this in the original, I think I would do this:

arr.sort(asc).save();

The problem with this, it would create a new set and assign/copy 
back to the caller, which would be a waste. So I thought about 
this:


arr.save.sort(asc);

Then save would tell to "sort()" what to do beforehand, like 
passing some argument saying that the sort should be done direct 
in the caller and no copy.


Is this (The latter) an approach you would use? Or there is a 
better way to do this.


By the way in this design I'd like to have both options, return a 
new set and/or change the original.


Thanks in advance,

Matheus.


Re: How do I correctly install packages for use with Visual Studio?

2022-10-16 Thread matheus via Digitalmars-d-learn

On Sunday, 16 October 2022 at 11:09:31 UTC, Decabytes wrote:
I'm trying to set up Visual Studio 2022 with Visual D, and I'm 
running into issues trying to get my project to build 
correctly. It's a double whammy because I've never used Visual 
Studio before (Just an Emacs Guy), but I need to debug my D 
programming and according to the 
[documentation](https://wiki.dlang.org/Debuggers) this is my 
only option on Windows.


I don't know if anything changed significantly, but I used to 
debug on Windows with WinDbg without any IDE.


Maybe this is useful: 
https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools


Matheus.


Re: Doubt about char.min/max == typeid(char)

2022-10-06 Thread matheus via Digitalmars-d-learn

On Friday, 7 October 2022 at 01:02:57 UTC, torhu wrote:

On Friday, 7 October 2022 at 00:13:59 UTC, matheus wrote:

Hi,

Could anyone please tell me why the properties of min/max of a 
char returns a "char type" and not a value as an int?


Well, why whould the highest and lowest values of a type be of 
a different type..?


Hmm well I was thinking the min/max as a range/limits, in this 
case 0 to 255 or it could be -128 to 127 if signed, or in a case 
of a bool: 0 to 1, but now I see it returns the min/max value of 
the type itself, like the latter false/true.


I had my reasoning based on my experience with C.

Thanks,

Matheus.



Doubt about char.min/max == typeid(char)

2022-10-06 Thread matheus via Digitalmars-d-learn

Hi,

Could anyone please tell me why the properties of min/max of a 
char returns a "char type" and not a value as an int?


I just got this while playing around:

void main(){
import std.stdio;
writeln(char.max); // "nothing"
writeln(typeid(char.max)); // "char"
writeln(cast(int)char.max); // 255
}

Thanks in advance,

Matheus.


Re: Why allow initializers of non-static members that allocate?

2022-06-10 Thread matheus via Digitalmars-d-learn

On Saturday, 11 June 2022 at 01:52:58 UTC, Mike Parker wrote:

...
That's because static arrays are allocated as part of the 
instance:

...


Yes I understood the problem, but the naive me was thinking that 
in this example:


struct S{
int[] arr = new int[](5);
}

For some reason this would be transformed as a statically "int[5] 
arr" in the case of structs.


But now I see that's not the case and "arr" points to whatever 
was allocated by "new", and will share across the instances of S 
(Since it's the same address).


... So would you then really want a warning every time you 
initialize a static array field?


Well would this be annoying? Yes, mainly if I already know this, 
but if not, then it would be like a nice to know warning for 
newbies like myself. By the way this would be only in the cases 
that a static array field being initialized with dynamic 
allocation like in the case of struct declaration, not on every 
place.



...
So the question in each case would be, where's the line between 
helpful and annoying?


Well I like to think about this like the "-Wall" flag in C 
compilers, you need to go for it, and you just dismiss the 
warning in such case if you don't agree or know what you're doing.



...
The compiler should be as helpful as it can, but it has to be 
helpful without getting in the way. There's a significant 
amount of learning by trial and error in any programming 
language. So I think there has to be a distinction between 
things like "easy to do by accident even when you know the 
deal"  and "once you learn it, you're unlikely to do it again".


Yes no doubt about it, by the way like I said, I never used this 
form to initialize fields in structs, I always used the "T[n] 
member", but in this particular case the result would have been 
very different from what I expected.


Anyway I'm always lurking around this Forum and learning new 
things.


Thanks,

Matheus.

PS: I'm ESL so sorry for my English mistakes.


Re: Why allow initializers of non-static members that allocate?

2022-06-10 Thread matheus via Digitalmars-d-learn

On Friday, 10 June 2022 at 07:49:43 UTC, Mike Parker wrote:

...
And it *is* documented:

Struct fields are by default initialized to whatever the 
Initializer for the field is, and if none is supplied, to the 
default initializer for the field's type.

The default initializers are evaluated at compile time.


https://dlang.org/spec/struct.html#default_struct_init


Hmm I understand the text but for this intializers I was 
expecting new address with length 5, for example:


import std.stdio;

struct S{
int[] arr = new int[](5);
int[2] arr2;
}

void main(){
S s1, s2;

s2.arr[0] = 42;
writeln(s1.arr[0], " address: ", [0]);
writeln(s2.arr[0], " address: ", [0]);

s2.arr2[0] = 10;
writeln(s1.arr2[0], " address: ", [0]);
writeln(s2.arr2[0], " address: ", [0]);
}

Prints:

42 address: 5586F5BD9CC0
42 address: 5586F5BD9CC0
 0 address: 7FFFC65C7A20
10 address: 7FFFC65C7A40


And as it can be seen: s1.arr and s2.arr shares the same address.

So, in the case of "int[] arr = new int[](5)", an array of length 
5 of type int will be instantiated and its address will be shared 
among whoever instantiates "S" and be pointed and accessed 
through arr.


In the second case, "int[2] arr2", 2 consecutive integer spaces 
in memory will be allocate independently for each "instantiation" 
of "S", so different address.


I never saw this before (I mean I never wrote the first case), 
I'm used to the "int[2] arr2;" way of declaring it, but if I had 
looked this code without knowing this, I'd be certain that s1.arr 
and s2.arr would have different addresses.


This is a bit weird (At least for a newbie like me), I really 
think the compiler should emit an warning about this.


Matheus.


Re: Comparing Exceptions and Errors

2022-06-05 Thread matheus via Digitalmars-d-learn

On Sunday, 5 June 2022 at 15:07:13 UTC, kdevel wrote:

... I would refactor the code:


I really liked this one. The way it solves and at same time 
restrict the "external access" with that struct of (a,b) makes 
the code easier to maintain too.


Glad I keep lurking around this forum.

Matheus.


Re: Compiler switch for integer comparison/promotion to catch a simple error

2022-05-30 Thread matheus via Digitalmars-d-learn

On Monday, 30 May 2022 at 13:15:12 UTC, bauss wrote:

Good luck convincing Walter that this is a mistake :)


I don't think this is a matter of convincing or changing the 
behavior, I think that a flag for this case (If not exist) should 
be added as a warning.


A language where some people use to spread the phrase "D as 
better C" should at least have this as flag/warning too.


Matheus.


Re: Compiler switch for integer comparison/promotion to catch a simple error

2022-05-29 Thread matheus via Digitalmars-d-learn

On Sunday, 29 May 2022 at 01:35:23 UTC, frame wrote:

Is there a compiler switch to catch this kind of error?

```d
ulong v = 1;
writeln(v > -1);
```

IMHO the compiler should bail a warning if it sees a logic 
comparison between signed and unsigned / different integer 
sizes. There is 50% chance that a implicit conversion was not 
intended.


Well I don't know about this, but of course I think (That if not) 
we should have at least a flag like we have with GCC (-Wextra).


Searching about I found in this topic: 
https://forum.dlang.org/post/hhpacodmcibejatqz...@forum.dlang.org


"Good luck adding a warning into DMD. After years there still 
isn't a warning for unsigned/signed comparisons."


This is from 2017, so let's wait for experienced weighting in.

Matheus.


Re: Installing DMD on linux via snap

2022-05-18 Thread matheus via Digitalmars-d-learn

On Wednesday, 18 May 2022 at 15:27:57 UTC, rikki cattermole wrote:

Snap package source: https://github.com/dlang-snaps/dmd.snap/

Hasn't been updated in 3 years.


I see... and even that I found my answer elsewhere, this problem 
was already discussed there: 
https://github.com/dlang-snaps/dmd.snap/issues (GCC isn't part of 
the dependencies).


But there was no further progress.

Matheus.


Installing DMD on linux via snap

2022-05-18 Thread matheus via Digitalmars-d-learn

Hi,

Even my problem is already solved, I'm passing this information 
because I don't know if you are aware.


Yesterday I needed to install DMD on a fresh installed version of 
Linux, so since I was using Xubuntu I decided to use snap.


sudo snap install dmd

Then a warning appeared saying that because some permissions I 
should add --classic, OK I added and the installation proceeded.


So I just ran DMD alone and I got the version and some info, but 
when I tried to compile a simple Hello world to check if 
everything was really fine, I was greeted with this:


cc: No such file or directory
--- errorlevel 255

Looking online I found my answer, this was probably because it 
was missing GCC, then I did:


apt-get install build-essential

And after that it worked, but I wonder... couldn't we get a hint 
about this after or even before installing DMD?


I remember installing other applications and being asked to 
install additional libraries/packages. Couldn't we have the same?


Matheus.


Re: Question on shapes

2022-05-16 Thread matheus via Digitalmars-d-learn

On Tuesday, 17 May 2022 at 04:37:58 UTC, Ali Çehreli wrote:

...
2) If you want to have a shape hierarchy, then you can start by 
defining its interface and implement that interface by concrete 
shape types. Drawing is ordinarily handled by member functions:

...


Hi Ali, I'm not the author but I have a question, in your second 
example, let's say that sometimes it would be required to "draw" 
with some scale factor, so (As a newbie) I would do something 
like this:


interface Shape {
  void draw();
  void draw(float scale);
}

Then in Circle class:

  void draw(float scale) {
writeln("This circle's radius is ", radius*scale);
  }
  void draw(){ draw(1); }

Then in Rectangular class:

  void draw(float scale) {
writefln!"This rectangle's dimensions are 
%sx%s."(width*scale,height*scale);

  }
  void draw(){ draw(1); }


So calling shape.draw() would draw with the original scale, 
otherwise you could call as shape.draw(some_scale);


The problem is these are just 2 shapes and it could be much more, 
so it would required to repeat all this.


In D there would be a better way to do such thing?

Thanks,

Matheus.


Re: What are (were) the most difficult parts of D?

2022-05-11 Thread matheus via Digitalmars-d-learn

On Wednesday, 11 May 2022 at 05:41:35 UTC, Ali Çehreli wrote:
What are you stuck at? What was the most difficult features to 
understand? etc.


To make it more meaningful, what is your experience with other 
languages?


Ali


I don't know if this will be helpful but here it goes, my user 
case is different since I use D as C on steroids.


My first language was C and I have projects in this language 
which I still maintain and my brain is used to it, but depending 
the project I'll use D instead of C to use features like: GC, AA, 
Strings, Modules and maybe Classes if I feel like it, but I don't 
go to far from these and one reason is sometimes in a rich 
language with lots of features like D It gets hard to stay up to 
date.


Now I know they must be useful to many others, but one thing that 
I don't like are the Attributes part, for me there are so many 
and this is a bit overwhelming (Again to me), for example need to 
think about: "@safe, @trusted, @system" while still prototyping 
may be a cumbersome, and if it's giving me trouble I'll just get 
rid of it. :)


Again I should sit and read the documentation or your book again 
but it's hard to keep up-to-date sometimes with work and so on.


By the way I used to program in C# at work too, but I stopped on 
whatever was the version that runs with .Net 4.6, again this is 
another case of language changing or adding so many features that 
I decided not to go on with it, since it's not required where I 
work (Occasionally I write a few batch programs here and there), 
and I'm current doing more database business at the company these 
days,


Sorry for any English mistakes,

Matheus.


Re: Library for image editing and text insertion

2022-04-27 Thread matheus via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 00:03:25 UTC, Adam Ruppe wrote:

...


I know about Adam Ruppe's work, I already used his terminal.d, 
but I think that unfortunately most people don't and I think it 
should be announced more in these parts. For me arsd is for D 
what stb is for C.


I think in the first time running any D compiler, it should blink 
in the terminal in Yellow/Pink or whatever color you like, and 
show some info like: Are you starting a new project any need some 
libs? Do you know about arsd? If not then go to: 
https://github.com/adamdruppe/arsd. :)


matheus.


Re: How to remove all characters from a string, except the integers?

2022-03-04 Thread matheus via Digitalmars-d-learn

On Friday, 4 March 2022 at 21:20:20 UTC, Stanislav Blinov wrote:

On Friday, 4 March 2022 at 19:51:44 UTC, matheus wrote:

OK but there is another problem, I tested your version and 
mine and there is a HUGE difference in speed:



string s, str = "4A0B1de!2C9~6";


Unless I did something wrong (If anything please tell). By the 
way on DMD was worse, it was like 5x slower in your version.


To add to the already-mentioned difference in allocation 
strategies, try replacing the input with e.g. a command-line 
argument. Looping over a literal may be skewing the results.


Interesting and I'll try that way. Thanks.

Matheus.


Re: How to remove all characters from a string, except the integers?

2022-03-04 Thread matheus via Digitalmars-d-learn

On Friday, 4 March 2022 at 20:38:11 UTC, ag0aep6g wrote:

...
The second version involves auto-decoding, which isn't actually 
needed. You can work around it with 
`str.byCodeUnit.filter!...`. On my machine, times become the 
same then.


Typical output:

str: 401296
Tim(ms): 138
Tim(us): 138505

str: 401296
Tim(ms): 137
Tim(us): 137376


That's awesome my timing are pretty much like yours. In fact now 
with "byCodeUnit"  it's faster. :)


Thanks,

Matheus.


Re: How to remove all characters from a string, except the integers?

2022-03-04 Thread matheus via Digitalmars-d-learn

On Friday, 4 March 2022 at 20:33:08 UTC, H. S. Teoh wrote:

On Fri, Mar 04, 2022 at 07:51:44PM +, matheus via ...
I don't pay any attention to DMD when I'm doing anything 
remotely performance-related. Its optimizer is known to be 
suboptimal. :-P


Yes, in fact I usually do my coding/compiling with DMD because is 
faster, then I go for LDC for production and speed.


Matheus.


Re: How to remove all characters from a string, except the integers?

2022-03-04 Thread matheus via Digitalmars-d-learn

On Thursday, 3 March 2022 at 23:46:49 UTC, H. S. Teoh wrote:

...
This version doesn't even allocate extra storage for the 
filtered digits, since no storage is actually needed (each 
digit is spooled directly to the output).


OK but there is another problem, I tested your version and mine 
and there is a HUGE difference in speed:


LDC 1.27.1, with -O2:

import std.datetime.stopwatch;
import std.stdio: write, writeln, writef, writefln;
import std;

void printStrTim(string s,StopWatch sw){
writeln("\nstr: ", s
,"\nTim(ms): ", sw.peek.total!"msecs"
,"\nTim(us): ", sw.peek.total!"usecs"
   );
}

void main(){
auto sw = StopWatch(AutoStart.no);
string s, str = "4A0B1de!2C9~6";
int j;

sw.start();
for(j=0;j<1_000_000;++j){
s="";
foreach(i;str){
(i >= '0' && i <= '9') ? s~=i : null;
}
}
sw.stop();
printStrTim(s,sw);

s = "";
sw.reset();
sw.start();
for(j=0;j<1_000_000;++j){
s="";
s = str.filter!(ch => ch.isDigit).to!string;
}
sw.stop();
printStrTim(s,sw);
}

Prints:

str: 401296
Tim(ms): 306
Tim(us): 306653

str: 401296
Tim(ms): 1112
Tim(us): 1112648

---

Unless I did something wrong (If anything please tell). By the 
way on DMD was worse, it was like 5x slower in your version.


Matheus.


Re: How to remove all characters from a string, except the integers?

2022-03-03 Thread matheus via Digitalmars-d-learn

On Thursday, 3 March 2022 at 21:03:40 UTC, H. S. Teoh wrote:

...

--
void main() {
string s = "blahblah123blehbleh456bluhbluh";
auto result = s.filter!(ch => ch.isDigit).to!int;
assert(result == 123456);
}
--

Problem solved.  Why write 6 lines when 3 will do?


Just because I'm a simple man. :)

I usually program mostly in C and when in D, I go in the same way 
but using features like: GC, strings, AA etc.


Of course your version is a D'ish way of handling things, and I 
can't contest it looks better visually. But if size was problem I 
could have written:


void main(){
string s, str = "4A0B1de!2C9~6";
foreach(i;str){
(i >= '0' && i <= '9') ? s~=i : null;
}
writeln(s);
}

Well still 1 line off, but I goes with my flow. I mean this 
example is a simple one, but usually I can see and understand 
what a code in C is doing (more) easily than D just looking at 
it. Don't even ask about C++, because I gave up. :)


Matheus.

PS: I spotted something on your code, you're converting the 
result to int, this can lead to a overflow depending the values 
in the string.


Re: How to remove all characters from a string, except the integers?

2022-03-03 Thread matheus via Digitalmars-d-learn

On Thursday, 3 March 2022 at 12:14:13 UTC, BoQsc wrote:
I've looked around and it seems using regex is the only closest 
solution.


I'm a simple man who uses D with the old C mentality:

import std.stdio;

void main(){
string s, str = "4A0B1de!2C9~6";
foreach(i;str){
if(i < '0' || i > '9'){ continue; }
s ~= i;
}
writeln("Result: ", s);
}

Result: 401296

Matheus.


Re: https://run.dlang.io/ vs All dmd compilers (2.060 - latest)

2022-02-28 Thread Matheus via Digitalmars-d-learn

On Monday, 28 February 2022 at 19:00:58 UTC, Matheus wrote:

On Monday, 28 February 2022 at 17:49:36 UTC, Mike Parker wrote:

...
Please try again.


Testing.

Matheus.


It worked thanks!

Matheus.


Re: https://run.dlang.io/ vs All dmd compilers (2.060 - latest)

2022-02-28 Thread Matheus via Digitalmars-d-learn

On Monday, 28 February 2022 at 17:49:36 UTC, Mike Parker wrote:

...
Please try again.


Testing.

Matheus.




Re: https://run.dlang.io/ vs All dmd compilers (2.060 - latest)

2022-02-28 Thread Matheus via Digitalmars-d-learn

On Monday, 28 February 2022 at 02:31:57 UTC, Mike Parker wrote:

...


Hey Parker, I think my IP still under surveillance, everytime I 
post I get:


"Your message has been saved, and will be posted after being 
approved by a moderator."


With VPN I can post without problem. Could you please take a look?

Matheus.


Re: https://run.dlang.io/ vs All dmd compilers (2.060 - latest)

2022-02-28 Thread Matheus via Digitalmars-d-learn

On Monday, 28 February 2022 at 08:11:15 UTC, Basile B. wrote:
This was [reported before]. Apparently this would be caused by 
a timeout.


[reported before]: 
https://forum.dlang.org/post/skc2dd$1o52$1...@digitalmars.com


Apparently yes, but I think the return error should be clear to 
avoid guessing.


I've been trying this for 2 weeks, I think there is something 
wrong there.


Matheus.


https://run.dlang.io/ vs All dmd compilers (2.060 - latest)

2022-02-27 Thread Matheus via Digitalmars-d-learn

Hi,

In "https://run.dlang.io; is the "All dmd compilers (2.060 - 
latest)" not working anymore?


Because I always get: "Server error:"

I've been trying for like 2 weeks and I always get this "Server 
Error: " message.


I even tried with this basic example:

void main(){
import std.algorithm, std.stdio;
"Starting program".writeln;
enum a = [ 3, 1, 2, 4, 0 ];
static immutable b = sort(a);
pragma(msg, "Finished compilation: ", b);
}

After one minute I think I get:


rdmd playground.d


Server error:

Thanks,

Matheus.


Re: how to handle very large array?

2022-02-14 Thread Matheus via Digitalmars-d-learn

On Monday, 14 February 2022 at 13:20:45 UTC, MichaelBi wrote:
thanks, you are all correct. i just change the algorithm and 
use the AA, previously using the naïve method...:), now solved 
perfectly. thanks again.


You could have used a normal Int Array for this task too, you're 
dealing with numbers and could go with array of 9 elements 0..8, 
then move data circularly and adding new lives as hit -1.


I pretty sure there is a Mathematical way to solve this, I mean 
without any Arrays, but I didn't bother about it since that even 
my basic JavaScript implementation runs in less than 1ms for 256 
days in an old computer.


Matheus.


Re: Wouldn't the compiler be smart with this shadowing variable?

2021-12-11 Thread Matheus via Digitalmars-d-learn

On Saturday, 11 December 2021 at 01:02:36 UTC, frame wrote:

...
You probably want this:

```d
int j;
for({int i=0; j=0;} i<10; ++i){}
```

Beware, this syntax comes directly from hell


Well this works! :)

I'm just a bit intrigued by your last sentence. Is there anything 
evil this may result or anything that I should be aware of?


Matheus.


Re: Wouldn't the compiler be smart with this shadowing variable?

2021-12-11 Thread Matheus via Digitalmars-d-learn
On Friday, 10 December 2021 at 21:55:17 UTC, Siarhei Siamashka 
wrote:

...
   2. reuse the existing "j" variable.


Yes.

But only one of them is a correct description of what actually 
happens when the compiler processes this code. So it's a good 
thing that the compiler is smart enough to reject ambiguous 
code and prevent humans from making mistakes.


Hmm I see your point. And I just thought in cases like this the 
reuse should be the way, but I can see that this is a small 
snippet and in a big code this may hurt someone.


Matheus.


Wouldn't the compiler be smart with this shadowing variable?

2021-12-10 Thread Matheus via Digitalmars-d-learn

Hi,

Wouldn't the compiler be smart with this shadowing variable, 
example:


void main(){
int j;
for(int i=0,j=0;i<10;++i){}
return;
}

onlineapp.d(3): Error: variable `j` is shadowing variable 
`onlineapp.main.j`


So in the "for loop" shouldn't "i" be declared and "j" just be 
assigned to 0?


I mean this is a bit weird, imagine I have different "for loops" 
and in this situation I'll need to do this:


j=0;
for(int i=0;i<10;++i){}

Otherwise:

for(i=0,j=0;i<10;++i){}

This works, but now "i" variable will be out of the "for loop" 
scope.


Matheus.


Re: How to loop through characters of a string in D language?

2021-12-10 Thread Matheus via Digitalmars-d-learn

On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote:

...
The character I want to skip: `;`


My C way of thinking while using D:

import std;

string stripsemicolons(string input){
char[] s = input.dup;
int j=0;
for(int i=0;i

Re: Without multiples inheritance, how is this done?

2021-05-08 Thread matheus via Digitalmars-d-learn

On Saturday, 8 May 2021 at 18:33:35 UTC, Jack wrote:

...
but the class ExtendFoo and ExtendedBaa  must inherit from Foo 
and Baa, respectively. But how can I make it inherit the 
routines from DRY class too without multiples inheritance? in 
C++ I'd just do:


class ExtendedFoo : DRY, Base { /* ... */ }
class ExtendBaa : DRY, Base { /* ... */ }


What about this model:

class baseFoo{
   // Implement foo stuff
}

class baseFooBar : baseFoo{
   // Implement bar stuff
}

class FooBar : baseFooBar{
   // Do your FooBar thing!
}

Matheus.


Re: Need for speed

2021-04-01 Thread matheus via Digitalmars-d-learn

On Thursday, 1 April 2021 at 19:00:08 UTC, Berni44 wrote:


Try using ldc2 instead of dmd:

```
ldc2 -O3 -release -boundscheck=off -flto=full 
-defaultlib=phobos2-ldc-lto,druntime-ldc-lto speed.d

```

should produce much better results.


Since this is a "Learn" part of the Foruam, be careful with 
"-boundscheck=off".


I mean for this little snippet is OK, but for a other projects 
this my be wrong, and as it says here: 
https://dlang.org/dmd-windows.html#switch-boundscheck


"This option should be used with caution and as a last resort to 
improve performance. Confirm turning off @safe bounds checks is 
worthwhile by benchmarking."


Matheus.


Re: D's Continous Changing

2021-03-03 Thread matheus via Digitalmars-d-learn

On Thursday, 4 March 2021 at 05:44:53 UTC, harakim wrote:

...


Yes it's a problem indeed. I had the same problem and that's 
worse when you don't upgrade very often.


But let me tell something, where I work we have software in C#, 
do you think that upgrading was smoothly with all the tools that 
Microsoft provides?


No it wasn't, and it gets worse with third party components.

So this guy was hired just for that, port a very old code to the 
new framework, and after a month he did, yes it compiled 
alright... but the software didn't work as expected is some 
cases, some controls wasn't acting right and was very unreliable.


Guess what? They are still developing with old framework until 
everything works correctly on the new framework.


Matheus.


Development: Work vs Lazy Programmers... How do you keep sanity?

2020-12-03 Thread matheus via Digitalmars-d-learn

Hi,

I didn't know where to post this and I hope this is a good place.

I'm a lurker in this community and I read a lot of discussions on 
this forum and I think there a lot of smart people around here.


So I'd like to know if any of you work with Lazy or even Dumb 
programmers, and If yes how do you keep your sanity?


Matheus.

PS: Really I'm almost losing mine.


Re: What is the difference between enum and shared immutable?

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

On Thursday, 29 October 2020 at 01:26:38 UTC, Mike Parker wrote:


enum int[] arr = [1,2,3];
someFunc(arr);

This is identical to

someFunc([1,2,3]);

Manifest constants have no address. They are effectively 
aliases for their values.


Hi Mike,

I really didn't know about this.

Thanks for the information,

Matheus.


Re: What is the difference between enum and shared immutable?

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

On Wednesday, 28 October 2020 at 22:07:06 UTC, H. S. Teoh wrote:
... (This is why it's a bad idea to use enum with an array 
literal, because every time it's referenced you get a new copy 
of the array.)

...


Could you please give an example (Snippet) about this?

Matheus.


Re: Is there something I'm not getting here?

2020-10-26 Thread matheus via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 02:21:39 UTC, matheus wrote:
On Tuesday, 27 October 2020 at 01:26:56 UTC, James Blachly 
wrote:

On 10/26/20 9:19 PM, Ruby The Roobster wrote:
Following code doesn't work(it's not the actual code but it 
represents it). Is there some rule about function overrides 
that I don't know about?



...
The error I keep getting no matter what says: Error: Multiple 
Overrides of Same Function. Anybody know what I should do?


It works for me.
...


I think he is referring to this:
...


I mean he may be having a duplicate method in the same class.

Matheus.


Re: Is there something I'm not getting here?

2020-10-26 Thread matheus via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 01:26:56 UTC, James Blachly wrote:

On 10/26/20 9:19 PM, Ruby The Roobster wrote:
Following code doesn't work(it's not the actual code but it 
represents it). Is there some rule about function overrides 
that I don't know about?



...
The error I keep getting no matter what says: Error: Multiple 
Overrides of Same Function. Anybody know what I should do?


It works for me.
...


I think he is referring to this:

import std;

class B{
public override string toString(){
return null;
}

public override string toString(){
return toString(null);
}
}

void main() {
B b = new P();
}

Error: function `B.toString` multiple overrides of same function

You can view: https://www.jdoodle.com/iembed/v0/3rm

Matheus.


Re: Question about: ("1.1").to!int;

2020-10-24 Thread matheus via Digitalmars-d-learn
On Saturday, 24 October 2020 at 04:04:18 UTC, Виталий Фадеев 
wrote:

On Friday, 23 October 2020 at 16:59:06 UTC, matheus wrote:
On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton 
Wakeling wrote:

On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:
Well since the caller is handling a string, shouldn't the 
caller verify the content before any conversion?


What if:
"1.1.1".to!int
?

The algorithm will become more complicated?
Will the speed decrease?


I don't get...

Anyway this should fail, look "1.1" is one thing, "1.1.1" is 
another thing as "1.a" is another thing.


Like I said before I think the behavior should be the same in 
these cases:


(1.1).to!int = 1.
("1.1").to!int = Current is an error and IMO should be 1.

Now for your question:

1.1.1.to!int = Error: found `0.1` when expecting `,`.
"1.1.1".to!int = Should be the same as above.

Matheus.


Re: Question about: ("1.1").to!int;

2020-10-23 Thread matheus via Digitalmars-d-learn
On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton 
Wakeling wrote:

On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:
Since (1.1).to!int = 1, shouldn't the string value 
("1.1").to!int at least try to convert to float/double and 
then to int?


The thing is, that's a great way for hard-to-identify bugs to 
creep into code.  In these cases:


auto a = (1).to!int; // this works
auto b = ("1").to!int;   // this works
auto c = (1.1).to!int;   // this works and c = 1

... then what the programmer wants is unambiguous.  In the 
first case it's just converting int => int.  In the second, 
it's converting from a string that unambiguously represents an 
integer value, to an int.  And in the third, it's converting 
_at programmer request_ from a double to an int (which has a 
well-defined behaviour).


However, if ("1.1").to!int were to work, this would be the `to` 
function making a judgement call on how to handle something 
ambiguous.  And while that judgement call may be acceptable for 
your current use-case, it won't be for others.


I got it everything you said, but like a said previously:

(1.1).to!int vs ("1.1").to!int

One is a decimal literal while the other is a string 
representation of a decimal.


To be honest I think the function is already making a judgment 
call when I do (1.1).to!int and returns 1, I really fail to see 
the difference when is ("1.1").to!int.


I agree with user1234: "The third case is just like `cast(int) 
1.1` it's not _at programmer request_ from my point of view, it's 
just that the `to` template has not be more restrictive than the 
D `cast` expression. `to` should do at least what a `cast` do and 
do more when there's no rule for the two types that are involved."


In particular, if `to` just accepted any string numerical 
representation for conversion to int, how could the caller 
explicitly _exclude_ non-integer input, if that is their 
use-case?


Well since the caller is handling a string, shouldn't the caller 
verify the content before any conversion?


Because a string may contain a integer, decimal representation or 
neither one.


Finally I don't want to make a fuss of it, I just thought it was 
a bit weird but it can be solved easily.


Thanks,

Matheus.


Re: Question about: ("1.1").to!int;

2020-10-23 Thread matheus via Digitalmars-d-learn

On Friday, 23 October 2020 at 08:09:13 UTC, Виталий Фадеев wrote:

On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:

Hi,

import std.stdio, std.conv;
void main(string[ ] args) {
auto a = (1).to!int; // this works
auto b = ("1").to!int;   // this works
auto c = (1.1).to!int;   // this works and c = 1
auto d = ("1.1").to!int; // Doesn't work
}

[...]


1.1 is not int.
"to" works fine.

As solution,... "1.1" should be splitted to lexems: "1", ".", 
"1". Then analyze and then converted to int.


Of course 1.1 it's not an integer, but since (1.1).to!int works I 
thought that ("1.1").to!int should work too.


Matheus.


Question about: ("1.1").to!int;

2020-10-21 Thread matheus via Digitalmars-d-learn

Hi,

import std.stdio, std.conv;
void main(string[ ] args) {
auto a = (1).to!int; // this works
auto b = ("1").to!int;   // this works
auto c = (1.1).to!int;   // this works and c = 1
auto d = ("1.1").to!int; // Doesn't work
}

The forth line gives me:

std.conv.ConvException@/usr/include/dlang/dmd/std/conv.d(1898): 
Unexpected '.' when converting from type string to type int


??:? pure @safe int std.conv.toImpl!(int, 
immutable(char)[]).toImpl(immutable(char)[]) [0x55de76d9b4d7]
??:? pure @safe int 
std.conv.to!(int).to!(immutable(char)[]).to(immutable(char)[]) 
[0x55de76d99a17]

??:? _Dmain [0x55de76d9986e]

Question:

Since (1.1).to!int = 1, shouldn't the string value ("1.1").to!int 
at least try to convert to float/double and then to int?


Because for what I see "to!int" converts from: int,real but in 
case of string only when it is a integer representation?


Matheus.


Re: Skipping or Stepping Through an Array?

2020-10-21 Thread matheus via Digitalmars-d-learn

On Wednesday, 21 October 2020 at 12:06:00 UTC, drug wrote:

There are two other way:
...
// using foreach
foreach (i; 0..a.length)
write(a[i], ", ");
...


Yes you can use foreach, but in this case will not act the way 
the OP wanted. In his for loop example the "i" is incremented by 
2: "i+=2".


So to perform what OP want with foreach it should be:

foreach (i,j;a){
if(i%2==0){ write(j, ", ");}
}

By the way it's possible to set a "step" value for "foreach"?

Matheus.


Re: Compiler is calling `_memset64` in betterC

2020-10-19 Thread matheus via Digitalmars-d-learn
On Sunday, 18 October 2020 at 19:24:28 UTC, Ferhat Kurtulmuş 
wrote:
I plan to start a project in reasonable size, I wonder if I 
should really use betterC... if I encounter a bug like this, 
will I be stuck at it?


The bug report says, it is a dmd specific problem, and LDC, my 
favorite d compiler, works well (tried it).


So the "first party" compiler has a bug while the "third party" 
one works. That's weird.


I would expect the other way around.

Matheus.


Re: Working with pointers/adresses

2020-07-09 Thread matheus via Digitalmars-d-learn

On Thursday, 9 July 2020 at 17:24:33 UTC, matheus wrote:

On Wednesday, 8 July 2020 at 20:33:39 UTC, Paul Backus wrote:

import std.stdio;

void main()
{
int i;
readf("%d\n", i); // read a number
ubyte* p = cast(ubyte*) i; // convert it to a pointer
writeln(*p); // write the data at that address to the 
console

}

Note that this program will almost certainly crash if you try 
to run it, since modern computers do not allow programs to 
read and write arbitrary memory locations.


I wonder if the question was more like intended to display the 
value using pointers, ie:


import std.stdio;

void main(){
int i;
readf("%d\n", i);
int *p = 
writeln(*p);
}

Because accessing arbitrary memory location seems very weird.

Matheus.


Or maybe he wanted to do this:

import std.stdio;

void main(){
int i;
readf("%d\n", i);
ulong address = cast(ulong)
ubyte* p = cast(ubyte*)address;
writeln(*p);
}

Matheus.


Re: Working with pointers/adresses

2020-07-09 Thread matheus via Digitalmars-d-learn

On Wednesday, 8 July 2020 at 20:33:39 UTC, Paul Backus wrote:

import std.stdio;

void main()
{
int i;
readf("%d\n", i); // read a number
ubyte* p = cast(ubyte*) i; // convert it to a pointer
writeln(*p); // write the data at that address to the 
console

}

Note that this program will almost certainly crash if you try 
to run it, since modern computers do not allow programs to read 
and write arbitrary memory locations.


I wonder if the question was more like intended to display the 
value using pointers, ie:


import std.stdio;

void main(){
int i;
readf("%d\n", i);
int *p = 
writeln(*p);
}

Because accessing arbitrary memory location seems very weird.

Matheus.




Re: Privatize a few members to allow messing with them #11353

2020-06-30 Thread matheus via Digitalmars-d-learn

On Tuesday, 30 June 2020 at 20:01:43 UTC, Stanislav Blinov wrote:

On Tuesday, 30 June 2020 at 19:58:05 UTC, matheus wrote:


+loc.linnum = loc.linnum + incrementLoc;

This works because it was declared:

void linnum(uint rhs) { _linnum = rhs; }

Right?


Almost. Given these definitions:

@safe @nogc pure @property
{
const uint linnum() { return _linnum; }
void linnum(uint rhs) { _linnum = rhs; }
}

This:

loc.linnum = loc.linnum + incrementLoc;

is rewritten as:

loc.linnum(loc.linnum() + incrementLoc);


Alright and thanks again.

Matheus.


Re: Privatize a few members to allow messing with them #11353

2020-06-30 Thread matheus via Digitalmars-d-learn

On Tuesday, 30 June 2020 at 19:55:56 UTC, matheus wrote:

On Tuesday, 30 June 2020 at 19:46:35 UTC, Stanislav Blinov

...
@safe @nogc pure @property
{
const uint linnum() { return _linnum; }
const uint charnum() { return _charnum; }
void linnum(uint rhs) { _linnum = rhs; }
void charnum(uint rhs) { _charnum = rhs; }
}

...with which the += won't work (at least this variant, as the 
getter isn't returning ref).


Oh I see now and thanks for the information.


By the way:

+loc.linnum = loc.linnum + incrementLoc;

This works because it was declared:

void linnum(uint rhs) { _linnum = rhs; }

Right?

Matheus.


Re: Privatize a few members to allow messing with them #11353

2020-06-30 Thread matheus via Digitalmars-d-learn

On Tuesday, 30 June 2020 at 19:46:35 UTC, Stanislav Blinov wrote:

On Tuesday, 30 June 2020 at 19:42:57 UTC, matheus wrote:

in this case this was more a style thing than anything else 
right? Or is there something I'm not able to see?


Before the change, linnum and charnum are public variables, one 
can do a += on them. After the change, they become properties 
accessing, as the PR says, private variables:


@safe @nogc pure @property
{
const uint linnum() { return _linnum; }
const uint charnum() { return _charnum; }
void linnum(uint rhs) { _linnum = rhs; }
void charnum(uint rhs) { _charnum = rhs; }
}

...with which the += won't work (at least this variant, as the 
getter isn't returning ref).


Oh I see now and thanks for the information.

Matheus.


Privatize a few members to allow messing with them #11353

2020-06-30 Thread matheus via Digitalmars-d-learn
Hi, I was looking the PR in DMD and I found this one: 
https://github.com/dlang/dmd/pull/11353/


One of the changes was:

-loc.linnum += incrementLoc;
+loc.linnum = loc.linnum + incrementLoc;

I usually do the former and I particularly hate the later, so my 
question is, in this case this was more a style thing than 
anything else right? Or is there something I'm not able to see?


Thanks,

Matheus.


Re: What would be the advantage of using D to port some games?

2020-06-24 Thread matheus via Digitalmars-d-learn

On Wednesday, 24 June 2020 at 19:46:55 UTC, IGotD- wrote:
A previous game implementation in D would be interesting and if 
you do it you are welcome to write your about experiences here. 
It's hard to say what features you would take advantage in D as 
I haven't seen the code in C/C++. However, one thing is clear D 
would be an easy port because it is so close to C/C++. Every 
algorithm can be ported directly without any bigger change. If 
it would Rust you would probably have to rethink some of the 
data structures and it would be more difficult. Another thing 
that is clear is that productivity would be high. With today's 
fast machines and old games you don't have to worry about any 
GC pauses as there is plenty of time for that. You can 
basically use the slow "scripting language" features of D. I 
would expect that D is in the C# ball park in productivity for 
such task.


Thanks for the information. Yes I am thinking about doing it but 
at the same time I wonder if it's worth (technically speaking) 
port those games.


I'll analyze if there's any part that could take the advantage of 
some D features that lacks in C/C++.


Matheus.


Re: What would be the advantage of using D to port some games?

2020-06-24 Thread matheus via Digitalmars-d-learn

On Wednesday, 24 June 2020 at 19:14:48 UTC, IGotD- wrote:

On Wednesday, 24 June 2020 at 18:53:34 UTC, matheus wrote:



What I'd like to know from the experts is: What would be the 
advantage of using D to port such games?




Can you elaborate your question a little bit more. Why would 
you want to port existing game code to another language to 
begin with?


To see how the game could fit/run in D, like people are porting 
some of those games to Rust/Go and so on.



When you mention "advantage", advantage compared to what?


To the original language the game was written. For example taking 
DOOM (Written in C), in D what would be the features that someone 
would use to port this game, like using CTFE to generate SIN/COS 
table would be reasonable?


I'm just looking for a roughly idea of this matter.

Matheus.


  1   2   >