Re: const of AliasSeq is silently ignored

2019-04-08 Thread Ali Çehreli via Digitalmars-d-learn

On 04/08/2019 12:56 PM, Yuxuan Shui wrote:


In this example:

     const(AliasSeq!(int, int)) a;


I would expect that to mean a type list (int, int) that cannot be 
modified, meaning that it is not allowed to change it from (int, int).



     pragma(msg, typeof(a)); // (int, int)


Makes sense to me.

However, there is no syntax that allows mutating an AliasSeq. In other 
words, the following doesn't compile anyway:


  AliasSeq!(int, int) a;
  a ~= AliasSeq!(double);

So, adding const to that construct does not add any meaning but not many 
people would notice it. :)


Ali


Re: Overloads not returning appropriate info. [Field reflunkory]

2019-04-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 6 April 2019 at 12:20:28 UTC, Alex wrote:
 Error: variable 
`std.traits.ParameterDefaults!(foo).Get!1u.Get` only parameters 
or stack based variables can be `inout`


so i think that is a bug in the phobos library

see: 
https://forum.dlang.org/thread/qbqvkcoexxtlvlxob...@forum.dlang.org


Re: Overloads not returning appropriate info. [Field reflunkory]

2019-04-08 Thread Walter Bright via Digitalmars-d-learn

On 4/8/2019 7:39 AM, Alex wrote:
My point is that you are going ape shit over using T.stringof, you posted no 


I mean, half the shit in __traits looks like it could be in std.traits and there 


Please tone down both the aggressiveness and the use of cuss words, and use 
professional demeanor.


Re: Iterate/sort associative array by value?

2019-04-08 Thread Seb via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:04:28 UTC, kdevel wrote:

On Sunday, 7 April 2019 at 17:16:12 UTC, Seb wrote:

---
["a": 1].byPair.array.sort!((a, b) => a.value < 
a.value).release.each!writeln;

---


What's the purpose of .release? The documentation in 
https://dlang.org/phobos/std_range.html#.SortedRange.release is 
rather monosyllabic.


As others have already explained, you'll get the original range 
back (instead of the SortedRange).

Sometimes, this is useful.
The obvious example is assigning back to the original range:

---
import std.experimental.all;
void main()
{
auto arr = ["a": 1].byPair.array;
arr = arr.sort!((a, b) => a.value < a.value);
}
---

https://run.dlang.io/is/8sFxVb

OTOH this works:

---
import std.experimental.all;
void main()
{
auto arr = ["a": 1].byPair.array;
arr = arr.sort!((a, b) => a.value < a.value).release;
}
---
https://run.dlang.io/is/TgXUZj

In the example where I used it, you won't need it.
Sorry for the confusion, but as it's often every now and then 
pretty useful, I thought it is a nice idea to give it more 
spotlight as it's one of the lesser known parts of Phobos.


Re: I really don't understand DUB

2019-04-08 Thread Dennis via Digitalmars-d-learn

On Monday, 8 April 2019 at 19:54:28 UTC, WhatMeWorry wrote:
Now, I've studied the on-line documentation and even walked 
through the code somewhat but I'm not making an headway.


Very relatable. My tips so far are:

- Look for projects in github with a similar structure to yours 
and look at their package files. Want to split up your library in 
sub-components? Look at:

https://github.com/d-gamedev-team/gfm/blob/master/dub.json
or:
https://github.com/AuburnSounds/Dplug/blob/master/dub.json

Want to build a game on Windows without console, with and icon 
and including Dll's?

https://github.com/gecko0307/dagon-demo/blob/master/dub.json

- If you think "okay, my D project is slightly unconventional, 
but I think I can make it work with dub using the right 
configuration / preBuildCommands / targetType none": It's an 
uphill battle, it won't work well (or at all).


- bookmark the package reference 
(https://dub.pm/package-format-json.html), you'll go back to it a 
lot.


(Surely it hurts that I've never been exposed to a library or 
package manager in general)


It shouldn't be this hard to grasp.


Is there some good beginner tutorial that I'm missing?


Nope. I considered writing one, but the prerequisite of that is 
that I understand dub myself. You'll have to do with:


https://dub.pm/getting_started.html
https://dub.pm/advanced_usage.html
https://github.com/dlang/dub/wiki/Cookbook


Re: How to compile and link simple application?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 19:43:11 UTC, Julian wrote:

On Monday, 8 April 2019 at 19:29:33 UTC, 4544fa8d wrote:
It's really not possible to call functions in modules like in 
any other languages? :S


What some other languages do is collect all of those calls into 
an
implicit function that's called before main(). What D does is 
run

that code at compile-time.


Another way, from https://dlang.org/spec/module.html#staticorder

In thisexe.d:

  import std.stdio, std.path, std.file;

  public string root_dir;

  shared static this() {
  root_dir = dirName(thisExePath());
  }

In thisexe_ex.d:

  #! /usr/bin/env rdmd
  import thisexe, std.stdio;

  void main() {
  writeln(root_dir);
  }

does what you'd expect.


const of AliasSeq is silently ignored

2019-04-08 Thread Yuxuan Shui via Digitalmars-d-learn



In this example:

const(AliasSeq!(int, int)) a;
pragma(msg, typeof(a)); // (int, int)

This kind of make sense, since AliasSeq is not a "single" type. 
But silently dropping const seems bad, the compiler should 
probably report an error/warning in this case?


I really don't understand DUB

2019-04-08 Thread WhatMeWorry via Digitalmars-d-learn
I've been using DUB for several years and I've gotten it to work 
generally.  But I've been trying to troubleshoot a DUB issue for 
two days now and I've come to the conclusion, I don't really 
understand DUB and I'm tired of muddling through.  (Surely it 
hurts that I've never been exposed to a library or package 
manager in general)   Now, I've studied the on-line documentation 
and even walked through the code somewhat but I'm not making an 
headway.


Maybe a higher level approach is required. Is there some good 
beginner tutorial that I'm missing?   Ideally, like a gentle walk 
through, for both Windows and POSIX?


Re: Iterate/sort associative array by value?

2019-04-08 Thread Dennis via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:04:28 UTC, kdevel wrote:
What's the purpose of .release? The documentation in 
https://dlang.org/phobos/std_range.html#.SortedRange.release is 
rather monosyllabic.


The sort function returns a SortedRange, which is usually an 
array wrapper with the extra type information that its content is 
sorted, enabling certain algorithms like lowerBound and 
upperBound with help of binary search.


"Ranges whose elements are sorted afford better efficiency with 
certain operations. For this, the assumeSorted function can be 
used to construct a SortedRange from a pre-sorted range. The 
std.algorithm.sorting.sort function also conveniently returns a 
SortedRange. SortedRange objects provide some additional range 
operations that take advantage of the fact that the range is 
sorted."

(https://dlang.org/phobos/std_range.html)

When you release it, you get it back as a normal slice without 
the type information that it is sorted, so you can assign it to 
regular old array variables. As mentioned in the quote, you can 
get it back as sortedRange with assumeSorted.


Re: How to compile and link simple application?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 19:29:33 UTC, 4544fa8d wrote:
It's really not possible to call functions in modules like in 
any other languages? :S


What some other languages do is collect all of those calls into an
implicit function that's called before main(). What D does is run
that code at compile-time. Silly example:

  import std.stdio;

  T twice(T)(T n) { return 2 * n; }

  auto x = twice(5);

  void main() {
  writeln(x);
  }

Take a look at the compiled result: https://godbolt.org/z/8vLsv9

There's a twice() that's compiled in, but if you look at x it's
already the result of a call to twice():

  int example.x:
  .long   10

and the (unoptimized) main just fetches that number to print.



Re: How to compile and link simple application?

2019-04-08 Thread 4544fa8d via Digitalmars-d-learn

On Monday, 8 April 2019 at 19:05:33 UTC, Julian wrote:

Shorter:
  string root_dir() {
  static string cache;
  return cache ? cache : (cache = dirName(thisExePath()));
  }
This might spam readlink() syscalls if they somehow return the


It's really not possible to call functions in modules like in any 
other languages? :S


---
import std.file;
import std.path;
import std.stdio;

//const ROOT_DIR = dirName(thisExePath());
int someInt = 0;
string someString = "sfgsdgdf";
writeln("one");

void main(){
writeln("two");
}
---



Re: How to compile and link simple application?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:54:10 UTC, Julian wrote:

  @property
  string root_dir() {
  static string cache;
  static bool isInit = false;
  if (!isInit) {
  isInit = true;
  cache = dirName(thisExePath());
  }
  return cache;
  }


Shorter:

  string root_dir() {
  static string cache;
  return cache ? cache : (cache = dirName(thisExePath()));
  }

This might spam readlink() syscalls if they somehow return the 
empty string,

but how would that even happen...


Re: How to compile and link simple application?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:47:42 UTC, 4544fa8d wrote:

On Monday, 8 April 2019 at 18:41:00 UTC, Adam D. Ruppe wrote:

Did you put your code inside a main() function?


I want to make constant with path to directory containing 
executable. This line is above main():

-
const ROOT_DIR = dirName(thisExePath());
-

This is not allowed? :O


That would give you dmd's path, if it worked.

This is allowed:

  #! /usr/bin/env rdmd
  import std.stdio, std.path, std.file;

  @property
  string root_dir() {
  static string cache;
  static bool isInit = false;
  if (!isInit) {
  isInit = true;
  cache = dirName(thisExePath());
  }
  return cache;
  }

  void main() {
  writeln(root_dir);
  }



Re: How to compile and link simple application?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:38:58 UTC, 4544fa8d wrote:

Hello,

I have "hello world" application. I imported std.file, executed 
thisExePath() and now I have this error:



dmd -m64 -of=../../bin/manager -release ./src/manager.d
/usr/include/dmd/phobos/std/file.d(3252): Error: readlink 
cannot be interpreted at compile time, because it has no 
available source code
/usr/include/dmd/phobos/std/file.d(3253):called from 
here: delegate () => readlink(linkz.ptr(), & buffer, 2048LU)()
/usr/include/dmd/phobos/std/file.d(3433):called from 
here: readLink("/proc/self/exe")

./src/manager.d(8):called from here: thisExePath()
./src/manager.d(8):called from here: 
dirName(thisExePath())

makefile:2: recipe for target 'all' failed


Whats going on? Why I cant build my executable file?


The error message is telling you that dmd is trying to run 
readlink
at compile-time. But this is probably an extern (C) symbol that 
isn't

resolved except by the linker to some code in libc, which can only
happen after any compile-time computation's done.

Are you trying to get the /proc/self/exe of dmd itself?


Re: How to compile and link simple application?

2019-04-08 Thread 4544fa8d via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:41:00 UTC, Adam D. Ruppe wrote:

Did you put your code inside a main() function?


I want to make constant with path to directory containing 
executable. This line is above main():

-
const ROOT_DIR = dirName(thisExePath());
-

This is not allowed? :O


Re: How to compile and link simple application?

2019-04-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 8 April 2019 at 18:38:58 UTC, 4544fa8d wrote:


Whats going on? Why I cant build my executable file?


Did you put your code inside a main() function?


How to compile and link simple application?

2019-04-08 Thread 4544fa8d via Digitalmars-d-learn

Hello,

I have "hello world" application. I imported std.file, executed 
thisExePath() and now I have this error:



dmd -m64 -of=../../bin/manager -release ./src/manager.d
/usr/include/dmd/phobos/std/file.d(3252): Error: readlink cannot 
be interpreted at compile time, because it has no available 
source code
/usr/include/dmd/phobos/std/file.d(3253):called from 
here: delegate () => readlink(linkz.ptr(), & buffer, 2048LU)()
/usr/include/dmd/phobos/std/file.d(3433):called from 
here: readLink("/proc/self/exe")

./src/manager.d(8):called from here: thisExePath()
./src/manager.d(8):called from here: 
dirName(thisExePath())

makefile:2: recipe for target 'all' failed


Whats going on? Why I cant build my executable file?


Re: Iterate/sort associative array by value?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 17:13:32 UTC, Seb wrote:

On Monday, 8 April 2019 at 08:31:33 UTC, Dennis wrote:

On Monday, 8 April 2019 at 07:53:23 UTC, Robert M. Münch wrote:
Why does DMD not give a hint, that an import from the 
standard lib might be missing? I find these explicit import 
statements very annyoing.


There currently are a few hard-coded import hints for common 
functions:

https://github.com/dlang/dmd/blob/master/src/dmd/imphint.d

But it definitely could be better.


Yeah, it's not too hard to improve this.
A quick start:

https://github.com/dlang/dmd/pull/9576


I can't make an issue yet, but since they're asking for a 
BugZilla issue,
a relevant one would be "published D examples fail without import 
hints".
In the very first chapter of the D Programming Language, library 
changes
result in errors for enforce (which you add) and 
std.algorithm.splitter


The book has an errata but the compiler's the very first thing 
that can
communicate "D has helpful error messages" instead of "maybe I 
should

wait for this language to mature a bit more".

For more comprehensive hints, isn't the documentation generated? 
Maybe,

patch docgen to generate this table as well.


Re: Iterate/sort associative array by value?

2019-04-08 Thread kdevel via Digitalmars-d-learn

On Sunday, 7 April 2019 at 17:16:12 UTC, Seb wrote:

---
["a": 1].byPair.array.sort!((a, b) => a.value < 
a.value).release.each!writeln;

---


What's the purpose of .release? The documentation in 
https://dlang.org/phobos/std_range.html#.SortedRange.release is 
rather monosyllabic.


Re: Iterate/sort associative array by value?

2019-04-08 Thread Seb via Digitalmars-d-learn

On Monday, 8 April 2019 at 08:31:33 UTC, Dennis wrote:

On Monday, 8 April 2019 at 07:53:23 UTC, Robert M. Münch wrote:
Why does DMD not give a hint, that an import from the standard 
lib might be missing? I find these explicit import statements 
very annyoing.


There currently are a few hard-coded import hints for common 
functions:

https://github.com/dlang/dmd/blob/master/src/dmd/imphint.d

But it definitely could be better.


Yeah, it's not too hard to improve this.
A quick start:

https://github.com/dlang/dmd/pull/9576


Re: Templates - What's Up with the template keyword?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:56:46 UTC, Mike Parker wrote:

In the subsequent sections, I show both long and short 
(eponymous) forms of enum and function templates.


Forgot to say...

I'm typing in the examples as I go and so far I haven't been 
lost. Even when you don't come right out and say how to use a 
particular template example, I'm able to fill in the blanks and 
get a complete, working example.





Re: Templates - What's Up with the template keyword?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:56:46 UTC, Mike Parker wrote:


You should have read further along in that chapter :-)


LOL! Actually, after reading Adam's reply, I dug back into your 
book and I'm starting to get a reasonable handle on this. I must 
say, I like the slow-but-steady intro you wrote.


Thanks, Mike. Great book!


Re: Templates - What's Up with the template keyword?

2019-04-08 Thread Mike Parker via Digitalmars-d-learn

On Monday, 8 April 2019 at 12:23:28 UTC, Ron Tarrant wrote:


First, the question...

In Michael Parker's book, "Learning D," (Packt, 2015) on page 
160 he gives an example of a basic template:


template MyTemplate(T)
{
   T val;

   void printVal()
   {
  import std.stdio : writeln;
  writeln("The type is ", typeid(T));
  writeln("The value is ", val);
   }
}

But in "Programming in D," (self, 2009-2018) by Ali Çehreli, 
there's no mention of the 'template' keyword in any of his 
examples.


Has the 'template' keyword been deprecated? Or is it optional?




You should have read further along in that chapter :-) I evolve 
the MyTemplate example through the end of that "Templates as code 
blocks" section to this:


template MyTemplate(T) {
  struct ValWrapper {
T val;
void printVal() {
  import std.stdio : writeln;
  writeln("The type is ", typeid(T));
  writeln("The value is ", val);
}
  }
}

And show that it must be instantiated like this:

void main() {
  MyTemplate!int.ValWrapper vw1;
  MyTemplate!int.ValWrapper vw2;
  vw1.val = 20;
  vw2.val = 30;
  vw1.printVal();
  vw2.printVal();
}

And in the next section, "Struct and class templates", I 
introduce the concept of eponymous templates by rewriting 
MyTemplate like so:


template ValWrapper(T) {
  struct ValWrapper {
T val;
void printVal() {
  writeln("The type is ", typeid(T));
  writeln("The value is ", val);
}
  }
}

And show that it can be instantiated with the shorthand:

ValWrapper!int vw;

And that the template can be refactored to this (since it's 
eponymous):


struct ValWrapper(T) {
  T val;
  void printVal() {
writeln("The type is ", typeid(T));
writeln("The value is ", val);
  }
}

In the subsequent sections, I show both long and short 
(eponymous) forms of enum and function templates.






Re: Cannot link vibe.d sample / optlink error

2019-04-08 Thread Radu via Digitalmars-d-learn

On Monday, 8 April 2019 at 13:42:31 UTC, Michal Minich wrote:

I used dmd 2.085.0 and 2.085.1 on Win 10

I followed sample at
https://vibed.org/blog/posts/a-scalable-chat-room-service-in-d

Just the beginning, where you you should compile hello word web 
app.


command line: "dub"

compilation finishes ok. then it prints "Linking..." and I get 
window message box:


---
Unexpected OPTLINK Termination at EIP=0040F60A
---
EAX=073D EBX=00438C70 ECX=0B2F EDX=038A
ESI=008F EDI=073D1344 EBP=0019FF28 ESP=0019FEE0
First=00402000
---
OK
---

I also tried clean build with dflags -m32mscoff. But then I get 
another kind of errors.


Any help moving forward is appreciated.


Hi there,
Compiling with 2.085.1 on Windows 10 works with `dub 
--arch=x86_mscoff`
LDC 1.15.0 works for x86/x86_64. Tested also on a fresh VMWare 
instance running Windows 7.


You can try running it with `dub --arch=x86_mscoff --verbose` in 
order to get more diagnostic messages for build errors.


Make sure you have "Visual C++ Redistributable for Visual Studio 
2015" installed, it is required to be able to run the produced 
executable, if you don't build it using the Visual Studio command 
line. The reason is that both DMD and LDC will use the MinGW 
`.lib` files, which require a dynamic linked C runtime (static 
linking is permitted only with Visual Studio)


Re: Overloads not returning appropriate info. [Field reflunkory]

2019-04-08 Thread Alex via Digitalmars-d-learn

On Monday, 8 April 2019 at 12:26:28 UTC, Adam D. Ruppe wrote:

On Sunday, 7 April 2019 at 17:42:58 UTC, Alex wrote:
That is blatantly wrong. The code works EXACTLY the same way 
with and without using stringof.


In some cases, yeah. In the general case, no.

Your import hack* is only there because of stringof. Using the 
local symbol, there is no need to import the module. This means 
you avoid name conflicts with local symbols (like I pointed out 
in the linked post) and it has the potential to avoid 
protection violation errors, since you are no longer getting 
the symbol from your module; it is gotten somewhere else, 
ideally from its own module, and passed to you, which is 
allowed even for private or hidden symbols.


It also just makes the code a lot simpler, so there's no more 
need to jump through hoops to debug it.


But I've already said the point of using T.stringof is so that 
one gets what T is and that actually helps debugging. You don't 
think I didn't try using T first? Why would I type extra symbols 
if it work exactly fine the first time?


The reason I added `~T.stringof~` which is 11 more chars than T.` 
was precisely because the code wasn't working and I was trying to 
figure out why. to claim that it's absolutely wrong in all cases 
is ignorant.


I realize that in many cases it is unnecessary and in some cases 
it will break the code(requiring an import because one is not 
using the type but the id which is then hidden)...


But as I said, I did a search and replace that it didn't change 
squat as far as the code. The main issue was using that typeof 
which you didn't catch cause you were too busy trying to make an 
issue out of stringof.


The other issues either remain, even after using your "rule", or 
I had to refactor the code and use different traits(such as the 
one you recommended for fields).



My point is that you are going ape shit over using T.stringof, 
you posted no real reasons why it is absolutely unnecessary yet 
claimed was after I already shown that it has some use.


It's one thing to make a suggestion and say "You know, you don't 
have to use T.stringof since it will function better in general, 
try it without it and see if fixes your problems" rather than 
keep on beating a dead horse.



* 
https://github.com/IncipientDesigns/Dlang_Reflect/blob/master/mReflect.d#L61


I have removed all T.stringof's in the code and I still get 
the exact same errors.


That's the first step. Then, you clean up the hacks that were 
introduced to work around stringof's problems and get a better 
design that actually works, like passing private members from 
one module to another via alias parameters.


I don't know what you are talking bout passing private members 
from one module using alias parameters. There is only one module 
that does the reflection and all the "passing" of private 
parameters are done INSIDE that module.


If you mean that I should pass the initial class as an alias, 
well, I tried that initially and it worked for some things but 
failed for others so went back and forth between using alias and 
types. The problem is because there are issues in D's type system 
and when they create hard to track bug one has to screw with shit 
to figure out what is going on and that introduces dead ends 
which may or may not be modify the design incipiently... which is 
the whole damn reason I'm writing the reflection library in the 
first place... to avoid all these issues  with traits and provide 
a common interface...


I mean, half the shit in __traits looks like it could be in 
std.traits and there is no clear reason why there are two aspects 
of D that do essentially the same thing. Also there are many 
"holes" in traits that require compound solutions(such as filter 
members to specific types) which then creates ugly CT 
code(multiple nested loops).







one could just open the source if there was anything to "hide"


That's not necessarily true, it is possible to have code 
exclude private members. In fact, it is often considered good 
practice to do that for library releases for encapsulation!


I'm not sure what you are talking about here. I assume you mean 
the body, which I'm not talking about. The body is irrelevant. 
You can't even get the body using __traits. I'm talking about if 
the symbol exists, private or not, one can see it in the source 
code since, for it to be marked private it must show up in the 
source. So, "private" does actually hide shit in the source code. 
It may hide the functionality/body/binary code, but marking a 
member private doesn't HIDE anything in the source.




Protection is a runtime thing(except for CTFE).


Protection *only* exists at compile time - at runtime, there's 
zero checks. There's nothing preventing you from passing a 
pointer to a private member, for example.


No, you really are missing the point. Protection is a RUNTIME 
thing. Else one would just make all members public. Protection 
exists at compile 

Re: What Does @ Mean?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:27:11 UTC, JN wrote:

Java uses @ for annotations too. Pascal uses @ for "address 
of", like & in D.


Just one of the many reasons I balked at Java... many MANY 
reasons.


Thanks, JN.


Re: What Does @ Mean?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:19:04 UTC, XavierAP wrote:

On Monday, 8 April 2019 at 11:58:49 UTC, Ron Tarrant wrote:


And while I'm asking, does an underscore have special meaning 
when used either at the beginning or end of a variable name?


In D, @ is used as Adam has explained as a prefix indicating 
attributes (either user-defined ones or, confusingly enough, 
some of the standard ones).


Yup. Confusion. Yup. :)

Of course you should never do this unless you absolutely need 
for interop.


No fear of that. I was just trying to understand the example I 
cited.


For example in D you could have a public property length and a 
private member _length.


This seems like a good practice.

In this case I've seen some other annoying conventions, for 
example private member variables being prefixed with m_


The things I missed by not getting my degree... or by not keeping 
my nose to the grindstone for the last 30-odd years. :)


Thanks, Xavier.


Re: What Does @ Mean?

2019-04-08 Thread JN via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:19:04 UTC, XavierAP wrote:
The only other example of language using @, in an almost but 
not quite completely different way, is C#. It's also a prefix 
that allows you to define names that would collide with 
reserved words, for example string @class = "menu"; Of course 
you should never do this unless you absolutely need for interop.


Java uses @ for annotations too. Pascal uses @ for "address of", 
like & in D.


Re: What Does @ Mean?

2019-04-08 Thread XavierAP via Digitalmars-d-learn

On Monday, 8 April 2019 at 11:58:49 UTC, Ron Tarrant wrote:


And while I'm asking, does an underscore have special meaning 
when used either at the beginning or end of a variable name?


In D, @ is used as Adam has explained as a prefix indicating 
attributes (either user-defined ones or, confusingly enough, some 
of the standard ones).


The only other example of language using @, in an almost but not 
quite completely different way, is C#. It's also a prefix that 
allows you to define names that would collide with reserved 
words, for example string @class = "menu"; Of course you should 
never do this unless you absolutely need for interop.


Underscore prefixes are used in some languages by pure user 
convention mainly for private members (fields), to avoid name 
clashing. For example in D you could have a public property 
length and a private member _length.


Python takes this a step further. Since it supports classes but 
no public/private visibility at all, users and IDEs have convened 
to use (one or two) underscore prefixes to signal members that 
aren't meant to be accessed publicly from outside the class, even 
if there's nothing stopping you (besides auto code completion not 
showing them).


For C and C++ the convention (recognized by the standards) is 
different: names prefixed by any number of underscores are all 
reserved; basically because the global namespace is so badly 
polluted already. In this case I've seen some other annoying 
conventions, for example private member variables being prefixed 
with m_


Re: Iterate/sort associative array by value?

2019-04-08 Thread diniz via Digitalmars-d-learn

Le 07/04/2019 à 19:16, Seb via Digitalmars-d-learn a écrit :

Then you can do:

---
["a": 1].byPair.array.sort!((a, b) => a.value < a.value).release.each!writeln;
---

You'll have a sorted array with key and value props.


That's what I would do: just operating on an array of {k,v} pairs.

--
diniz {la vita e estranj}


Cannot link vibe.d sample / optlink error

2019-04-08 Thread Michal Minich via Digitalmars-d-learn

I used dmd 2.085.0 and 2.085.1 on Win 10

I followed sample at
https://vibed.org/blog/posts/a-scalable-chat-room-service-in-d

Just the beginning, where you you should compile hello word web 
app.


command line: "dub"

compilation finishes ok. then it prints "Linking..." and I get 
window message box:


---
Unexpected OPTLINK Termination at EIP=0040F60A
---
EAX=073D EBX=00438C70 ECX=0B2F EDX=038A
ESI=008F EDI=073D1344 EBP=0019FF28 ESP=0019FEE0
First=00402000
---
OK
---

I also tried clean build with dflags -m32mscoff. But then I get 
another kind of errors.


Any help moving forward is appreciated.


Re: Templates - What's Up with the template keyword?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

On Monday, 8 April 2019 at 12:40:10 UTC, Adam D. Ruppe wrote:

You don't need template keyword for the majority of cases 
because the compiler lets you do shortcuts.

Thanks, Adam. Good to know.


(maybe I am looking at the wrong part of the book, it is hard 
to find the right section/page number online).


My bad. The edition I'm working from was released 2018-10-17 and 
can be found here:


http://ddili.org/ders/d.en/Programming_in_D.pdf

The page number in online PDF viewer is 421 and the example is 
about 1/3 of the way down the page.





Re: What Does @ Mean?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn

Well, that was quick!

Thanks Adam, Kagamin, and Alex.


Re: Templates - What's Up with the template keyword?

2019-04-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 8 April 2019 at 12:23:28 UTC, Ron Tarrant wrote:
But in "Programming in D," (self, 2009-2018) by Ali Çehreli, 
there's no mention of the 'template' keyword in any of his 
examples.


You don't need template keyword for the majority of cases because 
the compiler lets you do shortcuts.


If you write

void foo(T)(int a) {}

the compiler sees that as a shortcut of writing

template foo(T) {
  void foo(int a) {}
}

and does all the necessary expansion for you.

Writing long-form templates is for when you need to do it more 
advanced topics. Like a template is allowed to have several 
members if you write it long-form. You can also use it to force a 
specific strategy like CTFE inside the template (though the 
compiler now has shortcuts for that too, so you don't see it 
written long-form much more in new code).




Point!T getResponse(T : Point!T)(string question)


This looks wrong...

getResponse(T : Point)

should work (and is what I see in the book), but `T : Point!T` is 
different.



So what the colon does is specialize the template - it says "if 
you pass a type matching `Point` (the stuff after the colon), use 
this function instead of the generic function".


The reason `T : Point!T` isn't compiling is that that's saying 
only match a recursive template... and you don't have one of 
those.



You probably are thinking something along the lines of

Point!T getResponse(T : Point!R, R)(string question) {}

(maybe I am looking at the wrong part of the book, it is hard to 
find the right section/page number online). This is one of the 
most advanced template forms which is able to deconstruct other 
templates.


So, if you call that with a

Point!int p;

getResponse!(typeof(p))("my question")

then it will match T as being some kind of `Point!R`... and it 
will take apart the R into its own argument.


So when given Point!int, it will see the part after ! happens to 
be int, and make R == int.


Thus, inside the getResponse function:

T == Point!int
R == int

and you can inspect that and react accordingly. Or you can ignore 
the R and just use the Point. The value here is you could pass 
Point!int or Point!float or Point!whatever all to the one 
function.


(You can also do this if you just use an unrestricted T argument, 
but the Point!R specialization will make the intent more clear in 
documentation and lets you take it apart if you need to know what 
R is.)


Re: Overloads not returning appropriate info. [Field reflunkory]

2019-04-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 7 April 2019 at 17:42:58 UTC, Alex wrote:
That is blatantly wrong. The code works EXACTLY the same way 
with and without using stringof.


In some cases, yeah. In the general case, no.

Your import hack* is only there because of stringof. Using the 
local symbol, there is no need to import the module. This means 
you avoid name conflicts with local symbols (like I pointed out 
in the linked post) and it has the potential to avoid protection 
violation errors, since you are no longer getting the symbol from 
your module; it is gotten somewhere else, ideally from its own 
module, and passed to you, which is allowed even for private or 
hidden symbols.


It also just makes the code a lot simpler, so there's no more 
need to jump through hoops to debug it.


* 
https://github.com/IncipientDesigns/Dlang_Reflect/blob/master/mReflect.d#L61


I have removed all T.stringof's in the code and I still get the 
exact same errors.


That's the first step. Then, you clean up the hacks that were 
introduced to work around stringof's problems and get a better 
design that actually works, like passing private members from one 
module to another via alias parameters.



one could just open the source if there was anything to "hide"


That's not necessarily true, it is possible to have code exclude 
private members. In fact, it is often considered good practice to 
do that for library releases for encapsulation!



Protection is a runtime thing(except for CTFE).


Protection *only* exists at compile time - at runtime, there's 
zero checks. There's nothing preventing you from passing a 
pointer to a private member, for example.


This is why __traits(getMember) fails the same as T.name, but it 
is also the reason why there's hope to cheat here, at least once 
you get a correct foundation laid, by using mixin templates 
and/or passing aliases cross module.


(interestingly, .tupleof does let you bypass privacy protections, 
but only for aggregate members, not for methods.)


Templates - What's Up with the template keyword?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn
I'm digging into templates in an attempt to understand the 
signals-n-slots replacement for the observer pattern, but I've 
got a question I can't seem to find an answer for and an example 
for which I'm unable to solve the error.


First, the question...

In Michael Parker's book, "Learning D," (Packt, 2015) on page 160 
he gives an example of a basic template:


template MyTemplate(T)
{
   T val;

   void printVal()
   {
  import std.stdio : writeln;
  writeln("The type is ", typeid(T));
  writeln("The value is ", val);
   }
}

But in "Programming in D," (self, 2009-2018) by Ali Çehreli, 
there's no mention of the 'template' keyword in any of his 
examples.


Has the 'template' keyword been deprecated? Or is it optional?


And now, my broken code...

In Ali's book (section 64.7, page 401) this example is given:

Point!T getResponse(T : Point!T)(string question)
{
   writefln("%s (Point!%s)", question, T.stringof);
   auto x = getResponse!T(" x");
   auto y = getResponse!T(" y");
   return Point!T(x, y);
}

But I'm having trouble working out how this would be used. Up to 
this point, either the usage case is given or I was able to work 
it out on my own, but this one seems to demand a use case outside 
the scope of what's been covered in the chapter so far and I'm 
lost.


My full code for this example:

-
import std.stdio;
import std.math;
import std.string;

struct Point(T)
{
T x;
T y;

T distanceTo(Point that) const
{
immutable real xDistance = x - that.x;
immutable real yDistance = y - that.y;

		immutable distance = sqrt((xDistance * xDistance) + (yDistance 
* yDistance));


return(cast(T)distance);

} // distanceTo()

} // struct Point


Point!T getResponse(T : Point!T)(string question)
{
writefln("%s (Point!%s)", question, T.stringof);

auto x = getResponse!T(" x");
auto y = getResponse!T(" y");

return(Point!T(x, y));

} // getResponse() Point!T


void main()
{
	auto wayPoint1 = getResponse!Point("Where is the first map 
location?");
	auto wayPoint2 = getResponse!Point("Where is the second map 
location?");


writeln("Distance: ", wayPoint1.distanceTo(wayPoint2));

} // main()

--
(lines 47 & 48) Error: template instance `getResponse!(Point)` 
does not match template declaration getResponse(T : 
Point!T)(string question)


Any help will be very much appreciated.



Re: What Does @ Mean?

2019-04-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 8 April 2019 at 11:58:49 UTC, Ron Tarrant wrote:
Would someone please tell me what an at sign (@) means when 
it's used like this:


bool isLeaf() @property



In that case, it means nothing. We just defined the word to be 
`@property`, with the @ included. So it is just part of the name. 
Same with @safe, @trusted, @system, @nogc, and a few others built 
into the language.


It was arbitrary decided to put the @ in the words so it wouldn't 
conflict with existing variable names like `int safe;`



In some other contexts though, it just indicates to the parser 
that it is a user-defined attribute instead of continuing the 
declaration with a name. In these, it is a prefix to another user 
value. For example:


struct MyCustomAttribute {} // perfectly ordinary struct

@MyCustomAttribute() void func() {}

In that function, the @ before the name MyCustomAttribute tells 
the compiler that it is just an annotation instead of a return 
value or the defined name of the new function.



So, two purposes for the @: it is just part of some built-in 
keywords, and it can indicate you are using a user-define d name 
as an attribute/annotation instead of as a return value, etc.


And while I'm asking, does an underscore have special meaning 
when used either at the beginning or end of a variable name?


Nothing special there, you are allowed to use the _ anywhere in a 
name. Some people use it as a convention on private members, 
unused members, or keyword conflicts (like `body_` so the 
compiler doesn't see it as the keyword `body`).


But it is just a user convention, it doesn't mean anything 
special to the compiler... except:



How about a double underscore?


A leading double underscore is somewhat special. Those are 
allowed in any name, but those are reserved for compiler 
implementation details.


So like `__ctor` is the special name the compiler uses for 
constructors. You can call it (though since this is an internal 
compiler implementation detail you are choosing to exploit, it is 
liable to break at any time) or define stuff with these names to 
do various hacks.


You should avoid __names though since the compiler reserves them 
for its own use.


Re: Pass template parameter into q{} string

2019-04-08 Thread Kagamin via Digitalmars-d-learn

Maybe just use mixin template?

mixin template f(alias values)
{
static foreach(v;values)
mixin("bool " ~ v ~ " = false;");
}
int main()
{
enum string[] a=["a","b"];
mixin f!a;
return 0;
}


Re: What Does @ Mean?

2019-04-08 Thread Kagamin via Digitalmars-d-learn

https://dlang.org/spec/function.html#property-functions


Re: What Does @ Mean?

2019-04-08 Thread Alex via Digitalmars-d-learn

On Monday, 8 April 2019 at 11:58:49 UTC, Ron Tarrant wrote:
This is frustrating and makes me feel like a complete newb. 
Worse, it's impossible to search for. Ever try Googling a 
single character?


The D documentation also doesn't seem to explain the meaning of 
this or any other token. Sure, most of them are obvious, but 
this one eludes me. All I can find is this: 
https://dlang.org/spec/lex.html#tokens


Would someone please tell me what an at sign (@) means when 
it's used like this:


bool isLeaf() @property
{
   return children.length == 0;
}

In fact, I have no idea what @ means anywhere other than in an 
email address. Is this a common thing in contemporary languages?


And while I'm asking, does an underscore have special meaning 
when used either at the beginning or end of a variable name?


How about a double underscore?

I know underscores are sort of left over from C, but do these 
characters have special meaning in D or are they simply a 
convention... like T in a template definition?


Some of the attributes in D go with an "@".

https://forum.dlang.org/post/fiwfcsqmjsndcjixi...@forum.dlang.org
https://wiki.dlang.org/Language_Designs_Explained
https://dlang.org/spec/attribute.html


Re: D threading and shared variables

2019-04-08 Thread Kagamin via Digitalmars-d-learn

On Sunday, 7 April 2019 at 14:49:20 UTC, Archie Allison wrote:
The codebase is a reasonable size so too big (and proprietary) 
to share.


You can reduce it to a minimal example that doesn't work. Static 
variables are thread local by default in D unless they are marked 
as shared or __gshared.


What Does @ Mean?

2019-04-08 Thread Ron Tarrant via Digitalmars-d-learn
This is frustrating and makes me feel like a complete newb. 
Worse, it's impossible to search for. Ever try Googling a single 
character?


The D documentation also doesn't seem to explain the meaning of 
this or any other token. Sure, most of them are obvious, but this 
one eludes me. All I can find is this: 
https://dlang.org/spec/lex.html#tokens


Would someone please tell me what an at sign (@) means when it's 
used like this:


bool isLeaf() @property
{
   return children.length == 0;
}

In fact, I have no idea what @ means anywhere other than in an 
email address. Is this a common thing in contemporary languages?


And while I'm asking, does an underscore have special meaning 
when used either at the beginning or end of a variable name?


How about a double underscore?

I know underscores are sort of left over from C, but do these 
characters have special meaning in D or are they simply a 
convention... like T in a template definition?





Re: Iterate/sort associative array by value?

2019-04-08 Thread Dennis via Digitalmars-d-learn

On Monday, 8 April 2019 at 07:53:23 UTC, Robert M. Münch wrote:
Why does DMD not give a hint, that an import from the standard 
lib might be missing? I find these explicit import statements 
very annyoing.


There currently are a few hard-coded import hints for common 
functions:

https://github.com/dlang/dmd/blob/master/src/dmd/imphint.d

But it definitely could be better.

As Sebastian said, you can do `import std.experimental.all;` or 
from version 2.086 `import std;` to import the entire standard 
library.


If dmd as a library pans out, a language server might 
automatically suggest imports for unresolved symbols like common 
Java and C# IDEs do.


Re: Iterate/sort associative array by value?

2019-04-08 Thread Julian via Digitalmars-d-learn

On Monday, 8 April 2019 at 07:53:23 UTC, Robert M. Münch wrote:

On 2019-04-07 19:28:02 +, Dennis said:


Did you import it? import std.algorithm;


:-/ of course not...

Why does DMD not give a hint, that an import from the standard 
lib might be missing?


It does do this, so the question should be: why aren't its 
warnings

more extensive?

Example:

  void main() {
  writeln("Hello, world!");
  }

Fails to compile with this error:

  ./missing.d(4): Error: writeln is not defined, perhaps import 
std.stdio; is needed?


That seems to come from src/dmd/expressionsem.d , which uses 
importHint from

src/dmd/imphint.d , which just has this list:

  shared static this()
  {
  // in alphabetic order
  hints = [
  "calloc": "core.stdc.stdlib",
  "cos": "std.math",
  "fabs": "std.math",
  "free": "core.stdc.stdlib",
  "malloc": "core.stdc.stdlib",
  "printf": "core.stdc.stdio",
  "realloc": "core.stdc.stdlib",
  "sin": "std.math",
  "sqrt": "std.math",
  "writefln": "std.stdio",
  "writeln": "std.stdio",
  "__va_argsave_t": "core.stdc.stdarg",
  "__va_list_tag": "core.stdc.stdarg",
  ];
  }




Re: Iterate/sort associative array by value?

2019-04-08 Thread Robert M. Münch via Digitalmars-d-learn

On 2019-04-07 19:28:02 +, Dennis said:


Did you import it? import std.algorithm;


:-/ of course not...

Why does DMD not give a hint, that an import from the standard lib 
might be missing? I find these explicit import statements very 
annyoing. DMD should build up a database of stuff it knows about 
(provided via a config file where to find what) and auto-import just 
the things I use/need. The current system is legacy based like it is in 
C since 40 years...


Anyway, might be worth a topic on its own...

--
Robert M. Münch
http://www.saphirion.com
smarter | better | faster