Re: Singleton in Action?

2019-02-02 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 02 Feb 2019 17:34:11 +, Eugene Wissner wrote:
> For creation get() should be always used, since it is the most
> convenient way to ensure that there is really only one instance of the
> singleton. Just make this() private, so only you can create new
> instances:
> 
> private this()
> {
> }

And consider putting the class in its own source file.


Re: How can I express the type of a function in D?

2019-01-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 30 Jan 2019 12:56:06 -0800, Ali Çehreli wrote:
> I remember names like _add. Is that a Windows thing?

A number of functions are implemented as manually-mangled names with 
preprocessor macros that forward to them. It's weird, but it happens.


Re: How can I express the type of a function in D?

2019-01-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 30 Jan 2019 10:39:21 -0800, Ali Çehreli wrote:
> import core.demangle;
> 
> extern(C) int add(int, int);
> 
> void main() {
>alias F = typeof(add);
>pragma(msg, mangle!F("add"));
>pragma(msg, add.mangleof);
> }
> 
> Output:
> 
> _D3addUiiZi
> add   <-- Is that correct?

`add.mangleof` is correct. In fact, it's definitively correct.

typeof(add) is extern(C) int function(int, int). Based on this output, 
core.demangle seems like it's not taking the extern(C) portion into 
account.


Re: Should I prefix package names with the name of my program?

2019-01-28 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 28 Jan 2019 16:59:22 +, Victor Porton wrote:
> Should I prefix all module names with `xmlboiler.` (where XML Boiler is
> the name of my program). These packages are expected to be used
> internally by my program, not as an exported API (however there are some
> little chances that in the future I will make a public API)

You do you. I put all my source files inside a package unless it's a one-
file project mainly so that I can sort my import directives and have them 
organized nicely. But if you don't want to have to type `xmlboiler` five-
ish times per source file, you can skip it.


Re: Ordered set container?

2019-01-28 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 28 Jan 2019 17:18:52 +, Victor Porton wrote:
> I want "ordered set" container (like list or vector but with the
> warranty of no duplicate elements).
> 
> Which type can I use?

std.container.rbtree

It has options to preserve or squash duplicates.


Re: How is this code supposed to work?

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 25 Jan 2019 19:14:51 -0500, Steven Schveighoffer wrote:
> Interestingly, It's not possible to do the second form, so it's a bit
> curious why we don't just drop the requirements for nested
> parentheses...

The error messages there are really hideous, too:

template Just(alias s) { alias Just = s; }
alias f = (Just!Just)!int;

scratch.d(16): Error: basic type expected, not (
scratch.d(16): Error: function declaration without return type. (Note that 
constructors are always named this)
scratch.d(16): Error: semicolon expected to close alias declaration
scratch.d(16): Error: found ; when expecting . following int
scratch.d(17): Error: found } when expecting identifier following int.
scratch.d(18): Error: found End of File when expecting ; following 
statement
scratch.d(18): Error: found End of File when expecting } following 
compound statement

So I guess this is just to make people less confused about order of 
operations, since it would be unexpectedly right-associative in a language 
where most things are left-associative?


Re: How is this code supposed to work?

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 25 Jan 2019 09:34:47 +, AndreasDavour wrote:
>auto point3 = getResponse!Point!int("What's the point? ");

This could be:

getResponse!(Point!int)

or:

(getResponse!Point)!int

D requires this to be disambiguated at the parsing stage, before the 
compiler works out what getResponse might be.

An example of the latter:

template getResponse(alias n)
{
alias getResponse = n;
}

getResponse!Point is just Point.

I'm not sure why that tutorial has it wrong, but the way to get it fixed 
is to contact the author.


Re: std.socket.Address not allowed in tuples

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 24 Jan 2019 01:35:57 +, Steven O wrote:
> Is there any documentation or examples of how to do that? The
> RedBlackTree documentation gives trivial examples like

You define a function implementing the "less" operation for a pair of 
Tuple!(Address, int) (or whatever you have).

---
alias V = Tuple!(Address, int);
bool less(V a, V b)
{
  if (a[0].classinfo != b[0].classinfo)
  {
return a[0].classinfo < b[0].classinfo;
  }
  // do something for InternetAddress, Internet6Address, etc
  return 0;
}
---

Then pass that to RedBlackTree:

---
alias VTree = RedBlackTree!(V, less);
VTree tree = new VTree();
---


Re: opEquals() non-standard return type

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 23 Jan 2019 15:19:06 +, Jacob Shtokolov wrote:
> I'm wondering, is that possible to declare multiple versions of
> opEquals() and evaluate them in the different places depending on return
> type?

I looked at this a while ago for similar reasons. It didn't pan out.

When you override the comparison operator, you can't distinguish which 
comparison is overloaded. It takes at least 2^n evaluations of the 
function to determine all the comparisons, possibly more. (I *think* you 
can observe the short-circuiting logic as you do those evaluations to 
determine how each comparison is combined.)


Re: std.socket.Address not allowed in tuples

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 23 Jan 2019 15:56:15 +, Steven O wrote:
> Why am I not allowed to put Address types in tuples?

As always, it helps a lot to post the error message the compiler gave you. 
The message is:

/usr/include/dmd/phobos/std/functional.d-mixin-215(215): Error: template 
std.typecons.Tuple!(Address, int).Tuple.opCmp cannot deduce function from 
argument types !()(Tuple!(Address, int)) inout, candidates are:
/usr/include/dmd/phobos/std/typecons.d(806):std.typecons.Tuple!
(Address, int).Tuple.opCmp(R)(R rhs) if (areCompatibleTuples!
(typeof(this), R, "<"))
/usr/include/dmd/phobos/std/typecons.d(820):std.typecons.Tuple!
(Address, int).Tuple.opCmp(R)(R rhs) if (areCompatibleTuples!
(typeof(this), R, "<"))
/usr/include/dmd/phobos/std/container/rbtree.d(866): Error: template 
instance `std.functional.binaryFun!("a < b", "a", "b").binaryFun!
(inout(Tuple!(Address, int)), Tuple!(Address, int))` error instantiating
scratch.d(13):instantiated from here: RedBlackTree!(Tuple!
(Address, int), "a < b", false)

The last line says that the error came when trying to instantiate the 
RedBlackTree template. At that point, Tuple was instantiated. There is no 
issue putting an address in a Tuple.

The issue is that Address doesn't have a comparison operator defined, so 
the resulting tuple type can't be compared with the standard operators. 
You need to define your own function for comparing the tuples in question 
and pass that to RedBlackTree.


Re: Deprecation

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 22:53:23 +, Ali wrote:
> Hello. I am having an issue with the code below. the out put after
> compiling is this :
> 
> Deprecation: foreach: loop index implicitly converted from size_t to
> uint
> 
> the code is :
> 
> auto available = new int[cast(uint) max - min];
>   foreach (uint i, ref a; available)
>   a = min + i;
> 
> Any help would be highly appreciated.

You are trying to use a uint (max value 2^32-1) to give an index for an 
array (which might be more than 2^32-1 elements long). That's deprecated 
and will be gone from the language in a few releases.

Instead, write:

foreach (size_t i, ref a; available)
  a = cast(uint)(min + i);


Re: Is there a nice syntax to achieve optional named parameters?

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 09:39:31 +, John Burton wrote:
> On Thursday, 17 January 2019 at 01:43:42 UTC, SrMordred wrote:
> 
>> struct Config {
>>  string title;
>>  int width;
>> }
>>
>> struct Window {
>>  this(Config config)
> 
> It likely is a bad idea for a small struct like this but if it was much
> bigger would it makes sense to write this as :-
> 
>   this(const ref Config config)
> 
> Which is what you might do in C++ or does D handle this differently?

Creating a window is the dominating cost here. If you're creating enough 
windows that copying them is a problem, you're doing something seriously 
weird and it might be more productive to step back and think about that 
than to switch to const ref.


Re: Runtime heterogeneous collections?

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 10:07:41 -0500, Steven Schveighoffer wrote:
> But what is the common interface between those 2 types? Even in
> Dcollections, where RedBlackTree came from, there was no interfaces that
> didn't specify the type they were dealing with. In other words, there is
> no common interface for sets of 2 different types.

.empty(), .clear(), .length(), and .toString(sink, formatspec). Which is 
kind of anemic. Might as well use Object.


Re: Runtime heterogeneous collections?

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 17 Jan 2019 02:21:21 +, Steven O wrote:
> I want to create a heterogeneous collection of red-black trees, and I
> can't seem to figure out if it's possible.

RedBlackTree!int and RedBlackTree!string are entirely different types 
(they just happen to be generated from the same template).

There are two reasonable ways of doing things:

1. Make a wrapper class. Now you can store Object[], or you can make a 
base class or base interface and use that.
2. Use Variant, which can wrap anything, or the related Algebraic, which 
can wrap a fixed collection of types.

You can use this technique either with the collection types themselves or 
with the value types.


Re: unittest which uses a disk file

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 16 Jan 2019 21:07:24 +, Victor Porton wrote:
> What is the rule for unittest which uses a file (containing example data
> for testing) available only in the source distribution, not in binary
> distribution?
> 
> I am writing a library.

The easy way of doing things is to define a version for your library's 
unittests. Like I might write:

version (EpubTest) unittest
{
writeEbookFile("test.epub");
}

And then in dub.sdl, I'd have the test configuration add
-version=EpubTest. Dub has support for this sort of thing, but I don't 
know the details offhand.

If you have extra dependencies or need extra environment setup, you might 
want to make a second dub package inside the same repository and give it a 
path-based dependency on your library. Normal people won't touch that 
second package, so you can do whatever you want there, and it's a good 
place to add another README.


Re: What is the Utility of Parent Class Method Hiding in Inheritance?

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 16 Jan 2019 12:01:06 -0500, Steven Schveighoffer wrote:
> It was 2.068 that removed the HiddenFuncError, and made this a compile
> error instead. If your compiler is that or newer, definitely file a bug
> report.

Oh god, that must have been awful. I'm glad we're no longer in those 
benighted times.


Re: problem extracting data from GtkSourceView using Gtkd

2019-01-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 14 Jan 2019 22:52:48 +, Chris Bare wrote:
>   auto start = new TextIter();
>   auto end = new TextIter();

You shouldn't need to new these. `out` means that the function is going to 
overwrite the variables.

Other than that, I'm not sure.


Re: What is the Utility of Parent Class Method Hiding in Inheritance?

2019-01-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 14 Jan 2019 09:10:39 +, Vijay Nayar wrote:
>  a.foo(1);  // issues runtime error (instead of calling
> A.foo(int))

Calling the function doesn't issue any sort of error. Overriding one 
overload without overloading or explicitly aliasing in the rest issues a 
compile-time error.

If you got a runtime error instead, please create a bug report.

> I ran into this the other day, where I had a function of the same name
> in a child class, and found that all functions in the parent of the same
> name now became hidden, unless I add an alias statement.

If the functions from the parent class are hidden but your code compiles, 
please create a bug report.


Re: nice-curses releases / dub version git?

2019-01-12 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 12 Jan 2019 12:10:25 +, Droggl wrote:
> 2. Is there a way to get a certain git-version (eg. commit or maybe even
> just "latest") for a package in dub?

git submodule and path-based dependencies, if you need a particular 
version.

> 3. How is everyone in general using curses with D? Is there maybe a
> different library I should checkout instead? Are you using latest git?

dstep on curses.h and including that directly in my project.


Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 11 Jan 2019 17:25:29 +, Enjoys Math wrote:
> Package peggged not found for registry at https://code.dlang.org/

The package name is pegged, not peggged. Two g's, not three.


Re: Forward declaration inside Function block, no error?

2019-01-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 06 Jan 2019 20:19:59 +, Rubn wrote:
> You can declare functions inside of functions in D. You weren't forward
> declare grow() in the module namespace, so much as you were forward
> declaring a new function grow.

Unfortunately, you can't do forward declarations for nested functions. If 
you could, that would be handy for mutual recursion:

void main()
{
int a(int i);
int b(int i)
{
if (i > 0) return a(i - 1);
return abs(i);
}
int a(int i)
{
if (i % 2 == 0) return b(i - 2);
return b(i - 1);
}
writeln(a(12));
}

Unfortunately, Error: declaration a is already defined

And omitting the forward declaration gets you: Error: undefined identifier 
a


Re: Co-developing application and library

2019-01-05 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 05 Jan 2019 17:44:27 +, Neia Neutuladh wrote:
> 2. Different build configurations. The same source code has two
> different build targets; the executable doesn't depend on the library.
> Or, with enough bludgeoning, you can make the executable depend on the
> library.

Hit 'send' too soon.

The build configuration way would be:

---
# dub.sdl
configuration "exe" {
  targetType "executable"
}
configuration "lib" {
  targetType "staticLibrary"
  excludedSourceFiles "src/cli/*"
}
---

Then you'd build with:

dub build --config=lib
dub build --config=exe

To make this version of things yield an executable depending on a library, 
you'd use something like:

---
# dub.sdl
configuration "exe" {
  targetType "executable"
  excludedSourceFiles "src/lib/*"
  importPaths "src/lib"
  libs "-L." "-L-l:libmyproject.so"
}
configuration "lib" {
  targetType "sharedLibrary"
  excludedSourceFiles "src/cli/*"
}
---

The one advantage of this is being able to use shared libraries. It's 
awkward.


Re: Co-developing application and library

2019-01-05 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 05 Jan 2019 13:01:24 +, Russel Winder wrote:
> Dub seems to have the inbuilt assumption that libraries are dependencies
> that do not change except via a formal release when you developing an
> application.
> Clearly there is the workflow where you want to amend the library but
> not release as a part of developing an application. Does Dub have a way
> of doing this, I haven't been able to infer one to date. But I am a
> beginner at Dub.

There are a few ways to do this:

1. Path dependency, as Alex mentioned.
2. Different build configurations. The same source code has two different 
build targets; the executable doesn't depend on the library. Or, with 
enough bludgeoning, you can make the executable depend on the library.
3. Subprojects.
4. dub add-local on the library, as Mike Parker mentioned.

I wouldn't depend on ~master because (a) that won't change until you 
commit stuff and (b) it might require also running dub upgrade to get the 
new source code.

The subproject way of doing things:

---
# dub.sdl
name "myproject"
targetType "none"
# So we build the child projects
dependency "myproject:lib" version="*"
dependency "myproject:exe" version="*"
# To define the child projects
subPackage "./lib"
subPackage "./exe"
---

---
# exe/dub.sdl
name "exe"
dependency "myproject:lib" version="*"
targetType "executable"
---

This will intuit a project structure like:

  dub.sdl
  exe/
dub.sdl
src/
  lib/
dub.sdl
src/

But if you prefer, you can modify that with "sourcePaths" in the 
subpackage dub.sdls.


Re: reimplementing an interface in a derived class

2019-01-04 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 04 Jan 2019 08:46:24 +, Alex wrote:
> Let's assume this is right. How to force a B object to behave like an A
> object? I thought casting is a possible approach...

It requires a bit of surgery:

import std.stdio;
class A
{
void foo() { writeln("hello from A!"); }
}
class B : A
{
override void foo() { writeln("hello from B!"); }
}
void main()
{
auto b = new B;
auto ptrB = cast(void**)b;
ptrB[0] = A.classinfo.vtbl.ptr;
b.foo();
}

This takes advantage of the object layout used by DMD. 'vtbl' is the 
virtual function table, which is basically an array of function pointers. 
Each member function defined in a type (and its super types) gets a unique 
index into that array.

So when you write:

b.foo();

That works out to:

(cast(void function(B))b.vtbl[5])(b);

We replace object b's vtbl with class A's, and now b is just an A with 
some extra stuff allocated in its memory block.

Don't do this in production code. This is a terrible thing to do in 
production code, or any code you intend to use other than to see how D's 
object model works.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 04 Jan 2019 00:19:05 +, Alex wrote:
> B.foo overrides A.foo. By casting a B object to be an A object, A's
> behavior should be granted, shouldn't it?

I can't think of a single class system that works like that. C++, Java, 
C#, Dart, and TypeScript all work like D here. GObject in C works like D.

The point of OOP is that a bundle of data has particular ways of dealing 
with it. B has different data (at least theoretically), and that data has 
different ways of working with it. So if casting to a base class changed 
something to use the base class's behavior, you'd get bugs almost anywhere 
you used inheritance, since the derived class's data isn't being modified 
properly.

The only situation in which you might possibly want that sort of behavior 
is if inheritance were only for ease of implementation, but then you'd 
want to disallow that sort of cast anyway. It would be like trying to cast 
an object to one of its fields.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 23:44:15 +, Alex wrote:
> I assume that is another bug and has nothing to do with interfaces...

B.foo is both overriding A.foo and implementing D.foo, so that's not a bug.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 22:30:48 +, kdevel wrote:
> class A : D {
>  int foo() { return 1; }
> }
> 
> class B : A, D {
> [...]
>
> What is the meaning of the ", D"? It does not seem to make a difference
> if it is omitted.

B must provide its own implementation of D. It can't simply use A's 
implementation.


Re: What's wrong with this template function?

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 20:34:17 +, Machine Code wrote:
> Thank you very much, Ali. So the issue was basically I can't return from
> a static foreach() loop right?

The static foreach is done at compile time and the return is done at 
runtime.

After the template is expanded, your code ends up looking like:

Color first()
{
return Color.red;
return Color.blue;
return Color.green;
static assert(false);
}

And that doesn't compile, because there's a static assert there that 
fails. It's not at any line of code that would execute at runtime, but the 
compiler doesn't care about that.


Re: Subtypes with tighter constraints

2019-01-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 01 Jan 2019 14:05:43 +, Victor Porton wrote:
> In Ada2012 there are "subtypes". Subtypes can have tighter constraints
> (such as type invariants) than their base types.
> 
> I have a struct X in D. Is it possible to define a type equivalent to X
> except that having tighter invariants?

In D, structs don't participate in inheritance. Classes do, but invariants 
aren't inherited; they're specific to the class in which the function is 
defined. (Which is probably a bug and I filed https://issues.dlang.org/
show_bug.cgi?id=19537.)

I see three ways to make this work today:

1. Use alias this to wrap the struct. Add invariants that deal with the 
wrapped struct's fields.
2. Use compile-time reflection to copy the fields over, then manually copy 
the invariants over and add more.
3. Use a class. Define a virtual function like 'doInvariant()`. Call it 
from the base class's invariant{} block.

> As I understand if I derive Y from X, then it is no more X; that is I
> cannot use X (even provided it matches Y invariants) where I need Y. So
> in D it is impossible, right?

With classes, a derived class instance can be used anywhere you expect a 
base class instance. The reverse is not true.


Re: D-oriented Syntax Highlighting Plugin for WordPress?

2019-01-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 01 Jan 2019 14:46:15 +, Ron Tarrant wrote:
> I've found a ton of syntax highlighter plugins for WordPress, but none
> that admit to supporting D. Anyone know of one?

I believe I use Enlighter for that:
https://wordpress.org/plugins/enlighter/


Re: Why can't or shouldn't I just hash the address of an object? And how.

2018-12-29 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 30 Dec 2018 05:36:41 +, Enjoys Math wrote:
> Is it:
> 
> typeof(T).getHash()?

This gets the hashcode for the object by calling toHash() on it.

> Or does that do something other than just get the address?

It XORs the address with a bitwise rotation of the address. This reduces 
collisions since objects are allocated aligned.

As for your larger problem, I'd strongly tend toward using a database to 
hold application state instead of keeping it in memory.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 18:34:04 +, bauss wrote:
> I think there is a bigger problem at stake here in terms of software
> architecture.
> 
> What's the point needed for them to have the same identifier?

A probably abstract base class with only one child class. Normally you 
have "Foo" and "FooImpl", or "IFoo" and "Foo", but that's ugly.

This was the primary example that Michelle Long gave. I'd expect that a 
fair portion of people people who have used C# encountered this kind of 
situtaion. Like this sort of thing works in C#:

class Foo {}
class Foo : Foo {}
class Foo : Foo {}

You can do this in C# because each of these are *classes*, and some just 
happen to have type parameters. In D, you'd have one class and two 
templates, and you can't overload two symbols of different kinds, so you 
have to write it as:

class Foo() {}
class Foo(T): Foo!() {}
class Foo(T, U): Foo!() {}

In Java, for legacy reasons, this pattern is baked into the language; 
Foo always has another class, Foo, that it implicitly casts to and 
from. Some people take advantage of that.

Most people who do both metaprogramming and OOP in D and have been doing 
that for a nontrivial amount of time probably encountered this exact same 
thing in D. I encountered it the first time before D2 was a thing.

> Clearly the two classes will have two different functions and should be
> named accordingly.

They will have different implementations and may have different 
interfaces. The proposed use case is inheritance, so X!10's public 
interface will be a superset of X's (and likely identical).

To give a slightly less contrived example, let's say you want to have some 
functions available to a scripting language. (I'm doing something like 
this in a side project for a CLI spreadsheet program.) Each function has a 
display name, help text, argument validation, and the function body.

If I had done this in an OOP style (and I might end up reworking it to look 
more like this), I'd have something like:

interface Function
{
  string helpText();
  string name();
  Nullable!Error validateParameters(Val[] parameters);
  Val execute(Val[] parameters);
}

And then I'd have a convenience mechanism to produce a conforming class 
from a function with UDAs:

class FunctionImpl(alias fn) : Function
{
override:
  string helpText() { return getUDAs!(fn, Help)[0].text; }
  string name() { return __traits(identifier, fn); }
  // etc
}

It would be slightly nicer to just have "Function" everywhere instead of 
both Function and FunctionImpl. Not enough to justify the complexity of 
the symbol lookup rules required. Not enough to make `class Foo(T)` mean 
something different from `template Foo(T) class Foo`. But it *would* be 
slightly nicer, and it would make things slightly more straightforward for 
people coming from C#.


Re: Determination of thread status.

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
1. Find the Thread object:
  Tid threadId = spawn();
  auto thread = Thread.getAll.filter!(x => x.id == threadId).front;
2. Check the `isRunning` property.

The indirection with spawn() is awkward.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 16:55:36 +, Neia Neutuladh wrote:

And I forgot part of it.

Let's say we did the work to make this function:

class X {}
template X(int N)
{
  // `: X` somehow refers to the X in the outer scope
  class X : X {}
}

How do you distinguish between the base class and the derived class in 
there? You'd have to use typeof(this) and typeof(super) everywhere.

And externally, how do you refer to class X and template X separately? If 
you have a template with an alias parameter and pass X, how do you pass 
class-X and how do you pass template-X?

This is already unpleasant with functions, and there's a way to 
distinguish them.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 13:03:13 +, Michelle Long wrote:
> But I am not talking about inside the template being used. The whole
> point of doing this is so that one can refer to the base class using the
> same name as the derived with a template parameter to make a composite
> structure.

The following are entirely equivalent:

class X(int N) : X {}

template X(int N)
{
  class X : X {}
}

You want to be able to do, essentially:

class X {}
template X(int N)
{
  // `: X` somehow refers to the X in the outer scope
  class X : X {}
}

And sure, this specific case obviously doesn't work if the `: X` refers to 
the template or the class inside the template. But the symbol lookup rules 
aren't "try everything and see what sticks". You look up the nearest 
symbol and then you just use that.

It would be like arguing that, in the following example, the compiler 
should know that ints aren't callable and should call the function:

void foo() { writeln("merr critmis"); }
void main()
{
int foo = 10;
foo();
}

Which isn't obviously wrong, but it does make things harder to understand.


Re: Mysteries of the Underscore

2018-12-24 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 24 Dec 2018 08:16:01 -0800, H. S. Teoh wrote:
> Rather, it's *conventionally* taken to mean "unused".  The language
> actually does not treat it in any special way apart from "normal"
> identifiers.  It's perfectly valid (though probably not recommended!) to
> declare functions or variables with the name "_" and use them.

I once, in my callow days, wrote a unittest with variables named _, __, 
___, etc. It did not pass code review, but it did amuse.


Re: How to deprecate member function from outside?

2018-12-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 22 Dec 2018 21:33:14 +, Dru wrote:
> The first example shows that it is possible to deprecate a function
> separately from it's definition.

No, it doesn't. You declared two *different* functions. One was 
deprecated; the other wasn't.

> I want to know if it is possible to "fix" the second example? (deprecate
> a member function separately from it's definition)

No. All functions must be deprecated where you declare them.


Re: How to deprecate member function from outside?

2018-12-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 22 Dec 2018 18:55:47 +, Dru wrote:
> I would like to use "deprecated" on a member function, but do it from a
> separate file
> 
> this works:
> ///
> void func() {}
> 
> deprecated {
>void func();
> }

You're defining two functions, presumably in two different modules and 
with two different fully qualified names. One function is deprecated but 
has no body, so you will get a deprecation warning and a linker error if 
you try using it. One function is not deprecated and has a body, so you'll 
get no errors if you try using it.

If, on the other hand, you define both the non-deprecated and deprecated 
functions in the same file, and you try using them, you'll get an error 
saying that the function call matches multiple functions.


Re: using dub to compile plugins

2018-12-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 21 Dec 2018 10:56:39 +, Atila Neves wrote:
> I don't see how you can do this with dub, and I wouldn't attempt it
> either. Just use make, and have make call dub for the main project (and
> potentially any plugins that need it). Remember to make the dub targets
> `.PHONY` since you don't want to be managing the D dependencies by hand.

Or you could have it depend on dub.sdl, dub.selections.json, your D source 
files, and your string import files. Which is a bit more work but will 
result in a little less recompilation.


Re: Mixin operator 'if' directly

2018-12-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 19 Dec 2018 15:12:14 +, bauss wrote:
> That's assuming that it's compile-time data though.
> 
> If not then you can't do what you want to do.
> 
> What you can do is wrap it in a function in the mixin template which you
> just call after instantiating it.

Or while instantiating it:

mixin template foo()
{
  int _ignoreme()
  {
if (readln.strip == "abort") throw new AbortException;
return 1;
  }
  int _alsoIgnoreMe = _ignoreme();
}
void main()
{
  mixin foo;
}


Re: using dub to compile plugins

2018-12-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 19 Dec 2018 12:57:14 +, Codifies wrote:
> I could do this with a few simple rules in a Makefile, but I have no
> clue how to achieve this using dub.

If you need dub, you can create a wrapper script that generates the dub 
file for the plugins directory.

Make is a lot better for this kind of thing.


Re: saving std.random RNG state

2018-12-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 17 Dec 2018 22:20:54 +, harfel wrote:
> I am looking for a way to serialize/deserialize the state of the
> std.random.Random number generator, ideally using orange
> (https://github.com/jacob-carlborg/orange) or another serialization
> library. From looking at the module source code, I understand how to
> seed a random number generator with the state of another, but I do find
> a way to access the RNG's state, since it is hidden away in a private
> attribute. What is the recommended solution for this? Thanks in advance!

The .tupleof field allows you to access private members. This behavior 
might eventually change, but probably not without a long deprecation 
period.

If the struct stores everything by value:

cast(ubyte[])[0..1];

If you have typeinfo available, you can check if the thing has pointers 
with `(typeof(rng).flags & 1) == 0`. There's probably an equivalent in 
std.traits that works at compile time.


Re: Shared static this() not executed for unittest

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 17:19:05 +, Timoses wrote:
> Running `dub test` will output:
> Running ./unit-test-library writeln: unittest All unit tests have been
> run successfully.
> 
> Why is the `shared static this()` not executed?

Run `dub clean; dub test -v` and you'll see that main.d isn't compiled 
into the test library.

dub test substitutes its own main() function over yours. In order to do 
this, it needs to not compile in your main() and to compile in its own. 
dmd doesn't have an option to replace main(), so dub drops that entire 
source file.


Re: How to initialize a globle variable nicely and properly?

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 13:49:03 +, Heromyth wrote:
> Yes, it's very dangerous to create a new thread in shared static this().
> For a big project, it sometimes hard to identify this problem. Maybe,
> the compiler should do something for this, should it?

The runtime, more likely. There are plenty of problems in this vein that 
the compiler can't detect, but the runtime should be able to detect all of 
them.

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


Re: How to initialize a globle variable nicely and properly?

2018-12-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 02:54:55 +, Heromyth wrote:
>  shared static this() {
>  writeln("running A in shared static this(),
> sharedField=", sharedField);
> 
>  Thread th = new Thread(() {  });
>  th.start();

When you start a D thread, thread-local static constructors get run. So 
don't start threads until your shared static constructors finish.

If I encountered something like this, I would set up a queue of actions to 
be run at the start of main() and fill them with static constructors. 
Instead of this static constructor creating a thread, it would enqueue a 
delegate that starts the thread.


Re: Bug in shifting

2018-12-13 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 14 Dec 2018 00:16:51 +, Michelle Long wrote:
> byte x = 0xF;
> ulong y = x >> 60;

"Error: shift by 60 is outside the range 0..31"

This is the result of integer promotion rules. Change the 30 to a 60 and 
it works, and the result is, as you would expect, 0.

> I thought D required breaks for cases? Seems it doesn't any longer!

A number of things can terminate a case block:
* break
* continue
* goto
* assert
* throw
* return

Probably a few others.


Re: How to set constant value to environment variable at compile time?

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 10 Dec 2018 17:58:32 +, aliak wrote:
> string parseConfig(string str) {
>string ret;
>foreach (line; str.split("\n")) {
>  auto parts = line.split("=");
>  ret ~= `string ` ~ parts[0] ~ ` = "` parts[2] `";`;
>}
>return ret;
> }

That works as long as none of the environment variable values contain a 
double quote or a newline character.


Re: How to set constant value to environment variable at compile time?

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 10 Dec 2018 11:08:23 +, Narxa wrote:
> Hello, people!
> 
> I would like to have a constant with the value of some environment
> variable that is defined at compile time.

In your build script, echo the environment variable into a file. Then 
import() that file and use the value.

> I know I could possibly use 'gdc' to achieve that but I want to use the
> 'dmd' compiler.

Defining variables like that is a language-level feature. gdc supports 
exactly the same options as dmd.


Re: dmd -unittest works poorly with executables

2018-12-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 08 Dec 2018 20:16:09 +, Andrew Pennebaker wrote:
> I think it's lame to have to use magical code like `version(unittest) {}
> else` to guard our main functions, when we run unit tests. Could D go
> ahead and do the right thing, automatically shadowing our main functions
> when the unit tests are run?

The original intent was for unittests to run before main(). Your debug / 
test builds always run the unittests. This is awkward because unittests 
might sometimes actually be heavier tests that talk to a database or write 
to local files or change global state that would be used in main().

The normal technique with dub is to put *only* main() in app.d. Sometimes 
I take that a step further: I put a runMain() function somewhere in my 
project, and app.d's main() just calls that. Dub automatically excludes 
app.d from the unittest build. Minimum possible code outside the tested 
zone.

Not necessarily awesome, but we do have workarounds.


Re: Compiling a template

2018-12-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 06 Dec 2018 22:50:49 +, albertas-jn wrote:
> If templates are a compile-time feature and instances of templates are
> generated by compiler at compile time, why is it possible to compile a
> template definition with dmd -lib or -c?

You compile files, not individual declarations like a template. If you 
have a source file containing a hundred templates and nothing else, and 
you compile it, you'll get the same output as if you had an empty source 
file, byte for byte.


Re: Trying to get current function name results in compiler error with __traits

2018-12-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 07 Dec 2018 02:37:34 +, Arun Chandrasekaran wrote:
> I'm trying to get the current function name and apparently the commented
> line errors out.
> 
> What am I doing wrong?

Referring to nested functions is weird.

Dotted identifiers let you traverse aggregates. Modules, C++ namespaces 
(ugh), enums, structs, identifiers, unions, that sort of thing. They 
*don't* let you traverse functions to refer to symbols defined inside 
those functions.

*Separately*, nested functions have names that look like dotted 
identifiers. But you can't use that to refer to them, because that would 
make it *very* awkward to do symbol lookup.

For example:

struct Foo { int bar; }
Foo test()
{
void bar() { }
writeln();
return Foo();
}

Should the `writeln` line invoke the `test` function, get the `bar` field 
from its result, and take its address? Or should it take the address of 
the nested function `bar`?


Re: .dup vs operation on all elements

2018-12-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 03 Dec 2018 21:27:52 +, faissaloo wrote:
> Then shouldn't the following output false, false, true?

An object reference is a pointer value. The pointer values are copied. The 
pointed-at objects are not copied.

Furthermore, the syntax

Object[6] array = new Object();

only allocates one Object. Each item in the array is an object reference 
to the same object.


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 30 Nov 2018 22:10:11 +, ikod wrote:
> Thanks for explanation, got it.
> 
> My case is actually
> 
> interface I(K,V)
> {
>  int get()(K);
> }

Interface functions must be abstract. Templated functions are implicitly 
final. Final things can't be abstract.

If there's something about types K and V that determine whether you should 
be able to use the GC or not, you'll have to encode that explicitly.


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 30 Nov 2018 20:41:03 +, ikod wrote:
> I can't find the reason why nogc/nothrow can't be inferred in this case:
> 
> class S(K,V)
> {
>  auto get/*()*/(K a) {
>  return 0;
>  }
> }
> void main() @nogc nothrow {
>  S!(int, string) sia;
>  auto v = sia.get(1);
> }

class Nefarious : S!(int, string)
{
  override int get(int a)
  {
// Whoops, I used the GC
return new char[a].length;
  }
}

The compiler can't prove that a variable of type S!(int, string) will not 
be of type Nefarious, which uses the GC, so it can't infer @nogc for S.get.

However, if you make the function final, then the compiler can infer it to 
be pure nothrow @nogc @safe.

Or if you use a struct instead of a class, structs don't do inheritance, 
so the compiler can infer attributes without worrying about nefarious 
inheritance.

> But everything is ok if you uncomment parentheses after get.

Templated functions are implicitly final.


Re: Function signature as string

2018-11-29 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 29 Nov 2018 21:11:06 +, John Chapman wrote:
> Is there any way to get a string representing a function's exact
> signature as declared in the source? I can generate it myself using
> reflection but it might not be 100% verbatim so wanted to know if
> there's anything built in?
> 
>foreach (m; __traits(allMembers, T)) {
>  alias member = __traits(getMember, T, m);
>  string signature = // Call some function to get "member"'s
> signature as a string
>}

typeof().stringof should do it:

void bar(string s, ref Foo!int i) {}
void main()
{
writeln(typeof().stringof);
}

prints: void function(string s, ref Foo!int i)


Re: What can I use to parse a date string in a custom format?

2018-11-27 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 27 Nov 2018 18:22:17 +, PacMan wrote:
> I've been looking for a function or library to parse a date in a custom
> format (for validation) similar to C#'s [1]
> TryParseExactbut I couldn't find any. so far I only found
> fromISOExtString(), and fromSimpleString() which doesn't allow me to set
> a custom string format.

http://code.dlang.org/packages/datefmt didn't do it for you?

...that readme is pretty terrible, granted.


Re: How do I the temlate parameter name as string?

2018-11-26 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 27 Nov 2018 02:00:44 +, PacMan wrote:
> f is defined as:
> 
>> void f(T)(T t, string p)
>> if(is(T == A) || is(T == B))
>>{
>>  // ...
>>}
> 
> my goal is get "p" as string.

`f` is a template that generates functions. Before you instantiate that 
template, the function doesn't exist, so there's no function to get 
parameters from.

You can get the parameter names of any instantiation of that template, 
such as:

assert(ParameterIdentifierTuple!(f!A)[1] == "p");


Re: D Language 2.1

2018-11-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 25 Nov 2018 20:46:28 +, Tony wrote:
> From std.compiler.D_major and std.compiler.D_minor I see that my D
> language version is at 2.0 . But the version of gdc front-end I am using
> (via Debian default gdc package as of a few months ago) from
> std.compiler.version_major and std.compiler.version_minor is at 2.68.

D_minor is 0 in both.
version_minor is 68 in your version of GDC, which matches version_minor 
for DMD 2.068.*.

> That is a lot of bug fixes, with 0 changes to the language.

In semantic versioning terms, the product is D2 and the current version is 
83.0.0.

> Actually, I realize that changes to the language are being reflected in
> compiler versions, not language versions. Just wondering why it was
> decided not to version the language (2.1, 2.2, etc.)

There are feature changes with every major compiler release, so it would 
be pointless complexity to version the language separate from DMD.


Re: How to get all modules in a package at CT?

2018-11-24 Thread Neia Neutuladh via Digitalmars-d-learn
Easiest way is to put this in your build script:

find path/to/package -name '*.d' | \
   xargs grep '^module ' | \
   sed 's,^module,import,' \
   > data/modules.d

Add `-J data` to your DMD command line, or add `"stringImportPaths":
["data"]` to dub.json.

Then in your file:

mixin(import("modules.d"));


Re: version(StdDoc)

2018-11-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 23 Nov 2018 21:43:01 -0700, Jonathan M Davis wrote:
> A solution like that might work reasonably well, but you still
> have the problem of what to do when a symbol is documented in multiple
> version blocks, and having almost all the documentation in one version
> block and a few pieces of it in other version blocks would risk getting
> confusing and messy.

Keeping symbol names and function arguments consistent between them is 
also an issue; it's not just the documentation. The normal solution is to 
put the version blocks inside the relevant symbols -- sometimes type 
aliases inside version blocks and consistent code outside, sometimes 
functions where the entire body is a set of version blocks.


Re: version(StdDoc)

2018-11-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 23 Nov 2018 17:21:25 -0800, H. S. Teoh wrote:
> Ddoc may have its stink points, but in this case, the stuff inside
> version(Windows) blocks simply isn't compiled, so you can't expect ddoc
> to do much about it.  You can't just arbitrarily ddoc everything inside
> version blocks, because then you'll end up with ddocs for stuff inside
> version(none) and/or conflicting docs for alternative declarations in,
> say, OS-specific version blocks, or user-defined static if's.

That means that, instead of one site showing my project's documentation, I 
need a separate site for every combination of platform and version flags. 
And users who care about differences between platforms and version flags 
need to manually cross-reference docs for every symbol and overload.

It's a pretty terrible status quo.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 22 Nov 2018 15:50:01 +, Stefan Koch wrote:
> I'd say the problem here is not just false positives, but false
> negatives!

False negatives are a small problem. The compiler fails to catch some 
errors some of the time, and that's not surprising. False positives are 
highly vexing because it means the compiler rejects valid code, and that 
sometimes requires ugly circumlocutions to make it work.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 21 Nov 2018 20:15:42 +, welkam wrote:
> In D classes are reference type and unless you mark them as final they
> will have vtable.

Even if you mark your class as final, it has a vtable because it inherits 
from Object, which has virtual functions. The ProtoObject proposal is for a 
base class that has no member functions. If you had a final class that 
inherited from ProtoObject instead of Object, it would have an empty 
vtable.

> Lets face it most people dont mark their classes as
> final. What all this mean is that EVERY access to class member value
> goes trough indirection (additional cost)

D classes support inheritance. They implicitly cast to their base types. 
They can add fields not present in their base types. If they were value 
types, this would mean you'd lose those fields when up-casting, and then 
you'd get memory corruption from calling virtual functions.

That is a cost that doesn't happen with structs, I'll grant, but the only 
way to avoid that cost is to give up inheritance. And inheritance is a 
large part of the reason to use classes instead of structs.

> and EVERY method call goes
> trough 2 indirections (one to get vtable and second to call
> function(method) from vtable).

Virtual functions do, that is. That's the vast majority of class member 
function calls.

> Now Java also have indirect vtable calls
> but it also have optimization passes that convert methods to final if
> they are not overridden. If Java didnt do that it would run as slow as
> Ruby.

Yeah, no.

https://git.ikeran.org/dhasenan/snippets/src/branch/master/virtualcalls/
results

Java and DMD both managed to de-virtualize and inline the function. DMD can 
do this in simple cases; Java can do this in a much wider range of cases 
but can make mistakes (and therefore has to insert guard code that will go 
back to the original bytecode when its hunches were wrong).

If it were merely devirtualization that were responsible for Java being 
faster than Ruby, Ruby might be ten times the duration of Java (just as 
dmd without optimizations is within times the duration of dmd without 
optimizations). You could also argue that `int += int` in Ruby is another 
virtual call, so it should be within twenty times the speed of Java.

Instead, it's 160 times slower than Java.

> On top of that some
> people want to check on EVERY dereference if pointer is not null. How
> slow you want your programs to run?

Every program on a modern CPU architecture and modern OS checks every 
pointer dereference to ensure the pointer isn't null. That's what a 
segfault is. Once you have virtual address space as a concept, this is 
free.

> Thats negatives but what benefit classes give us?
> First being reference type its easy to move them in memory. That would
> be nice for compacting GC but D doesnt have compacting GC.

You can do that with pointers, too. D doesn't do that because (a) it's 
difficult and we don't have the people required to make it work well 
enough, (b) it would make it harder to interface with other languages, (c) 
unions mean we would be unable to move some objects and people tend to be 
less thrilled about partial solutions than complete ones.

> Second they
> are useful for when you need to run code that some one else wrote for
> your project. Something like plugin system. [sarcasm]This is happening
> everyday[/sarcasm]
> Third porting code from Java to D.
> 
> Everything else you can do with struct and other D features.

Similarly, you can write Java-style object oriented code in C. It's 
hideously ugly and rather error-prone. Every project trying to do it would 
do it in a different and incompatible way.

Walter decided a long time ago that language support for Java-style OOP 
was a useful component for D to have, and having a standardized way of 
doing it with proper language support was better than leaving it to a 
library.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 21 Nov 2018 17:00:29 +, Alex wrote:
> C# wouldn't reject the case above, would it?

C# *would* reject that (you can't call any methods on a null object), but 
in D, it compiles and runs and doesn't segfault.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-20 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 23:14:27 +, Johan Engelen wrote:
> When you don't call `a.foo()` a dereference, you basically say that
> `this` is allowed to be `null` inside a class member function. (and then
> it'd have to be normal to do `if (this) ...` inside class member
> functions...)

That's what we have today:

module scratch;
import std.stdio;
class A
{
int i;
final void f()
{
writeln(this is null);
writeln(i);
}
}
void main()
{
A a;
a.f();
}

This prints `true` and then gets a segfault.

Virtual function calls have to do a dereference to figure out which 
potentially overrided function to call.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-20 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 15:29:50 +, Kagamin wrote:
> On Tuesday, 20 November 2018 at 11:11:43 UTC, aliak wrote:
>> This only applies to little scripts and unittests maybe.
>>
>> Not when you're writing any kind of relatively larger application that
>> involves being run for longer or if there's more possible permutations
>> of your state variables.
> 
> Umm... if you write a larger application not knowing what is a reference
> type, you're into lots and lots of problems.

A pointer to a struct is a reference type.

There are plenty of cases where you need reference semantics for a thing. 
If you are optimistic about the attentiveness of your future self and 
potential collaborators, you might add that into a doc comment; people can 
either manually do escape analysis to check if they can store the thing on 
the stack, or allocate on the heap and pass a pointer, or embed the thing 
as a private member of another thing that now must be passed by reference.

If you're pessimistic and don't mind a potential performance decrease, you 
might defensively use a class to ensure the thing is a reference type.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 00:30:44 +, Jordi Gutiérrez Hermoso wrote:
> On Monday, 19 November 2018 at 21:57:11 UTC, Neia Neutuladh wrote:
> 
>> Programmers coming from nearly any language other than C++ would find
>> it expected and intuitive that declaring a class instance variable
>> leaves it null.
> 
> What do you think about making the syntax slightly more explicit and
> warn or possibly error out if you don't do it that way?

The prevailing idea is that warnings are either non-problems, in which 
case they shouldn't be emitted, or things you really need to fix, in which 
case they should be errors.

Things that are sometimes errors can be left to lint tools.

> Either
> 
>SomeClass c = null;
> 
> or
> 
>SomeClass c = new SomeClass();
> 
> and nothing else.

That would work, though it would be mildly tedious.

However, the general philosophy with D is that things should be implicitly 
initialized to a default state equal to the `.init` property of the type. 
That default state can be user-defined with structs, but with other types, 
it is generally an 'empty' state that has well-defined semantics. For 
floating point values, that is NaN. For integers, it's 0. For arrays, it's 
a null array with length 0. For objects and pointers, it's null.

> Nulls/Nones are always a big gap in a language's type system. A common
> alternative is to have some Option/Maybe type like Rust or Haskell or
> D's Variant.

Variant is about storing arbitrary values in the same variable. Nullable 
is the D2 equivalent of Option or Maybe.

> How about making that required to plug the null gap?

That's extremely unlikely to make it into D2 and rather unlikely to make 
it into a putative D3. However, if you feel strongly enough about it, you 
can write a DIP.

I've used Kotlin with its null safety, and I honestly haven't seen 
benefits from it. I have seen some NullPointerExceptions in slightly 
different places and some NullPointerExceptions instead of empty strings in 
log messages, but that's it.


Re: What is best way to read and interpret binary files?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 14:32:55 -0800, H. S. Teoh wrote:
>> Standard caveats about byte order and alignment.
> 
> Alignment shouldn't be a problem, since local variables should already
> be properly aligned.

Right, and the IO layer probably doesn't need to read to aligned memory 
anyway.

Struct fields, however, need to have the same relative alignment as the 
file.


Re: What is best way to read and interpret binary files?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 21:30:36 +, welkam wrote:
> So my question is in subject/title. I want to parse binary file into D
> structs and cant really find any good way of doing it. What I try to do
> now is something like this
> 
> byte[4] fake_integer;
> auto fd = File("binary.data", "r");
> fd.rawRead(fake_integer);
> int real_integer = *(cast(int*)  fake_integer.ptr);
> 
> What I ideally want is to have some kind of c style array and just cast
> it into struct or take existing struct and populate fields one by one
> with data from file. Is there a D way of doing it or should I call
> core.stdc.stdio functions instead?

Nothing stops you from writing:

SomeStruct myStruct;
fd.rawRead((cast(ubyte*))[0..SomeStruct.sizeof]);

Standard caveats about byte order and alignment.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 21:23:31 +, Jordi Gutiérrez Hermoso wrote:
> When I was first playing with D, I managed to create a segfault by doing
> `SomeClass c;` and then trying do something with the object I thought I
> had default-created, by analogy with C++ syntax. Seasoned D programmers
> will recognise that I did nothing of the sort and instead created c is
> null and my program ended up dereferencing a null pointer.

Programmers coming from nearly any language other than C++ would find it 
expected and intuitive that declaring a class instance variable leaves it 
null.

The compiler *could* give you a warning that you're using an uninitialized 
variable in a way that will lead to a segfault, but that sort of flow 
analysis gets hard fast.

If you wanted the default constructor to be called implicitly, that would 
make @nogc functions behave significantly differently (they'd forbid 
declarations without explicit initialization or would go back to default 
null), and it would be a problem for anything that doesn't have a no-args 
constructor (again, this would either be illegal or go back to null).

Easier for everything to be consistent and everything to be initialized to 
null.


Re: Neater enum + version

2018-11-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 18 Nov 2018 17:47:07 +, Vladimirs Nordholm wrote:
> Is there anyway to make it "neater"? Maybe something in one line:
> 
>  enum foo = version (Posix) { "posix" } : { "other" } ;

If you're doing it often:

T ifPosix(T)(T a, T b)
{
  version (Posix) return a; else return b;
}
enum foo = ifPosix("posix", "other");

If it's a one-off thing, though, there's not much you can do.


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 21:16:13 +, aliak wrote:
> Could do. But it's not scalable. I'd have to comment out all the
> unittests that call the template function with a T that allocates inside
> the @nogc template (if I understood you correctly that it)

I meant something like:

void debugln(T...)(T args) @nogc
{
  import std.stdio;
  debug(MyProject) writeln(args);
}

You use that function instead of writeln in your @nogc-compatible 
templates:

void callFunc(alias func)()
{
  debugln("about to call function!");
  func();
  debugln("done calling function!");
}

Then I can write:

@nogc:
void foo() { printf("hello world\n"); }
void main() { callFunc!foo(); }


Re: Making external types available to mixins

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 17:58:54 +, John Chapman wrote:
> The idea is that users could type (for example) makeWith!`Calendar`(…)
> instead of the longer makeWith!ICalendarFactory(…).

Your project might define a hundred types named ICalendarFactory; the 
compiler can't figure out which one you're talking about unless you use 
the fully qualified name.

If you require that Calendar and ICalendarFactory be defined in the same 
module, you can use Calendar's module name to look up the appropriate 
ICalendarFactory.

You can also just build a string that the calling code mixes in.


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 13:55:24 +, aliak wrote:
> You can use "debug blah" to hide inside functions that are attributed,
> but when you have an attributed function that calls a template,
> attribtues of which are supposed to be inferred, it seems to fail.

You can explicitly mark a templated function as @nogc. If you want your 
function's @nogc-ness inferred, you can pull out the debug logging into a 
separate function and explicitly mark it @nogc.


Re: Could not setup D extension on vs code

2018-11-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 14 Nov 2018 19:28:44 +, WebFreak001 wrote:
> It's a real pain that you can't select specific commits in dub, but I
> try to keep up with the updates and make them work somehow.

Yeah, I've used submodules and path-based dependencies once or twice 
because of that. It's not the best.


Re: dip1000: why can't the addressee come into existence later?

2018-11-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 10 Nov 2018 16:25:40 +, Stanislav Blinov wrote:
> Yep, you just over-simplified the first case.

It is too simple to clearly illustrate why the code is invalid, but not so 
simple that the compiler accepts that code.

> Consider:
> 
> int* p;
> {
>  int i;
>  p = 
> }
> *p = 42;

In that example, the scope for i ends before the scope for p ends. It's 
not at all surprising that that code is wrong. In the other examples I 
gave, both i and p go out of scope at the same time.

But there's a total ordering for when variables' lifetimes end, which is 
the key (and non-obvious) difference between the two.


Re: dip1000: why can't the addressee come into existence later?

2018-11-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 10 Nov 2018 11:47:24 +, Nicholas Wilson wrote:
> On Saturday, 10 November 2018 at 06:56:29 UTC, Neia Neutuladh wrote:
>> Is this right?
> 
> Are you sure you added @safe to the second example?
> https://run.dlang.io/is/2RbOwK fails to compile.

Maybe take another look at the post you're replying to? I was saying that, 
if the compiler allowed one thing that looked safe to me, it would either 
require nuance (check for scope guards, destructors, and the like before 
saying something is un-@safe) or allow other code that is obviously 
invalid.


dip1000: why can't the addressee come into existence later?

2018-11-09 Thread Neia Neutuladh via Digitalmars-d-learn
The following code doesn't work with @safe -dip1000:

int* p;
int i;
p = 

i has a shorter lifetime than p, the compiler complains.

But this code does:

int i;
int* p;
p = 

In both cases, p can't point to i before i exists, and p ceases to exist 
when i ceases to exist.

I believe this is because the first option would let me write:

struct Foo
{
  bool exists = true;
  ~this() { exists = false; }
  void doStuff() { assert(exists); }
}

Foo* p;
scope(exit) (*p).doStuff;
Foo f;
scope(exit) destroy(f);
p = 

And this will run into the assert when -dip1000 should ensure it can't.

The compiler does this even in the absence of scope guards and destructors 
because simple, obvious rules will be easier to understand and implement 
than nuanced ones, even if it makes you reorder declarations sometimes.

Is this right?


Re: Why is stdio ... stdio?

2018-11-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 09 Nov 2018 02:03:36 +, Chris Katko wrote:
> Simple curious question.
> 
> Why isn't :
> 
> import std.stdio;
> 
> instead:
> 
> import std.io;

IO includes things like memory mapping, sockets, listing files, named 
pipes, that sort of thing.

Standard IO includes only reading and writing to files and the console.

> (Also, while we're at it. Why doesn't this form have code highlighting?
> It would much improve readibility. Doesn't that seem almost essential
> for a programming forum?)

It's not a forum. It's a newsgroup that happens to have a web interface. 
Newsgroups are text-only. So bbcode is out, html is out, but interpreting 
markdown might be reasonable. But nobody's done that work.


Re: Exception slipping through the catch block?

2018-11-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 08 Nov 2018 17:27:40 -0700, Jonathan M Davis wrote:
> You ran into one of the rare cases where it makes sense catch an Error
> or a Throwable, and you're one of the few people who understands the
> situation well enough to deal with it properly. The vast majority of D
> programmers don't. Certainly, anyone who has to ask about the
> differences between Throwable, Error, and Exception doesn't.

I really don't believe it's that rare or that fraught, most of the time.

If an error happens, it's better for most programs to try to leave behind 
enough artifacts for you to start debugging the problem. Most of the time, 
a stacktrace on stderr is good enough and still possible. And that's what 
the runtime does.

This isn't, strictly speaking, safe. Your program detected an error, and 
in Walter's book, that means you can't trust the program to do *anything*. 
Unwinding the stack, formatting a stacktrace, writing to stderr, this is 
all Dangerous Stuff You Shouldn't Be Doing. Even sending your process 
sigabrt to trigger a core dump is potentially dangerous.

But the utility is greater than the likely harm, which is why druntime 
will unwind the stack, format a stacktrace, and write to stderr when an 
Error is thrown and not caught.

Similarly, if your program logs to a file normally and you use that logfile 
for most of your debugging, it's sensible to try to log the error to that 
file and then exit. Especially if, like with H. S. Teoh's case, it's 
difficult or impossible for you to access the process's stderr.

This is still *slightly* fraught. If your logging system is responsible 
for that Error being thrown, you probably won't succeed in logging the 
Error. If you have custom Error classes that do weird things, those things 
are more likely to break. Your application might be out of memory, so the 
allocations involved in logging could also fail.

So, moderately fraught, but I don't think it's "here be dragons" any more 
than usual.


Re: scoped classes and dependency inversion

2018-11-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 08 Nov 2018 11:04:19 +, Sjoerd Nijboer wrote:
> I'm trying to invert the dependency from the classes `Bar -> Foo` to
> `Foo -> IFoo <- Bar` at compile time.
> 
> I do want `Foo's` to be embedded into `Bar`

These goals are a *little* at odds with each other; having a scoped!Foo 
puts significant constraints on how to build the object. But you know your 
needs a lot better than some generic advice.

I believe what you need to do is pass a factory function into the 
constructor. This is a bit awkward.

The really annoying part is that std.typecons doesn't have a named type 
for the scoped wrapper for a type. It's actively hostile to having scoped 
fields for no discernable reason. Filed https://issues.dlang.org/
show_bug.cgi?id=19379

Anyway, here's some code to make it work. It's kind of ugly.

---
import std.stdio;
import std.typecons;

void main()
{
auto bar = new Bar!Foo((ref f) { f = scoped!Foo(); });
}

class Bar(TFoo) if(is(TFoo : IFoo))
{
alias SFoo = typeof(scoped!TFoo());
SFoo _foo;
this(void delegate(ref SFoo) dg)
{
dg(_foo);
}
}

class Foo : IFoo
{
void baz(){}
}

interface IFoo
{
void baz();
}
---


Re: scoped classes and dependency inversion

2018-11-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 08 Nov 2018 12:45:57 +, Alex wrote:
> Hmm... not sure, if I got your idea... Do you think about something like
> this?

The point is dependency inversion. The class shouldn't need to know how to 
build its dependencies; it should leave that to other code. The fact that 
you can use the default constructor to build a thing is more coupling than 
desired.


Re: Is this a bug? +goto

2018-11-05 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 06 Nov 2018 00:33:56 +, MatheusBN wrote:
> Just to be clear, when you say "x exists at the label Q", you mean at
> the same scope, right?

The same or an outer scope. It's also invalid to write:

goto Y;
{
  int x;
  {
Y:
  }
}

> That's interesting but a bit confusing isn't?
> 
> And I found a bit strange that in such code, since "x" is never used,
> why it isn't skipped.

Because simple rules are usually easier to understand and implement.

> I know it's another language but in C at least in GCC there is no error
> over such code, so that's my confusion.

Because C is a horribly unsafe language, far beyond necessary to have a 
low-level systems language.

In C++, if you skip over `int i = 10;` it's an error, but not if you skip 
over `int i;`.

Similarly, if you skip over a class variable declaration without an 
explicit initialization expression, if the class has a constructor or 
destructor, it's an error.

In D, every variable of every type is initialized unless you opt out. The 
compiler *could* let you skip over declarations that are void-initialized, 
but there isn't a huge reason to do so.


Re: Dealing with raw types as attributes

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 02 Nov 2018 04:01:00 +, Nicholas Wilson wrote:
> By noting that all (interesting for the purpose of UDA's i.e. not void)
> types have a .init
> 
> or you could do
> 
> static if (is(typeof(uda) == Foo) || is(uda == Foo))

Which, again, only tests for presence, when I want to check for presence 
*and* get the value, which should be Foo.init if the person supplied the 
raw type.


Re: Dealing with raw types as attributes

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 02 Nov 2018 00:36:18 +, Nicholas Wilson wrote:
>> What do you do to handle this?
> 
> @Foo() int bar;
> 
> instead of
> 
> @Foo int bar;

Right. And if you're offering a library with UDAs for other people to use?


Re: Removing the precision from double

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 01 Nov 2018 23:59:26 +, kerdemdemir wrote:
> I am doing trading and super scared of suprices like mathematical errors
> during the multiplications(or division 1/tickSize) since market will
> reject my orders even if there is a small mistake.
> 
> Is this safe? Or is there a better way of doing that ?

tldr: consider using std.experimental.checkedint and highly granular units, 
like milli-cents. Also consider using a rational number library. Doubles 
aren't necessarily bad, but they'd concern me.

# 1. Fixed precision

The common way of working with sensitive financial stuff is fixed 
precision numbers. With fixed precision, if you can represent 0.0001 cents 
and you can represent ten billion dollars, you can represent ten billion 
dollars minus 0.0001 cents. This is not the case with single-precision 
floating point numbers:

writeln(0.0001f);
writefln("%20f", 10_000_000_000f);
writefln("%20f", 10_000_000_000f - 0.0001f);

prints:

0.0001
  100.00
  100.00

The problem with fixed precision is that you have to deal with overflow 
and underflow. Let's say you pick your unit as a milli-cent (0.001 cents, 
$0.1).

This works okay...but if you're trying to assign a value to each CPU 
cycle, you'll run into integer underflow. Like $10/hour divided by CPU 
cycles per hour is going to be under 0.001 cents. And if you try inverting 
things to get cycles per dollar, you might end up with absurdly large 
numbers in the middle of your computation, and they might not fit into a 
single 64-bit integer.

## Fixed precision with Checked

std.experimental.checkedint solves the overflow problem by turning it into 
an error. Or a warning, if you choose. It turns incorrect code from a 
silent error into a crash, which is a lot nicer than quietly turning a 
sale into a purchase.

It doesn't solve the underflow problem. If you try dividing $100 by 37, 
you'll get 270270 milli-cents, losing a bit over a quarter milli-cent, and 
you won't be notified. If that's deep in the middle of a complex 
calculation, errors like that can add up. In practice, adding six decimal 
places over what you actually need will probably be good enough...but 
you'll never know for certain.


# Floating point numbers

Floating point numbers fix the underflow and overflow problems by being 
approximate. You can get numbers up to 10^38 on a 32-bit float, but that 
really represents a large range of numbers near 10^38.

**That said**, a double can precisely represent any integer up to about 
2^53. So if you were going to use milli-cents and never needed to 
represent a value over one quadrillion, you could just use doubles. It 
would probably be easier. The problem is that you won't know when you go 
outside that range and start getting approximate values.


# Rational numbers

A rational number can precisely represent the ratio between two integers. 
If you're using rational numbers to represent dollars, you can represent a 
third of a dollar exactly. $100 / 37 is stored as 100/37, not as something 
close to, but not exactly equal to, 2.702 repeating.

You can still get overflow, so you'll want to use 
std.experimental.checkedint as the numerator and denominator type for the 
rational number. Also, every bit of precision you add to the denominator 
sacrifices a bit of range. So a Rational!(Checked!(long, Throw)) can 
precisely represent 1/(2^63), but it can't add that number to 10. Manual 
rounding can help there.


Re: Dealing with raw types as attributes

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 01 Nov 2018 20:01:51 +, Stanislav Blinov wrote:
> Check if an UDA is a type?.. As in, not just `is(uda == Foo)`,
> but simply `is(uda)`:

Which works, but generally makes things more complex in code that's 
already pretty deeply nested. It's also something I have to worry about 
every time I do the static foreach to get UDAs, in the cases where that's 
more than once.


Re: Dealing with raw types as attributes

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 01 Nov 2018 11:35:27 -0700, Ali Çehreli wrote:
> On 11/01/2018 09:14 AM, Neia Neutuladh wrote:
>> The spec says that a user-defined attribute must be an expression, but
>> DMD accepts a wide range of things as UDAs:
>> 
>>struct Foo { string name = "unknown"; }
>>@Foo int bar;
>> 
>> `bar` has the *type* Foo as an attribute. It's not an *instance* of
>> Foo. So if I try to look at the UDAs:
> 
> That would work with hasUDA(). I have an example here:
> 
>http://ddili.org/ders/d.en/uda.html

That lets me test for presence, nothing more. While that's useful, I 
usually have a UDA struct whose fields I need to access.

std.traits.getUDAs doesn't hide the difference between @Foo and @Foo(), so 
that's also not an option. I could use a customized version of that that 
replaces @Type with @Type.init, and that's a reasonable choice when I know 
other people aren't going to deal with that annotation type.


Dealing with raw types as attributes

2018-11-01 Thread Neia Neutuladh via Digitalmars-d-learn
The spec says that a user-defined attribute must be an expression, but DMD 
accepts a wide range of things as UDAs:

  struct Foo { string name = "unknown"; }
  @Foo int bar;

`bar` has the *type* Foo as an attribute. It's not an *instance* of Foo. 
So if I try to look at the UDAs:

  static foreach (uda; __traits(getAttributes, bar))
  {
static if (is(typeof(uda) == Foo))
{
  pragma(msg, "bar is @Foo");
}
  }

That just doesn't work; typeof(Foo) isn't anything, so is(typeof(Foo) == 
Foo) is false.

I can change my code to read `static if (is(uda == Foo))`. But that 
obviously fails:

  @Foo("customName") int bar2;

What do you do to handle this?

My current workaround is to make the attribute into a struct instance and 
use opCall in lieu of constructors:

  struct _Foo
  {
string name;
_Foo opCall(string name)
{
  _Foo f;
  f.name = name;
  return f;
}
  }
  enum _Foo Foo = _Foo.init;

Now I can use `static if (is(typeof(uda) == _Foo))` and it always works. 
But are there better options? Any obvious flaws?


Re: how to make '==' safe for classes?

2018-10-28 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 28 Oct 2018 18:00:06 +, Stanislav Blinov wrote:

> On Sunday, 28 October 2018 at 12:38:12 UTC, ikod wrote:
> 
>> and object.opEquals(a,b) do not inherits safety from class C
>> properties, and also I can't override it.
> 
> Yep. Since Object is the base class and it defines opEquals as:
> ```
> bool opEquals(Object);
> ```
> 
> the compiler rewrites `a == b` as
> `(cast(Object)a).opEquals(cast(Object)ob)`, i.e. it inserts a @system
> call into your code.

More pedantically, it rewrites it as:

  (a is b) ||
  (a !is null && (cast(Object)a).opEquals(cast(Object)b))

An object might not be equal to itself via opEquals, but it will always 
compare equal to itself with ==.


Re: Dub Renaming source/app.d makes project a library

2018-10-27 Thread Neia Neutuladh via Digitalmars-d-learn
targetType "executable" does it for me (dub 1.11.0).

Can you post your full dub.sdl?


Re: static foreach

2018-10-10 Thread Neia Neutuladh via Digitalmars-d-learn
On 10/10/2018 04:03 PM, James Japherson wrote:> Says that it cannot 
interpret X(the class that contains the static> opApply).
It's a bit hard to diagnose the problem you're getting using that 
function when we don't have the code that uses it. Or the context that's 
referenced with the foreach loop there. You might want to post a larger 
segment of code and the entire error message.


The error I'm seeing that might be related is: opApply is a static 
member of the type. So part of the function (after mixins) reads:


dg(X.opApply);

This attempts to call X.opApply with no arguments and pass the result to 
dg. But X.opApply requires an argument.


You probably want to add a `is(typeof(mixin("X." ~ m)) == cPiece)` in there.



Re: Simple parallel foreach and summation/reduction

2018-09-19 Thread Neia Neutuladh via Digitalmars-d-learn

On Thursday, 20 September 2018 at 05:34:42 UTC, Chris Katko wrote:
All I want to do is loop from 0 to [constant] with a for or 
foreach, and have it split up across however many cores I have.


You're looking at std.parallelism.TaskPool, especially the amap 
and reduce functions. Should do pretty much exactly what you're 
asking.


auto taskpool = new TaskPool();
taskpool.reduce!((a, b) => a + b)(iota(1_000_000_000_000L));


Re: Fast linear search for non-null key in slice of Nullable(T, T.max)

2018-09-16 Thread Neia Neutuladh via Digitalmars-d-learn

On Sunday, 16 September 2018 at 16:28:20 UTC, Per Nordlöw wrote:

If I have

alias N = Nullable!(T, T nullValue)

fed as template parameter to another template how can I
at compile-time get the `nullValue` ?


import std.traits;
enum nullValue = TemplateArgsOf!(N)[1];


Re: Shared, ref, arrays, and reserve template instantiation

2018-09-12 Thread Neia Neutuladh via Digitalmars-d-learn
On Wednesday, 12 September 2018 at 23:41:16 UTC, James Blachly 
wrote:
When I add the "shared" attribute to an array, I am no longer 
able to call reserve because the template won't instantiate:


Error: template object.reserve cannot deduce function from 
argument types !()(shared(int[]), int), candidates are:

/dlang/dmd/linux/bin64/../../src/druntime/import/object.d(4091):
  object.reserve(T)(ref T[] arr, size_t newcapacity)

1. Shared modifies the type, so the template does not match. 
Even casting does not seem to work however. Is there something 
about shared that makes it unable to be taken by reference?
2. Is there a workaround for me to be able to preallocate the 
array?


Kind regards


I'm guessing you tried something like:

shared char[] x;
// Doesn't work; it casts the result of x.reserve
cast(char[])x.reserve(100);
// Doesn't work; (cast(char[])x) is not an lvalue, so it 
can't be ref

(cast(char[])x).reserve(100);

Arrays are passed and stored like pointers, and `reserve` 
modifies the array, which is why the thing needs to be ref.


Anyway, it works like this:

// Cast and store in a variable so it can be ref
auto b = cast(char[]) x;
// Okay, reallocates b (changes b.ptr), doesn't change x
b.reserve(100);
// Copy changes back to the shared variable
x = cast(shared) b;



Re: Load entire file, as a char array.

2018-09-02 Thread Neia Neutuladh via Digitalmars-d-learn

On Monday, 3 September 2018 at 03:04:57 UTC, Chris Katko wrote:
This should be simple? All I want to do is load an entire file, 
and access individual bytes. The entire thing. I don't want to 
have know the file size before hand, or "guess" and have a 
"maximum size" buffer.


So far, all google searches for "dlang binary file read" end up 
not working for me.


Thank you.


http://dpldocs.info/experimental-docs/std.file.read.1.html

import std.file : read;
auto bytes = read("filename");

This gives you a void[], which you can cast to ubyte[] or char[] 
or whatever you need.


Re: How to use listener.d example?

2018-08-31 Thread Neia Neutuladh via Digitalmars-d-learn

On Friday, 31 August 2018 at 07:38:54 UTC, Marcin wrote:

https://github.com/dlang/dmd/blob/master/samples/listener.d

Can some one add more comment to that example?

I need to make code that connects to local application, very 
similar to this.


Assumptions:
1. Create an application that listens to arguments.
2. Create an application that will send arguments to the 
application mentioned above.
3. The application will return the sine (argument) to the 
client.

4. All communication must be realized via console.


Another, more structured way to do this is with an RPC framework 
like Apache Thrift. With Thrift, you'd write an interface 
description:


---
namespace d math.api
service Sine
{
  double sine(1: double value);
}
---

In your application, you'd have something like:

---
import vibe.d;
import vibethrift;
import math.api.Sine;

class SineImpl : Sine
{
  double sine(double value)
  {
static import std.math;
return std.math.sin(value);
  }
}
void main()
{
  serve!Sine(new SineImpl, "0.0.0.0", );
  return runApplication();
}
---

Then you use the corresponding Thrift client to make requests 
against it.


You could also do this with Vibe and REST:

---
import vibe.d;
class Sine
{
  @path("/sine")
  string getSine(double value)
  {
static import std.math;
import std.conv : to;
return std.math.sin(value).to!string;
  }
}
void main()
{
  auto settings = new HTTPServerSettings;
  settings.port = ;
  auto router = new URLRouter;
  router.registerWebInterface(new Sine);
  listenHTTP(settings, router);
  runApplication();
}
---

And then you can point your browser at 
http://localhost:/sine?value=1.5 and get back 0.997495. You 
can similarly use std.net.curl to make the request.


But let's say you want to do everything yourself.

That script is the server. Line 55 is the thing that handles the 
input. You need to put your code there.


The remote application might send input in multiple packets. That 
means you have to collect input somewhere and figure out where 
the end is. You can either pass a length as the first part 
(usually a 4-byte value in network byte order), or require a 
special character to terminate the commend (I recommend the ASCII 
Record Separator character, U+001E, or the like), or know enough 
about your input to figure out where it ends anyway.


Once you get the end of your input, you send it off somewhere to 
parse and process. It's up to you how you want to send numbers 
across. When you're done, you need to convert the output numbers 
back to bytes somehow and send them back with socket.send(), and 
then you close the connection.


Once you've got that working, you need to write a client that 
does pretty much the same thing, but Socket.connect instead of 
the bind/listen/accept business, and you can just use Socket.read 
for the response rather than dealing with a SocketSet.


Re: extern __gshared const(char)* symbol fails

2018-08-31 Thread Neia Neutuladh via Digitalmars-d-learn

On Friday, 31 August 2018 at 06:20:09 UTC, James Blachly wrote:

Hi all,

I am linking to a C library which defines a symbol,

const char seq_nt16_str[] = "=ACMGRSVTWYHKDBN";

In the C sources, this is an array of 16 bytes (17 I guess, 
because it is written as a string).


In the C headers, it is listed as extern const char 
seq_nt16_str[];


When linking to this library from another C program, I am able 
to treat seq_nt16_str as any other array, and being defined as 
[] fundamentally it is a pointer.


When linking to this library from D, I have declared it as:

extern __gshared const(char)* seq_nt16_str;

***But this segfaults when I treat it like an array (e.g. by 
accessing members by index).***


I believe this should be extern extern(C)? I'm surprised that 
this segfaults rather than having a link error.


A bare `extern` means "this symbol is defined somewhere else".

`extern(C)` means "this symbol should have C linkage".

When I try it with just `extern`, I see a link error:

scratch.o: In function `_Dmain':
scratch.d:(.text._Dmain[_Dmain]+0x7): undefined reference to 
`_D7scratch5cdataPa'

collect2: error: ld returned 1 exit status
Error: linker exited with status 1




Re: Are properties mature enough?

2018-08-19 Thread Neia Neutuladh via Digitalmars-d-learn

On Sunday, 19 August 2018 at 18:32:17 UTC, QueenSvetlana wrote:

In the D Style Guide, it says:

Properties
https://dlang.org/dstyle.html#properties

Functions should be property functions whenever appropriate. In 
particular, getters and setters should generally be avoided in 
favor of property functions. And in general, whereas functions 
should be verbs, properties should be nouns, just like if they 
were member variables. Getter properties should not alter state.


In the Properties function section, it says:

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

WARNING: The definition and usefulness of property functions is 
being reviewed, and the implementation is currently incomplete. 
Using property functions is not recommended until the 
definition is more certain and implementation more mature.


So which is it?


The `@property` annotation might not remain in the language. 
However, the property call syntax for functions will remain.


So you can write:

---
struct Random
{
  private int value;
  int next() { value++; return value; }
  void seed(int value) { this.value = value; }
}

Random r;
r.seed = 21;
writeln(r.next);
---

That's going to work forever.

You *could* add @property to the next and seed functions. That 
forces people to use them as fields. However, there's some 
discussion about how that's going to be handled in the future. So 
you might want to leave it off.


Re: Dub project has both .sdl and .json files. Is this normal or did I do something wrong?

2018-08-04 Thread Neia Neutuladh via Digitalmars-d-learn

On Friday, 3 August 2018 at 19:41:32 UTC, Bastiaan Veelo wrote:
But if you commit it, and a compiler deprecation causes a 
dependency in that pinned version to fail to compile, then your 
app won't compile either, even though your code itself does not 
suffer from the deprecation and even though a newer release of 
the dependency is available that solves the deprecations. This 
means that, if your app is on code.dlang.org, people won't be 
able to dub fetch && dub run.


This is also true if the dependency gets a major version bump and 
then gets updated for a breaking compiler change.


If the dependency range is broad enough, you can `dub upgrade && 
dub run`.


What advantages does committing dub.selections.json have that 
outweigh this disadvantage?


Dependencies don't always follow semantic versioning. For 
instance, a binding for a C library that is actively developed 
might reasonably follow the bound library's versioning. Or the 
maintainer might make a mistake and commit a breaking change 
without bumping to a new major version.


This is why my top-level projects these days have specific 
versions of dependencies rather than the more commonly used 
ranges. I'm only going to test against those specific versions, 
so why should I claim that my application can use future versions?


It would be OK if dub.selections.json would also pin the 
compiler version and there were a standard way to select that 
version (like dvm, but without its shortcomings).


That would be good. If I were less lazy, I could add that to dub. 
It already manages packages; the compiler is just a slightly 
different dependency.


  1   2   >