Re: Interested in D, spec confuses me.

2016-02-02 Thread anonymous via Digitalmars-d

On 02.02.2016 20:50, Bambi wrote:

Making the return value immutable is a very different thing from making
every value of the object immutable to the method alone.


Sure it's a different thing, but the meaning of "immutable" is the same.

By the way, it's not that the object's fields are made immutable for the 
method, but the method can only be called on immutable objects.



These are
different meanings. It reads like a redundancy but has different
meanings. This isn't good in my eyes.


I don't see how it reads like a redundancy. Surely, you don't expect a 
redundancy in this:


void f(immutable int[] a, immutable int[] b);

The other signature is no different. Two occurrences of "immutable", 
applying to two different things.


I agree that it can be unclear to newbies what exactly is immutable when 
a method is marked immutable, but the meaning of the keyword is the same 
as elsewhere. Using another word there would be more confusing.


questions about NetBSD port

2016-02-02 Thread Nikolay via Digitalmars-d
I am porting LDC/phobos/druntime to NetBSD. Currently my patch is 
merged into LDC master. I have several questions about 
phobos/druntime and general workflow.
As I can understand I should prepare pull requests for 
phobos/druntime master branches. LDC team will merge/cherry-pick 
changes into ldc branch from master later. Is it correct 
workflow?  Because it means that I can’t check my patch: there is 
no dmd compiler for NetBSD + phobos/druntime master branches.


Also I have a set of issues with real (long double) type. Several 
functions absent in NetBSD for real type (more specific - they 
are just aliases for functions with double). Other functions 
return less accurate values.

I have to disable a couple unit tests for NetBSD.
E.g. std/conv.d:2835 assert(to!string(r) == 
to!string(real.min_normal))
see related question:  
http://stackoverflow.com/questions/35090322/netbsd-long-double-trouble
But also there are a set of unit tests where I have to reduce 
accuracy. This problem affects std/internal/math/gammafunction.d, 
std/math.d, std/numeric.d, std/complex.d

E.g.  std/complex.d:792
assert(sin(complex(2.0L, 0)) == std.math.sin(2.0L));
I replace with:
assert(feqrel(sin(complex(2.0L, 0)).re, std.math.sin(2.0L)) > 
real.mant_dig-10);
My question is: should I wrap such changes with version(NetBSD) 
statement or it is acceptable reduce accuracy for all platforms?


PS
You can look to my code here (netbsd_patch branch):
https://github.com/nrTQgc/druntime
https://github.com/nrTQgc/phobos




Re: DMD OSX / Segfault 11

2016-02-02 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/2/16 1:06 PM, Robert M. Münch wrote:

I have a very strange effect, I'm not sure what it is about:

Value: {}

WordV: Value {
 Value* get() {}
}

BaseOperator: Value : {
}


Now comes the code using this:

auto op = cast(BaseOperator)(Word.get());
if (op !is null) {...


If get() returns "Value*" it segfaults, if I change it to "Value" it
works. How can this be?

I want to check of the Value returned from get() is a BaseOperator or not.



If this is valid D, I'm not sure what it means :)

-Steve


Re: Interested in D, spec confuses me.

2016-02-02 Thread Steven Schveighoffer via Digitalmars-d

On 2/2/16 2:50 PM, Bambi wrote:

On Tuesday, 2 February 2016 at 15:48:02 UTC, anonymous wrote:

"immutable" is not a homonym here. It means the same thing ("cannot
ever change"). And it's not redundant either, as the two instances
apply to different targets. It's clear what the first "immutable" ties
to: It qualifies the return type. The second one is less clear: It
qualifies the type of the object, meaning the method can only be
called on an immutable object.

Leaving either of them out changes the meaning of the signature:
`int[] bar() immutable {}` - Return type is mutable now.
`immutable(int[]) bar() {}` - Object type is mutable now. I.e., this
method can be called on a mutable object, and it cannot be called on
an immutable object.


Making the return value immutable is a very different thing from making
every value of the object immutable to the method alone. These are
different meanings. It reads like a redundancy but has different
meanings. This isn't good in my eyes.


Technically, it doesn't *make* it immutable, it is just an overload that 
accepts an immutable object. I like to think of a method like this:


immutable(int)[] bar() immutable

as a function that looks like this:

immutable(int)[] bar(immutable(Object) this)

If you tried to call this method on a mutable object, and there wasn't a 
mutable overload (i.e. without an attribute), the call would fail.




Also it's not so much an issue of clarification - well, the extern one
is, I genuinely didn't understand what the documentation meant - but it
is an issue of the design choices not making much sense to me. These
just stand out to me as unnecessarily confusing and obscure in an
otherwise nice and clear language.


A lot of things in D come from C++. This is how C++ specifies const methods.

The purpose is to be familiar to C++ developers, and to make porting easier.

This means it can look confusing as not all C/C++ decisions were the 
best. However, this one I happen to like -- I can't think of a better way.


-Steve


Re: reduce -> fold?

2016-02-02 Thread Andrei Alexandrescu via Digitalmars-d

On 2/2/16 11:02 AM, Atila Neves wrote:

On Friday, 29 January 2016 at 12:08:01 UTC, Andrei Alexandrescu wrote:

As has been discussed before there's been discussion about
std.algorithm.reduce taking the "wrong" order of arguments (its
definition predates UFCS). I recall the conclusion was there'd be
subtle ambiguities if we worked reduce to implement both orders.

So the next best solution is to introduce a new name such as the
popular "fold", and put them together in the documentation.


Thoughts?

Andrei


Definitely yes.


Atila, wanna do the honors? -- Andrei



Re: Linking C libraries with DMD

2016-02-02 Thread jmh530 via Digitalmars-d-learn

On Friday, 22 January 2016 at 04:43:52 UTC, Mike Parker wrote:

[snip]


Thanks again for your help. I've worked through some simple 
examples and started trying to write a binding to a C library.


I think I've got the .h file converted properly (the D file 
compiles), but I was getting a linking error. The enums were 
showing up, but not the functions. I tried creating a simple 
project that mimics what was happening in the C library and found 
no issues.


I think I narrowed it down to what is causing the linking error. 
I had not compiled the C dll myself. Looking in to the issue, I 
noticed it was compiled with MinGW. There were instructions for 
using it with Visual Studio (to make the .def and .dll files into 
a .lib) though and I assumed following those was sufficient. 
However, based on what you've said, I suspect that if I 
re-compile the dll using Visual Studio, then it will work with D.


I don't think I would have figured that out without your comments 
above.


Re: Better docs for D (WIP)

2016-02-02 Thread Andrei Alexandrescu via Digitalmars-d-announce

On 1/31/16 6:14 AM, Rory McGuire via Digitalmars-d-announce wrote:

If you don't get a cease and desist letter from the D Foundation soon
I'd be surprised.


Please. Let's take this a notch or three down. -- Andrei



Re: This feels wrong

2016-02-02 Thread Steven Schveighoffer via Digitalmars-d

On 2/2/16 10:21 AM, Shachar Shemesh wrote:

On 02/02/16 17:00, Steven Schveighoffer wrote:


Just put try around the opApply specific parts you want to monitor.
Don't guard the call to dg.

The call to dg is, obviously, part of a loop. That whole loop body is
inside a try/catch.


I don't see a big difference from this:

int opApply( scope int delegate(int) dg ) {
foreach(int i; 0 .. 50) {
int res = dg(i);
try {
if( res!=0 ) {
writefln("Delegate returned %s", res);
return res;
}
} catch(Exception ex) {
writefln("Caught in loop: %s", ex.msg);
}
}

return 0;
}


My problem isn't so much the actual how to solve it, but rather that it
is a potential pitfall when implementing that I don't think is documented.


OK, I understand what you are saying. It could be listed in the docs as 
something to avoid.


-Steve



Re: Determine type of property

2016-02-02 Thread NX via Digitalmars-d-learn
On Tuesday, 2 February 2016 at 03:36:25 UTC, Steven Schveighoffer 
wrote:

int y() { return 1;}


No need for meta-programming hackery, mark it as @property:

int y() @property { return 1;}



Re: This feels wrong

2016-02-02 Thread Ali Çehreli via Digitalmars-d

On 02/02/2016 07:21 AM, Shachar Shemesh wrote:

> it is a potential pitfall when implementing that I don't think is
> documented.

Good catch! Please either open a documentation bug for this or fork the 
repo and fix it yourself. :) (Hopefully, there is an 'Improve this page' 
link on that page.)


Ali



Re: Interested in D, spec confuses me.

2016-02-02 Thread Bambi via Digitalmars-d

On Tuesday, 2 February 2016 at 15:48:02 UTC, anonymous wrote:
"immutable" is not a homonym here. It means the same thing 
("cannot ever change"). And it's not redundant either, as the 
two instances apply to different targets. It's clear what the 
first "immutable" ties to: It qualifies the return type. The 
second one is less clear: It qualifies the type of the object, 
meaning the method can only be called on an immutable object.


Leaving either of them out changes the meaning of the signature:
`int[] bar() immutable {}` - Return type is mutable now.
`immutable(int[]) bar() {}` - Object type is mutable now. I.e., 
this method can be called on a mutable object, and it cannot be 
called on an immutable object.


Making the return value immutable is a very different thing from 
making every value of the object immutable to the method alone. 
These are different meanings. It reads like a redundancy but has 
different meanings. This isn't good in my eyes.


Also it's not so much an issue of clarification - well, the 
extern one is, I genuinely didn't understand what the 
documentation meant - but it is an issue of the design choices 
not making much sense to me. These just stand out to me as 
unnecessarily confusing and obscure in an otherwise nice and 
clear language.


Re: reduce -> fold?

2016-02-02 Thread Andrei Alexandrescu via Digitalmars-d

On 1/30/16 1:08 PM, David Nadlinger wrote:

On Saturday, 30 January 2016 at 17:40:38 UTC, Andrei Alexandrescu wrote:

I forgot the distinction between currying and partial application. Can
we also define currying in current D? -- Andrei


Currying is turning (A, B, C) -> D into A -> (B -> (C -> D)), i.e. a
function with multiple arguments into a sequence of functions that each
take a single argument to apply each.

I think I've implemented something like that for fun once, but never
really found much use for it. In the few places where I could have used
it (mostly binary functions), just using a lambda and partial
application seemed to be much more idiomatic. I guess D lacks any idioms
that would make its use come naturally.

  - David


Thanks. I guess it'd be nice to have it on code.dlang.org somewhere so 
people can play with it. -- Andrei


Re: Interested in D, spec confuses me.

2016-02-02 Thread H. S. Teoh via Digitalmars-d
On Tue, Feb 02, 2016 at 07:50:57PM +, Bambi via Digitalmars-d wrote:
> On Tuesday, 2 February 2016 at 15:48:02 UTC, anonymous wrote:
> >"immutable" is not a homonym here. It means the same thing ("cannot
> >ever change"). And it's not redundant either, as the two instances
> >apply to different targets. It's clear what the first "immutable"
> >ties to: It qualifies the return type. The second one is less clear:
> >It qualifies the type of the object, meaning the method can only be
> >called on an immutable object.
> >
> >Leaving either of them out changes the meaning of the signature:
> >`int[] bar() immutable {}` - Return type is mutable now.
> >`immutable(int[]) bar() {}` - Object type is mutable now. I.e., this
> >method can be called on a mutable object, and it cannot be called on
> >an immutable object.
> 
> Making the return value immutable is a very different thing from
> making every value of the object immutable to the method alone. These
> are different meanings. It reads like a redundancy but has different
> meanings. This isn't good in my eyes.
[...]

It's an unfortunate historical accident that function attributes can
easily be conflated with return type attributes. Different people have
pushed for prohibiting (apparently) ambiguous cases, but so far Walter
has been resistant to the idea. Because of this, my own recommendation
is to always use parenthesis when writing type qualifiers, and always
write function attributes on the right rather than on the left:

struct S {
// Do write:
immutable(int) func() { ... }
int func() immutable { ... }
immutable(int) func() immutable { ... }

// Don't write:
immutable int func() { ... }
immutable immutable int func() { ... } // may not compile
}

I'd even recommend using parenthesis in variable declarations, just for
consistency's sake:

// Do write:
immutable(int) x;

// Don't write:
immutable int x;

Even though the two are identical, I think it's better to always write
parentheses so that you get into the habit of thinking of the type in
terms of parentheses, and don't get confused when you encounter
ambiguous cases (or at least you'll be on the alert when parentheses are
absent, and be sure read the function signature more carefully).


T

-- 
Debian GNU/Linux: Cray on your desktop.


Re: Vision for the first semester of 2016

2016-02-02 Thread Andre Polykanine via Digitalmars-d-announce
PvDda> I hope D GUI will be usable some day for me and other people not
PvDda> wanting to fight with tools (and external libraries).

Oh  yeah!  I  find  this  library  the  most  adequate  (and  the most
accessible, btw). But unfortunately it seems abandoned :(.


Andre



Re: The Quick Mom Algorithm

2016-02-02 Thread Ivan Kazmenko via Digitalmars-d
On Friday, 29 January 2016 at 22:47:44 UTC, Andrei Alexandrescu 
wrote:

http://dpaste.dzfl.pl/05a82699acc8

While thinking of MoM and the core reasons of its being slow 
(adds nice structure to its input and then "forgets" most of it 
when recursing), I stumbled upon a different algorithm. It's 
much simpler, also deterministic and faster than MoM for many 
(most?) inputs. But it's not guaranteed to be linear. After 
having pounded at this for many hours, it is clear that I am in 
need of some serious due destruction. I call it a "quick median 
of medians" or in short "quick mom".


The code does not compile when I try to use topN, as medianOfUpTo 
is not present.  Please include it.


Anyway, for now, I just wanted to quickly check whether my 
previous attack on topN would have any effect here.


I've replaced the line
if (r.length <= 5) return medianOfUpTo!(5, lp)(r);
with a quick fix:
if (r.length == 2)
{
if (!less (r.front, r.back)) swap (r.front, r.back);
return 0;
}
if (r.length == 1) return 0;

Here is the code (just glued together the two snippets):
http://dpaste.dzfl.pl/f648a600a11d

Turns out like maybe it does have its effect (size = 5 million):

building Element array: 2442 msecs
checking Element array: 2432 msecs
checking int array: 388 msecs
checking random int array: 140 msecs
checking increasing int array: 41 msecs
checking decreasing int array: 42 msecs

The int array built by the attack makes the program run slower 
than a random array, and the ratio increases with size.




Utah Meetup group

2016-02-02 Thread Alex Herrmann via Digitalmars-d-announce

Hello D programmers,

I'm trying to get a Utah D meetup started, if you're interested, 
let me know here ( 
https://docs.google.com/forms/d/13Y8S0aBntCiEGxiCXyCrPwjdG1h3zRXOxCpyzN95U6s/viewform ), and I'll email everyone who replied in a week or so about the numbers, and the next step if there's a good amount of demand.


Thanks, Alex


Re: Interested in D, spec confuses me.

2016-02-02 Thread IceCreamEater via Digitalmars-d

On Tuesday, 2 February 2016 at 20:17:20 UTC, H. S. Teoh wrote:
On Tue, Feb 02, 2016 at 09:13:41PM +0100, anonymous via 
Digitalmars-d wrote: [...]
The other signature is no different. Two occurrences of 
"immutable", applying to two different things.


I agree that it can be unclear to newbies what exactly is 
immutable when a method is marked immutable, but the meaning 
of the keyword is the same as elsewhere. Using another word 
there would be more confusing.


Another way to think about it, is that the "immutable" on the 
function means that the implicit `this` reference to the object 
is immutable.



T


I thought immutable was added to the language as a better 
guarantee to 'const'. Which really tells me const wasn't cutting 
it and wasn't a proper guarantee.


Re: How would you implement this in D? (signals & slots)

2016-02-02 Thread Atila Neves via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 17:35:25 UTC, Chris Wright wrote:

On Tue, 02 Feb 2016 15:59:06 +, Atila Neves wrote:

[...]


I've seen this sort of thing before. A blogger I used to 
follow, Jeremy Miller, implemented an event broker using this 
pattern. I don't like it. It requires a new type for each 
event, and you have to defensively use that pattern even if you 
only have one event at the moment. Every time I implemented an 
event system, I've gone with named events and no special type 
for their parameters.


[...]


Nice. I liked your example and Kagamin's better than mine.

Atila


Re: Interested in D, spec confuses me.

2016-02-02 Thread Chris Wright via Digitalmars-d
On Tue, 02 Feb 2016 21:35:13 +, IceCreamEater wrote:

> On Tuesday, 2 February 2016 at 20:17:20 UTC, H. S. Teoh wrote:
>> On Tue, Feb 02, 2016 at 09:13:41PM +0100, anonymous via Digitalmars-d
>> wrote: [...]
>>> The other signature is no different. Two occurrences of "immutable",
>>> applying to two different things.
>>> 
>>> I agree that it can be unclear to newbies what exactly is immutable
>>> when a method is marked immutable, but the meaning of the keyword is
>>> the same as elsewhere. Using another word there would be more
>>> confusing.
>>
>> Another way to think about it, is that the "immutable" on the function
>> means that the implicit `this` reference to the object is immutable.
>>
>>
>> T
> 
> I thought immutable was added to the language as a better guarantee to
> 'const'. Which really tells me const wasn't cutting it and wasn't a
> proper guarantee.

D1 const (and up to about D2.007) was, if I recall, strictly for compile-
time constants.

When designing immutable, Bartosz and Walter realized that many functions 
don't care whether their parameters are mutable by anyone or not. For 
instance, the 'find' function in std.array -- it's not mutating the 
array, but it should be usable on mutable arrays.

So we got const, where all values implicitly cast to const. Functions 
promise not to modify anything marked const, so it's always safe to 
submit immutable values. They don't get access to potential optimizations 
available with immutable objects, which means they're safe for mutable 
values.


Re: reduce -> fold?

2016-02-02 Thread Atila Neves via Digitalmars-d
On Tuesday, 2 February 2016 at 20:02:39 UTC, Andrei Alexandrescu 
wrote:

On 2/2/16 11:02 AM, Atila Neves wrote:
On Friday, 29 January 2016 at 12:08:01 UTC, Andrei 
Alexandrescu wrote:

As has been discussed before there's been discussion about
std.algorithm.reduce taking the "wrong" order of arguments 
(its
definition predates UFCS). I recall the conclusion was 
there'd be
subtle ambiguities if we worked reduce to implement both 
orders.


So the next best solution is to introduce a new name such as 
the

popular "fold", and put them together in the documentation.


Thoughts?

Andrei


Definitely yes.


Atila, wanna do the honors? -- Andrei


If it's not urgent, sure.

Atila


Re: D's equivalent to C++'s std::move?

2016-02-02 Thread maik klein via Digitalmars-d
On Monday, 1 February 2016 at 13:52:49 UTC, Ola Fosheim Grøstad 
wrote:
On Monday, 1 February 2016 at 13:21:02 UTC, Shachar Shemesh 
wrote:

q = std::move(p);

I am unsure what is the correct way to do this under D.


Note that C++ std::move(...) doesn't do anything related to 
state, it is only a type cast, so it is zero-overhead.


What I have done to get semantics close to C++ is to define 
"moving" type and a "pointer" type that use it.


(I dislike how D deals with this.)


Could you share this? I would be very interested in how you have 
approached it.





Re: Interested in D, spec confuses me.

2016-02-02 Thread Jacob Carlborg via Digitalmars-d

On 2016-02-02 17:41, jmh530 wrote:


Sure, but - as this post illustrates - there are clearly sections of the
spec that could have their explanations improved.


I think the spec on "extern" [1][2] is pretty clear. I think the 
explanation of "const" and "immutable" [3] is clear as well. All of the 
sections have examples as well.


[1] http://dlang.org/spec/declaration.html#extern
[2] http://dlang.org/spec/attribute.html#linkage
[3] http://dlang.org/spec/const3.html

--
/Jacob Carlborg


Re: D's equivalent to C++'s std::move?

2016-02-02 Thread Ali Çehreli via Digitalmars-d

On 02/01/2016 05:21 AM, Shachar Shemesh wrote:

> I have a non-copyable struct with move semantics. In other words, a
> struct with @disable this(this), but with working overloads for the
> this(copy) and opAssign.
>
> Now I have an instance of that struct. I would like to be able to
> voluntarily give up ownership for the sake of another instance.
>
> In C++, I would do something like this:
>
> unique_ptr p (new int), q;
>
> q = std::move(p);
>
> I am unsure what is the correct way to do this under D.

This question has been brought up a lot lately. I've decided to look at 
this more seriously yesterday.


My first observation is that if @post-blit is disabled isn't the struct 
already a unique type? If so, we don't need unique_ptr for variables of 
that type, right? Am I completely off there?


vector is a valid use case but it's not possible with D's 
arrays because D's arrays work with .init object, which require 
assigning into.


So, I've played with an array type that can store non-copyable types. 
The main functions are emplace_back() and move_back(). One requirement 
is that the stored type must be idempotent regarding destruction of its 
.init value.


Have you used something similar before? Is this a correct approach to 
this problem?


(Pardon the non-D naming convention that uses underscores.)

/* An array that can store non-copyable types. */
struct UniqueArray(T) {
ubyte[] storage;
size_t count;

@disable this(this);

this(size_t size) {
storage = new ubyte[](size);
}

~this() {
foreach (i; 0 .. count) {
destroy_at(i);
}
}

/* Returns the address of element at index 'i'.*/
T* addressOf(size_t i) {
const offset = T.sizeof * i;
return cast(T*)(storage.ptr + offset);
}

/* Returns a range to all elements. TODO: Use operator overloading. */
auto all() {
auto arr = (cast(T*)(storage.ptr))[0..count];
T*[] result;
foreach (ref i; arr) {
result ~= 
}
return result;
}

import std.typecons : Flag, Yes, No;

/* Emplaces a new object at index 'i' with the given constructor
 * arguments. */
T* emplace_at(Flag!"occupied" occupied = Yes.occupied,
  Args...)(size_t i, Args args) {
import std.exception : enforce;
import std.conv : emplace;

enforce(i <= count);

T* place = addressOf(i);

/* TODO: Be exception-safe; don't destroy before succesful
 * construction. */
if (occupied) {
destroy_at(i);
}

emplace(place, args);
return place;
}

/* Emplaces an object at the end with the given constructor 
arguments. */

T* emplace_back(Args...)(Args args) {
if (storage.length == (count * T.sizeof)) {
storage.length += T.sizeof;
}

const isOccupied = false;
T* place = emplace_at!(No.occupied)(count, args);
++count;
return place;
}

/* Moves an lvalue to the end. The arguments becomes T.init. */
void move_back(ref T s) {
import std.algorithm : move;

T* place = emplace_back();
move(s, *place);
}

/* Destroys the element at index 'i'. */
void destroy_at(size_t i) {
destroy(*addressOf(i));
}
}

UniqueArray!S uniqueArray(S)(size_t size = 0) {
return UniqueArray!S(size);
}

/* Test code follows. */

import std.stdio;

/* A non-copyable type. */
struct S {
int i = -1;

@disable this(this);

void printInfo(string func = __FUNCTION__)() {
writefln("%s for %s", func, i);
}

this(int i) {
this.i = i;
printInfo();
}

~this() {
printInfo();

if (i == -1) {
/* This type does not do anything special for its .init 
value. */

writefln("  ... (Skipping cleanup for .init)");

} else {
writefln("  Doing proper cleanup");
}
}
}

void main() {
auto u = uniqueArray!S();

/* Some are emplaced back, some are moved back. */
foreach (i; 0 .. 5) {
if (i % 2) {
writefln("Emplacing rvalue %s back", i);
u.emplace_back(i);

} else {
writefln("Making lvalue %s", i);
auto s = S(i);
writefln("Moving lvalue %s back", i);
u.move_back(s);

assert(s == S.init);
}
}

writefln("Replacing 2 with 100");
u.emplace_at(2, 100);

writefln("Destroying %s", 1);
u.destroy_at(1);

/* Just do someting with element states. NOTE: writeln(u) does not work
 * because 'u' is not copyable. */
foreach (i, ref e; u.all) {
writefln("%s: %s", i, e.i);
}

writefln("Leaving main");
}

For convenience, here is the output of the program:

Making lvalue 0
deneme.S.this for 0
Moving lvalue 0 back
deneme.S.~this for -1
  ... (Skipping cleanup for .init)
deneme.S.~this for -1
 

Re: D's equivalent to C++'s std::move?

2016-02-02 Thread Ola Fosheim Grøstad via Digitalmars-d

On Tuesday, 2 February 2016 at 22:36:22 UTC, Ali Çehreli wrote:
This question has been brought up a lot lately. I've decided to 
look at this more seriously yesterday.


Nice to see that others are playing around with this, I don't 
have time to check your code, but one key issue with move 
semantics is exception safety.


AFAICT D's "std.move" is insufficient, as it would null out the 
original pointer prematurely and when an exception is thrown the 
resource will disappear rather than simple remain "unmoved".




Re: D's equivalent to C++'s std::move?

2016-02-02 Thread Ali Çehreli via Digitalmars-d

On 02/02/2016 03:09 PM, Ola Fosheim Grøstad wrote:

On Tuesday, 2 February 2016 at 22:36:22 UTC, Ali Çehreli wrote:

This question has been brought up a lot lately. I've decided to look
at this more seriously yesterday.


Nice to see that others are playing around with this, I don't have time
to check your code, but one key issue with move semantics is exception
safety.

AFAICT D's "std.move" is insufficient, as it would null out the original
pointer prematurely and when an exception is thrown the resource will
disappear rather than simple remain "unmoved".



Exactly. I've saved my rear end by inserting a TODO comment just before 
posting the code: :p


/* TODO: Be exception-safe; don't destroy before succesful
 * construction. */
if (occupied) {
destroy_at(i);
}

emplace(place, args);

Ali



const and immutable member variables in classes

2016-02-02 Thread Ali Çehreli via Digitalmars-d-learn

const and immutable members make structs non-assignable:

struct S {
const int c;// Makes S non-assignable
immutable int i;// Makes S non-assignable
}

void main() {
auto a = S();
auto b = S();
a = b;  // Compilation ERROR
}

(That is the same issue in C++.)

That's why I've been avoiding them altogether. However, considering that 
there is no default-assignment for classes, there is no problem with 
using const or immutable members with classes, right?


Ali


Re: D's equivalent to C++'s std::move?

2016-02-02 Thread Ola Fosheim Grøstad via Digitalmars-d

On Tuesday, 2 February 2016 at 21:18:27 UTC, maik klein wrote:
Could you share this? I would be very interested in how you 
have approached it.


My ad hoc pointer experiments try to be general and is 
convoluted, so not the best example. The basic idea is to have a 
pointer type that match "&&" in C++ (which cannot be done 
completely).


So we have something like:

struct moving(T){
   T* ptr;
  ~this(){ assert(ptr is null); } // optional check to ensure 
that the move is completed

}

then have a move() function that returns a moving!T struct

In you pointer struct you match opAssign(moving!T ...) to emulate 
"operator=(T&& ...)" and set the ptr field to null to prevent it 
from being used again (if you want that extra check).




Re: Linking C libraries with DMD

2016-02-02 Thread jmh530 via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 20:06:05 UTC, jmh530 wrote:
I suspect that if I re-compile the dll using Visual Studio, 
then it will work with D.




Yeah, this is what finally allowed me to progress.

Unfortunately, my sample example compiles, but throws an Access 
Violation error when I run it. I think I will start a new thread 
to address that.


Binding to C - Arrays and Access Violation

2016-02-02 Thread jmh530 via Digitalmars-d-learn
I'm working on generating a binding to a C library. I've got the 
.h file converted and can call some parts of the library with no 
errors. However, I have reached a stumbling block in a critical 
part.


The library requires passing function pointers to various 
functions in the library. When I try to run these functions, I 
get an Access Violation error. I enabled additional DMD warnings, 
which helped pinpoint the issue.


My D code calls a C function. One of the parameters to the C 
function is a function pointer to a D function. This D function 
(below) is one that I copied  from the C library's tutorial. I 
only slightly changed the signature. This function is eventually 
called in other functions in the C library.


double myfunc(uint n, const double* x, double* grad, void* 
my_func_data)

{
if (grad)
{
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}

The line (though likely the next will too) that causes a problem 
is


grad[0] = 0.0;

Thus, as it is an Access Violation, I'm guessing the issue is 
with accessing elements of arrays in the D function from the C 
function. I don't know. When I try to call the D function in D, 
it works, but I have to refer to x and grad as x.ptr and grad.ptr.


I'm not sure how to go about fixing this...


Re: Interested in D, spec confuses me.

2016-02-02 Thread H. S. Teoh via Digitalmars-d
On Tue, Feb 02, 2016 at 09:35:13PM +, IceCreamEater via Digitalmars-d wrote:
> On Tuesday, 2 February 2016 at 20:17:20 UTC, H. S. Teoh wrote:
> >On Tue, Feb 02, 2016 at 09:13:41PM +0100, anonymous via Digitalmars-d
> >wrote: [...]
> >>The other signature is no different. Two occurrences of "immutable",
> >>applying to two different things.
> >>
> >>I agree that it can be unclear to newbies what exactly is immutable
> >>when a method is marked immutable, but the meaning of the keyword is
> >>the same as elsewhere. Using another word there would be more
> >>confusing.
> >
> >Another way to think about it, is that the "immutable" on the
> >function means that the implicit `this` reference to the object is
> >immutable.
> >
> >
> >T
> 
> I thought immutable was added to the language as a better guarantee to
> 'const'. Which really tells me const wasn't cutting it and wasn't a
> proper guarantee.

You're misunderstanding D's type system.  Immutable is not a "better
const", as though const is somehow defective.  Perhaps the following
diagram may help to clear things up:

const
   / \
(mutable)   immutable

What this means is that both mutable and immutable are implicitly
convertible to const. Or, to put it another way, const is a kind of
"wildcard" that can point to underlying data that's either mutable or
immutable.

Mutable data is, well, mutable -- anybody who can get to it, can modify
it. Immutable means *nobody* can modify it once it's initialized.

Why const, then?  Const is useful for when a function doesn't care
whether the underlying data is mutable or not, because it doesn't need
to change the data. Const provides guarantees to the caller that the
function won't touch the data -- even if the data is actually mutable in
the caller's context.  It's a "no-mutation view" on data that's possibly
mutable by a third party.

Furthermore, since const provides actual guarantees that the called
function isn't going to touch the data, this opens up optimization
opportunities for the compiler. E.g., it can assume that any part(s) of
the data that are held in registers will remain valid after the function
call (provided said registers aren't touched by the function), so it
doesn't need to issue another load after the function returns. As a
contrived example, say you have code like this:

struct Data { int x; }
int func1(Data* d) { ... }
int func2(const(Data)* d) { ... }
...
void main() {
Data d;
int value1 = d.x*func1() + d.x;
int value2 = d.x*func2() + d.x;
d.x++;
}

When evaluating value1, the compiler may have issued a load for the
first occurrence of d.x, then it calls func1. But since func1 may modify
d.x, the second d.x needs another load in order to ensure the correct
value is used.

When evaluating value2, however, since func2 takes a const pointer to
the Data, the compiler knows the value of d.x cannot possibly change
across that function call, so it can safely reuse the value of d.x that
was previously loaded.  It may also go further and refactor the
expression as d.x*(func2() + 1), because the const guarantees that
func2 can't mutate d.x behind our backs and invalidate the result. Such
a refactoring is invalid with func1, because there is no guarantee that
d.x will have the same value after func1 returns.

Now, the same argument applies if immutable was used in place of const.
However, the last line in main() illustrates why we need const rather
than immutable in this case: we actually *want* to modify d.x in main().
We just don't want func2 to touch anything. So we can't use immutable --
since immutable means *nobody* can touch the data. So, const provides
both the guarantee that func2 won't touch the data, thus allowing the
aforementioned optimization, and also continues to let main() mutate the
data at its leisure.

As an added benefit, you can also call func2 with immutable Data: you
know it's safe, because even though func2 doesn't require immutability,
it also guarantees that it won't touch the data. So you don't need to
write two copies of func2, one to work with mutable data and one to work
with immutable data. This is why both mutable and immutable can
implicitly cast to const.


T

-- 
He who does not appreciate the beauty of language is not worthy to bemoan its 
flaws.


Re: const and immutable member variables in classes

2016-02-02 Thread anonymous via Digitalmars-d-learn

On 02.02.2016 23:48, Ali Çehreli wrote:

struct S {
 const int c;// Makes S non-assignable
 immutable int i;// Makes S non-assignable
}

void main() {
 auto a = S();
 auto b = S();
 a = b;  // Compilation ERROR
}

(That is the same issue in C++.)

That's why I've been avoiding them altogether. However, considering that
there is no default-assignment for classes, there is no problem with
using const or immutable members with classes, right?


I'm not sure what you mean by "default assignment". I'd say it works 
more simply with classes, because they're reference types. It's the same 
as using pointers to structs:


auto a = new S();
auto b = new S();
a = b; /* no problem */


Re: const and immutable member variables in classes

2016-02-02 Thread Ali Çehreli via Digitalmars-d-learn

On 02/02/2016 03:02 PM, anonymous wrote:

> I'm not sure what you mean by "default assignment".

I think I meant member-wise assignment. :)

> I'd say it works
> more simply with classes, because they're reference types. It's the same
> as using pointers to structs:
>
> auto a = new S();
> auto b = new S();
> a = b; /* no problem */

Exactly. This aspect of reference types had not occurred to me until 
recently.


Ali



Re: Interested in D, spec confuses me.

2016-02-02 Thread bubbasaur via Digitalmars-d

On Wednesday, 3 February 2016 at 00:43:36 UTC, Dicebot wrote:
Casting immutable and violating it is undefined behavior and 
once you do it all bets are off - compiler is even allowed to 
attempt formatting your hard drive when compiling this program 
:)


The fact DMD doesn't do anything scary right now when you do it 
is a mere coincidence and may change in any release with no 
notice.


Well if anything bad happen it will mess with dpaste. :)

By the way, now you and Ali are saying this isn't correct, so I 
took a look on this page: http://dlang.org/spec/const3.html


And looking on the bottom: "Implicit Conversions" - I wonder, is 
this page missing something or what? Look what I'm seeing right 
now:


http://i.imgur.com/L4a6bx6.png

It shouldn't be some circles or crosses showing the conversion on 
that table?


Bubba.



Re: reduce -> fold?

2016-02-02 Thread Andrei Alexandrescu via Digitalmars-d

On 2/2/16 3:50 PM, Atila Neves wrote:

On Tuesday, 2 February 2016 at 20:02:39 UTC, Andrei Alexandrescu wrote:

On 2/2/16 11:02 AM, Atila Neves wrote:

On Friday, 29 January 2016 at 12:08:01 UTC, Andrei Alexandrescu wrote:

As has been discussed before there's been discussion about
std.algorithm.reduce taking the "wrong" order of arguments (its
definition predates UFCS). I recall the conclusion was there'd be
subtle ambiguities if we worked reduce to implement both orders.

So the next best solution is to introduce a new name such as the
popular "fold", and put them together in the documentation.


Thoughts?

Andrei


Definitely yes.


Atila, wanna do the honors? -- Andrei


If it's not urgent, sure.


Thanks! And don't forget: in D, everything is top priority. -- Andrei




Re: Binding to C - Arrays and Access Violation

2016-02-02 Thread biozic via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 22:56:28 UTC, jmh530 wrote:
I'm working on generating a binding to a C library. I've got 
the .h file converted and can call some parts of the library 
with no errors. However, I have reached a stumbling block in a 
critical part.


The library requires passing function pointers to various 
functions in the library. When I try to run these functions, I 
get an Access Violation error. I enabled additional DMD 
warnings, which helped pinpoint the issue.


My D code calls a C function. One of the parameters to the C 
function is a function pointer to a D function. This D function 
(below) is one that I copied  from the C library's tutorial. I 
only slightly changed the signature. This function is 
eventually called in other functions in the C library.


double myfunc(uint n, const double* x, double* grad, void* 
my_func_data)

{
if (grad)
{
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}

The line (though likely the next will too) that causes a 
problem is


grad[0] = 0.0;

Thus, as it is an Access Violation, I'm guessing the issue is 
with accessing elements of arrays in the D function from the C 
function. I don't know. When I try to call the D function in D, 
it works, but I have to refer to x and grad as x.ptr and 
grad.ptr.


I'm not sure how to go about fixing this...


Is grad allocated in the D code? If so, it could have been 
collected because the GC lost track of its use when passing to 
and from the C code. Or is grad owned by the C code? If so, 
either there is a bug in the library or it's misused, because its 
memory has been freed/has never been allocated/has gone out of 
scope.






Re: Binding to C - Arrays and Access Violation

2016-02-02 Thread Mike Parker via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 22:56:28 UTC, jmh530 wrote:



My D code calls a C function. One of the parameters to the C 
function is a function pointer to a D function. This D function 
(below) is one that I copied  from the C library's tutorial. I 
only slightly changed the signature. This function is 
eventually called in other functions in the C library.


double myfunc(uint n, const double* x, double* grad, void* 
my_func_data)




Thus, as it is an Access Violation, I'm guessing the issue is 
with accessing elements of arrays in the D function from the C 
function. I don't know. When I try to call the D function in D, 
it works, but I have to refer to x and grad as x.ptr and 
grad.ptr.


I'm not sure how to go about fixing this...


The parameter to the C function should be declared as extern(C), 
and so should your function implementation.


extern(C) alias FuncPtr = double function(uint, const(double)*, 
double*, void*);

extern(C) void takeFuncPtr(FuncPtr);

extern(C) double myfunc(uint n, const(double)* x, double* grad, 
void* my_func_data) {

...
}

If you haven't done that, then this is quite possibly the root of 
your problem.





Re: Interested in D, spec confuses me.

2016-02-02 Thread Ali Çehreli via Digitalmars-d

On 02/02/2016 04:31 PM, bubbasaur wrote:

> Ok, but what would differ using immutable instead of const in your
> example (AS ARGUMENTS)?
>
> See:
>
> import std.stdio;
>
>  struct Data { int x; }
>  auto func1(Data* d) { return d.x; }
>  auto func2(const(Data)* d) { return d.x; }

I cannot trust that a member of 'd' will not be modified later on. So, I 
cannot store 'd' as is. If I want to make use of its current state 
later, I must make a copy of it (which may have its own 
member-with-inderection issues).


In short, the promise of "I will not change members of 'd'" is not 
related to what can happen to that date by other parts of the code.


>  auto func3(immutable(Data)* d) { return d.x; }

There, I know that 'd' will not change state. I can store it somewhere 
for later use; no need to copy. I can even pass it to a thread without 
needing a lock.


>  auto value2 = d.x*func2() + d.x;
>  auto value3 = d.x*func3(cast(immutable)) + d.x;

That's not very nice because we've just fooled func3(). :) Although it 
required immutable data, we've given it mutable data. The programmer is 
on his or her own at that point. We hope the program will work correctly. :)


> Functions 2 and 3 are acting in the same way

I like this explanation:

- A const parameter is a promise by the callee to not modify

- An immutable parameter is a requirement for the caller to never modify

Ali



Re: Interested in D, spec confuses me.

2016-02-02 Thread bubbasaur via Digitalmars-d

On Wednesday, 3 February 2016 at 00:41:31 UTC, Ali Çehreli wrote:

I like this explanation:

- A const parameter is a promise by the callee to not modify

- An immutable parameter is a requirement for the caller to 
never modify


Well this explanation on the matter was simple, solid and 
comprehensive enough.


Bubba.


Re: Interested in D, spec confuses me.

2016-02-02 Thread Ali Çehreli via Digitalmars-d

On 02/02/2016 04:56 PM, bubbasaur wrote:

I took a
look on this page: http://dlang.org/spec/const3.html


That table has a bunch of check marks, which happens to be a Unicode 
character: ✔.


It looks like a font issue. Perhaps we should update that page and use a 
more available character like 'x'. :p


Ali



Re: Vision for the first semester of 2016

2016-02-02 Thread Andrei Alexandrescu via Digitalmars-d-announce

On 1/29/16 11:07 AM, Adam D. Ruppe wrote:

I'd love it if you could do `import thirdparty.independent;` and it
magically works too - without even need for a configuration file or an
install command. And the docs are right there and tutorials are written
however the author feels like writing them.


I suggested that at a point, it was destroyed. -- Andrei


Re: Interested in D, spec confuses me.

2016-02-02 Thread Chris Wright via Digitalmars-d
On Tue, 02 Feb 2016 15:41:07 -0800, H. S. Teoh via Digitalmars-d wrote:

> Furthermore, since const provides actual guarantees that the called
> function isn't going to touch the data, this opens up optimization
> opportunities for the compiler.

const opens up optimizations at the call site, so it's useful. immutable 
is useful on top of const because it allows optimizations within the 
function.

Want to memoize a function? If it takes const(char[]), you have to copy 
your input and later check the entire array to see if the parameters 
match a previous call. If it takes an immutable(char[]), you can compare 
pointers.

Do you need to acquire a lock to read this data? If it's immutable, no, 
you don't.


Re: const and immutable member variables in classes

2016-02-02 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, February 02, 2016 14:48:03 Ali Çehreli via Digitalmars-d-learn 
wrote:
> const and immutable members make structs non-assignable:
>
> struct S {
>  const int c;// Makes S non-assignable
>  immutable int i;// Makes S non-assignable
> }
>
> void main() {
>  auto a = S();
>  auto b = S();
>  a = b;  // Compilation ERROR
> }
>
> (That is the same issue in C++.)
>
> That's why I've been avoiding them altogether. However, considering that
> there is no default-assignment for classes, there is no problem with
> using const or immutable members with classes, right?

Default initialization isn't really the issue. It's assignability in
general. Even if you @disabled default initialization in a struct, then
having a const or immutable member would be annoying, because you couldn't
assign it another value later. But in any case, no, classes don't have that
problem (at least not normally), because you don't assign to them. You just
assign to their references. So, you don't normally run into an issue where
you're trying to overwrite the state of a class object and aren't able to.

Now, you _can_ run into issues if you want to provide a way to overwrite the
whole state of a class object similar to assigning to a struct, but the
class would have to be specially written to support that via some kind of
non-standard function in order to support that, and you could just avoid
giving such a class any const or immutable members.

- Jonathan M Davis




DMD OSX / Segfault 11

2016-02-02 Thread Robert M. Münch via Digitalmars-d-learn

I have a very strange effect, I'm not sure what it is about:

Value: {}

WordV: Value {
Value* get() {}
}

BaseOperator: Value : {
}


Now comes the code using this:

auto op = cast(BaseOperator)(Word.get());
if (op !is null) {...


If get() returns "Value*" it segfaults, if I change it to "Value" it 
works. How can this be?


I want to check of the Value returned from get() is a BaseOperator or not.

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



Re: DMD OSX / Segfault 11

2016-02-02 Thread anonymous via Digitalmars-d-learn

On 02.02.2016 19:06, Robert M. Münch wrote:

I have a very strange effect, I'm not sure what it is about:

Value: {}

WordV: Value {
 Value* get() {}
}

BaseOperator: Value : {
}


This isn't valid D code at all, which makes it unnecessarily hard to 
understand what you mean.



Now comes the code using this:

auto op = cast(BaseOperator)(Word.get());
if (op !is null) {...


If get() returns "Value*" it segfaults, if I change it to "Value" it
works. How can this be?


A Value* is a pointer to a class reference. Unless you're doing 
something really funky with the pointer, casting it to a class type 
doesn't make sense.


Casting between class types that have an inheritance relation, like 
Value and BaseOperator, does make sense (upcat/downcast).


If anything, you should be casting between Value* and BaseOperator* 
(both pointer types) if you want to do something with pointers.


But you very seldom need pointers to class references. Just return Value 
from get, and cast to BaseOperator.


Re: Interested in D, spec confuses me.

2016-02-02 Thread H. S. Teoh via Digitalmars-d
On Tue, Feb 02, 2016 at 09:13:41PM +0100, anonymous via Digitalmars-d wrote:
[...]
> The other signature is no different. Two occurrences of "immutable",
> applying to two different things.
> 
> I agree that it can be unclear to newbies what exactly is immutable
> when a method is marked immutable, but the meaning of the keyword is
> the same as elsewhere. Using another word there would be more
> confusing.

Another way to think about it, is that the "immutable" on the function
means that the implicit `this` reference to the object is immutable.


T

-- 
"How are you doing?" "Doing what?"


Re: Interested in D, spec confuses me.

2016-02-02 Thread Era Scarecrow via Digitalmars-d

On Tuesday, 2 February 2016 at 16:41:54 UTC, jmh530 wrote:
Sure, but - as this post illustrates - there are clearly 
sections of the spec that could have their explanations 
improved.


 It's sorta why i don't refer to the spec to see how the language 
currently works, and instead refer to the D book that's the 
baseline for the D2 standard; even if it's incredibly out of 
date. Too much of the spec from when i glanced at it felt like i 
was reading a lexx/yacc definition, which is a total turn-off.


Re: const and immutable member variables in classes

2016-02-02 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Feb 02, 2016 at 09:08:07PM -0800, Jonathan M Davis via 
Digitalmars-d-learn wrote:
> On Tuesday, February 02, 2016 19:32:39 Ali Çehreli via Digitalmars-d-learn 
> wrote:
> > On 02/02/2016 07:05 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> >  > I usually tell folks not to do it because of all of the problems
> >  > it causes.
> >
> > That's been my guideline: "const and immutable members should be
> > avoided." Now I'm tempted to add this: "only in structs."
> 
> IIRC, I've pretty much always been telling folks specifically to not
> have structs with const or immutable members and haven't generally
> said anything about classes.
> 
> But I really don't see any reason to avoid it in classes at this
> point.  Maybe if a serialization mechanism were involved, it would
> matter, but the class would probably have to be designed to support
> that given that there is no equivalent to the assignment operator for
> the class objects themselves (just their references). Ultimately, it's
> the ability to overwrite the state of the object that's the problem,
> and that simply isn't an issue with class objects under normal
> circumstances.
[...]

I still can't come up with a compelling use case that would justify
using a const/immutable class member, that couldn't be done by some
other means, though. Especially since we're talking about classes, we
already have all the traditional OO mechanisms for controlling access to
members - get methods, and so on, which are more flexible and adaptable
to different use cases to begin with (e.g., can be overridden by derived
classes, can implement custom access criteria not expressible by
const/immutable, etc.), so I have a hard time justifying using
const/immutable members instead.


T

-- 
The computer is only a tool. Unfortunately, so is the user. -- Armaphine, K5


Re: Determine type of property

2016-02-02 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/2/16 2:04 PM, NX wrote:

On Tuesday, 2 February 2016 at 03:36:25 UTC, Steven Schveighoffer wrote:

int y() { return 1;}


No need for meta-programming hackery, mark it as @property:

int y() @property { return 1;}



I don't have control over S. I am passed S and need to figure out that 
it qualifies as a type I can use.


I also figured this out on my own, but for some reason my reply didn't 
go through. This is what I came up with:


template propertyType(alias x)
{
static if(is(typeof(x) == function))
alias propertyType = typeof(x());
else
alias propertyType = typeof(x);
}

-Steve


Re: Binding to C - Arrays and Access Violation

2016-02-02 Thread jmh530 via Digitalmars-d-learn

On Wednesday, 3 February 2016 at 00:28:24 UTC, biozic wrote:


Is grad allocated in the D code? If so, it could have been 
collected because the GC lost track of its use when passing to 
and from the C code. Or is grad owned by the C code? If so, 
either there is a bug in the library or it's misused, because 
its memory has been freed/has never been allocated/has gone out 
of scope.


grad is only created in the C code. I don't pass it myself.


Re: Binding to C - Arrays and Access Violation

2016-02-02 Thread jmh530 via Digitalmars-d-learn

On Wednesday, 3 February 2016 at 00:37:25 UTC, Mike Parker wrote:


The parameter to the C function should be declared as 
extern(C), and so should your function implementation.


extern(C) alias FuncPtr = double function(uint, const(double)*, 
double*, void*);

extern(C) void takeFuncPtr(FuncPtr);

extern(C) double myfunc(uint n, const(double)* x, double* grad, 
void* my_func_data) {

...
}

If you haven't done that, then this is quite possibly the root 
of your problem.


Success! Couldn't have done it without your help.

I had originally had the equivalent of FuncPtr as extern(C), but 
I had removed that because myfunc wouldn't compile. I hadn't 
thought of putting those modifications on myfunc. Just assumed 
that I did the function pointers wrong.


A few extra questions: 1) In other parts of the code I'm using 
extern(System), but that doesn't work for these. Why is extern(C) 
used for function pointers?, 2) You use const(double)*, in other 
parts of the code I had converted the C code from const char* to 
const(char*). Does it matter where the pointer * falls?


Re: const and immutable member variables in classes

2016-02-02 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, February 02, 2016 19:32:39 Ali Çehreli via Digitalmars-d-learn 
wrote:
> On 02/02/2016 07:05 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
>  > I usually tell folks not to do it because of
>  > all of the problems it causes.
>
> That's been my guideline: "const and immutable members should be
> avoided." Now I'm tempted to add this: "only in structs."

IIRC, I've pretty much always been telling folks specifically to not have
structs with const or immutable members and haven't generally said anything
about classes.

But I really don't see any reason to avoid it in classes at this point.
Maybe if a serialization mechanism were involved, it would matter, but the
class would probably have to be designed to support that given that there is
no equivalent to the assignment operator for the class objects themselves
(just their references). Ultimately, it's the ability to overwrite the state
of the object that's the problem, and that simply isn't an issue with class
objects under normal circumstances.

- Jonathan M Davis




Re: Vision for the first semester of 2016

2016-02-02 Thread Chris Wright via Digitalmars-d-announce
On Fri, 29 Jan 2016 16:07:48 +, Adam D. Ruppe wrote:

> I'd love it if you could do `import thirdparty.independent;` and it
> magically works too - without even need for a configuration file or an
> install command. And the docs are right there and tutorials are written
> however the author feels like writing them.

That's how Go does it. It's not the case that Go doing things one way 
means that you should do the opposite, but it is an indication that you 
should look for other examples before following suit.

In the case of dependencies, they should always be versioned. The 
language and standard library should be stable enough that you don't have 
to specify a version you  depend on -- though that isn't always true. So 
are you going to include a version specifier in import statements now? 
That would be awkward.


Re: questions about NetBSD port

2016-02-02 Thread Iain Buclaw via Digitalmars-d
On 2 Feb 2016 7:50 pm, "Nikolay via Digitalmars-d" <
digitalmars-d@puremagic.com> wrote:
>
> I am porting LDC/phobos/druntime to NetBSD. Currently my patch is merged
into LDC master. I have several questions about phobos/druntime and general
workflow.
> As I can understand I should prepare pull requests for phobos/druntime
master branches. LDC team will merge/cherry-pick changes into ldc branch
from master later. Is it correct workflow?  Because it means that I can’t
check my patch: there is no dmd compiler for NetBSD + phobos/druntime
master branches.
>
> Also I have a set of issues with real (long double) type. Several
functions absent in NetBSD for real type (more specific - they are just
aliases for functions with double). Other functions return less accurate
values.
> I have to disable a couple unit tests for NetBSD.
> E.g. std/conv.d:2835 assert(to!string(r) == to!string(real.min_normal))
> see related question:
http://stackoverflow.com/questions/35090322/netbsd-long-double-trouble
> But also there are a set of unit tests where I have to reduce accuracy.
This problem affects std/internal/math/gammafunction.d, std/math.d,
std/numeric.d, std/complex.d
> E.g.  std/complex.d:792
> assert(sin(complex(2.0L, 0)) == std.math.sin(2.0L));
> I replace with:
> assert(feqrel(sin(complex(2.0L, 0)).re, std.math.sin(2.0L)) >
real.mant_dig-10);
> My question is: should I wrap such changes with version(NetBSD) statement
or it is acceptable reduce accuracy for all platforms?
>
> PS
> You can look to my code here (netbsd_patch branch):
> https://github.com/nrTQgc/druntime
> https://github.com/nrTQgc/phobos
>
>

Is NetBSD similar to FreeBSD in that you have 80-bit reals but only the
first 53 bits of the mantissa are used?

I don't know how accurate LDC is when it sets up compile time float
properties.  But what do you get when:

pragma (msg, real.sizeof);
pragma (msg, real.mant_dig);

Alternatively, use a C program with printfs for:

sizeof(long double)
LDBL_MANT_DIG

To make sure both ldc and gcc are agreeable.

Have a look at rt/dmain2.d (look for fldcw) if the problem is because of
what I describe above.


Re: questions about NetBSD port

2016-02-02 Thread Iain Buclaw via Digitalmars-d
On 3 Feb 2016 8:35 am, "Joakim via Digitalmars-d" <
digitalmars-d@puremagic.com> wrote:
>
> On Wednesday, 3 February 2016 at 07:01:10 UTC, Iain Buclaw wrote:
>>
>> On 3 Feb 2016 7:30 am, "Joakim via Digitalmars-d" <
digitalmars-d@puremagic.com> wrote:
>>>
>>>
>>> On Tuesday, 2 February 2016 at 18:45:20 UTC, Nikolay wrote:


 I am porting LDC/phobos/druntime to NetBSD. Currently my patch is
merged
>>
>> into LDC master. I have several questions about phobos/druntime and
general workflow.

 As I can understand I should prepare pull requests for phobos/druntime
>>
>> master branches. LDC team will merge/cherry-pick changes into ldc branch
from master later. Is it correct workflow?  Because it means that I can’t
check my patch: there is no dmd compiler for NetBSD + phobos/druntime
master branches.
>>>
>>>
>>>
>>> You're probably better off porting dmd 2.068 first (as it's the last dmd
>>
>> written wholly in C++), using it to compile dmd git master on NetBSD,
then porting druntime and phobos master.  Porting dmd to NetBSD/x86 is
likely easy: simply follow what the other BSDs have done, as you did for
ldc.
>>>
>>>
>>
>> I doubt it. Using ldc/gdc usually means that it's just the library you
need to play with, not the compiler.
>
>
> The problem is that ldc/gdc are not on 2.069, let alone the just-released
2.070.  So as he said, if he really wants to test his druntime/phobos PRs
against master _on_ NetBSD, he has no choice but to port dmd.  I haven't
had to do so myself, but looking at how it's been done for other BSDs, it
looks fairly easy to me.

Druntime doesn't change all that much, so it's trivial to rebase to
master.  As for phobos, the only parts that matter tend to be std.math and
co.

Maybe there are some places like std.file too, but I've likely been spoiled
by using version(GNU) in places where DMD chooses to have a version branch
for each platform.  :-)


Re: TIOBE February 2016.... 15 ?!

2016-02-02 Thread cym13 via Digitalmars-d
On Wednesday, 3 February 2016 at 07:45:02 UTC, Ola Fosheim 
Grøstad wrote:

I don't think anyone takes Tiobe seriously.


I'm pretty sure nobody here does, but I know lots of people 
outside who care.
Also I find showing even little achievements good for the troop's 
morale.


I won't enter any fight, see last month's TIOBE post for the 
arguments ;)




Re: TIOBE February 2016.... 15 ?!

2016-02-02 Thread Ola Fosheim Grøstad via Digitalmars-d

On Wednesday, 3 February 2016 at 07:06:47 UTC, cym13 wrote:
It's all true, D rose up 6 positions: 
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html


I don't quite know what the leading factor for that change was 
but it sure will be great for its image.


I don't think anyone takes Tiobe seriously. Here is the search 
trend for "dlang", "golang", "swift ios" and "rust (programming 
langauge)":


https://www.google.com/trends/explore#q=dlang%2C%20golang%2C%20swift%20ios%2C%20%2Fm%2F0dsbpg6=q=Etc%2FGMT-1

golang and swift are soaring, rust is gaining ground and dlang is 
stable.




Re: My LLVM talk @ FOSDEM'16

2016-02-02 Thread deadalnix via Digitalmars-d-announce

On Monday, 1 February 2016 at 21:05:03 UTC, Kai Nacke wrote:

It was recorded. I announce when the video is online.

Regards,
Kai


Thanks, hope to see that soon :)


Re: CTFE thoughts & functional approach

2016-02-02 Thread Robert M. Münch via Digitalmars-d

On 2016-01-31 14:35:13 +, cym13 said:


I see things differently. First of all I don't see everyone trying
to do meta-programming with the same language. C++ for example has
a quite specific syntax between its arcane templates and the
preprocessor.


Well, ok, maybe a "using the same concepts as the underlaying language" 
might hit it better.



I see having the same language as a *huge* advantage. If a function
doesn't have side effects then it can be used at runtime or at
compile-time and integrated with your logic easily.


The thing I mean is not that you shouldn't be able to reference or use 
things from the "target language" but how to write down what you want 
to do. 

Code generation by building strings using the D operators for example 
is something I think is not very elegant. If I could use a list and 
build it up without having to care about the code / data difference, 
that would simplify things a lot.


Imagine we could use Lua during compile time and have access to the AST etc.



D's metaprogramming success is IMHO directly linked to it not having
a separate language for it, because it lowers the cost of learning
and using metaprogramming.


But limits you to a subset that doesn't feel very natural for doing a 
lot of common things in code-generation.


It's saying "metaprogramming isn't different from any other kind of 
programming, you can use the same tools".


Yes, and I don't think this statement holds. It's very different 
because the goal is totally different. I need a tool that allows me to 
manipulate my underlying code during compilation. The main aspect is: 
Manipulate D code.


Why not have a CTL (compile-time-language) that has access to some 
compiler internals, that follows a more functional concept? We are 
evaluating sequences of things to generate code, include / exclude code 
etc.


Having access to some compiler internals is already what is done, or I 
don't understand exactly what you mean by that.


Sure, but the question is how do to deal with it. IMO it's not very 
straight forward at the moment.



I think you should put some sort of example of how you'd want it,
because right now I don't understand. D has some nice functional
tools and they already show their strength at compile-time.


Ok, here is a simple example: I want to ensure that specific switch 
statements handle all cases for a given enum, list, etc. This is a 
common pattern and often a source of problems because you change a 
collection but miss to update all side-effecting places.


This is an example how I have done it (maybe there is a much better way 
to do it, but I didn't come up with one):


==> BEGIN

import std.conv;
import std.stdio;
import std.string;
import std.traits;

// @@example code should work with classes as well
enum A {afoo, bfoo, cfoo};

enum members1 = __traits(allMembers, A); // returns TypeTuple
auto members2 = __traits(allMembers, A);

pragma(msg, typeof(members1));
// pragma(msg, typeid(members1)); // run-time only
// static assert(is(members1 : enum)); // Error: basic type expected, not enu

pragma(msg, typeof(members2));
// pragma(msg, typeid(members2)); // run-time only


// function that generates a string which is used as a mixin at compile time
// result string must conform to syntax as it was hand-written code
string generateEnums(T...)(string type){
   string code = "enum " ~ type ~ " {";

   // this is a static foreach (compile time)
   foreach(m; T){
 debug pragma(msg, m ~ ","); // check what code we get at compile time
 code ~= m ~ ",";
   }

   return(code ~ "}");
}

int main(){
   A switch_var_a;
   final switch(switch_var_a){
 case A.afoo:
 case A.bfoo:
 case A.cfoo:
   }

   string user_input = readln();

   mixin(generateEnums!members1("B"));
   B switch_var_b = chomp(user_input).to!B; // get rid of terminating chars

   final switch (switch_var_b) {
 case B.afoo:
 {
   writeln("a");
   break;
 }
 case B.bfoo: // if commeted will cause a compiler error
 {
   writeln("b");
   break;
 }
 case B.cfoo: {writeln("c");}
   }

   return(0);
}

<== END

How about being able to write something like "ensure_final_switch B;" 
and have this call a CTF that generates the necessary code and has 
access to tool for building D structured code, AST etc.? And has a 
compile-time state I can later access in a upcoming CTF.



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

Re: CTFE thoughts & functional approach

2016-02-02 Thread deadalnix via Digitalmars-d
On Tuesday, 2 February 2016 at 08:34:38 UTC, Robert M. Münch 
wrote:

On 2016-02-01 08:15:11 +, deadalnix said:

I'm not sure what is preventing you from doing that already. 
There is compile time reflection (has access to some compiler 
internals) and D support functional style. Unless you have 
some specific in mind, I don't think there is anything we can 
do to help here. t seems you already have the pieces you want.


See my other example. Yes, maybe I can do everything already, 
but it's not straightforward. I have to fiddle around a lot to 
get it to work.


Of course that can be my incompetence with CTFE. However, my 
experience and intuition is that what I would like to use CTFE 
for (code-generation depending on some other parts of the code 
like enums, presence of member functions, etc.) can be done 
much simpler than at the moment.


That is definitely true that the compile time API is kind of 
screwy. That's definitively not you. I think the best path 
forward at this stage is to provide nice API as a library on top 
of it.


Re: CTFE thoughts & functional approach

2016-02-02 Thread Robert M. Münch via Digitalmars-d

On 2016-02-01 08:15:11 +, deadalnix said:

I'm not sure what is preventing you from doing that already. There is 
compile time reflection (has access to some compiler internals) and D 
support functional style. Unless you have some specific in mind, I 
don't think there is anything we can do to help here. t seems you 
already have the pieces you want.


See my other example. Yes, maybe I can do everything already, but it's 
not straightforward. I have to fiddle around a lot to get it to work.


Of course that can be my incompetence with CTFE. However, my experience 
and intuition is that what I would like to use CTFE for 
(code-generation depending on some other parts of the code like enums, 
presence of member functions, etc.) can be done much simpler than at 
the moment.


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



Re: CTFE thoughts & functional approach

2016-02-02 Thread Robert M. Münch via Digitalmars-d

On 2016-01-31 15:31:59 +, anonymous said:

You're conflating CTFE with the other meta programming tools here. CTFE 
is the same language as run-time D, but it doesn't have strange 
template syntax. Templates, static if, __traits, etc. have strange 
syntax, but they're sort of a different language already.


See my example in the other post. IMO what I want to achieve is a very 
simple example but the implementation I came up with is far from being 
simple.



Are you maybe wishing for a nicer alternative to templates, etc?


No, my point is that CTFE and meta-programming seems to be much simpler 
and powerful if I can use a more functional programming approach for 
it. Working with powerful lists and data = code and code = data concept 
would simplify this.


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

[Issue 15375] replace nsis installer by .msi installer

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=15375

steven kladitis  changed:

   What|Removed |Added

 CC||steven_kladi...@yahoo.com

--- Comment #1 from steven kladitis  ---
I agree the windows installer currently is pretty bad.

--


[Issue 15640] type inference in variadic array params not working for classes

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=15640

--- Comment #1 from Marc Schütz  ---
Note also that the following works, too:

class A { }
class B : A { }
class C : A { }
auto a = [new A(), new B()];
pragma(msg, typeof(a));  // A[]

--


Re: Variadic template parameters T... bounding

2016-02-02 Thread Daniel Kozak via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 13:57:54 UTC, Marc Schütz wrote:

On Tuesday, 2 February 2016 at 13:52:55 UTC, Marc Schütz wrote:
The last call should work IMO, but it doesn't. I believe 
that's a compiler bug.


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


I would say it is not a bug
test!A(new B(), new C()); // works
which is what I expected


Interested in D, spec confuses me.

2016-02-02 Thread Bambi via Digitalmars-d
I have to disclaim that I am not a very good programmer, and I am 
doing this on a hobby level.


I'm reading through the spec because D seems to be a very 
interesting language that affords lower level control than say C# 
without the syntactical mess of C++. A few things confuse me a 
lot.


1. const isn't constant
 To my mind, a const is a value that cannot change from the 
moment it is defined. But D allows for modification of const 
values through non-const references and pointers, and does not 
promise to optimize const by placing it in read only memory or 
similar. Instead, it provides immutable, which does promise an 
constant value throughout the lifetime of the value. I'm not sure 
why this distinction was created, or what const is supposed to 
accomplish here. It's just very confusing to have two keywords 
that intuitively do the same thing but don't really. Applying 
these keywords to methods would seem to make the data of the 
parent object immutable to only the function. Which might be 
useful but isn't immediately obvious from the written form.


The example snippet ' immutable(int[]) bar() immutable {} ' 
brings back bad memories of redundant declarations of the style ' 
Object object = new Object(); '. And homonyms in programming 
languages seem like a bad idea in general.


2. when is an extern an extern?
 The wiki page on interfacing with C states that C globals 
require an extra extern. The extern definition in the spec 
clarifies that extern(C) alone will copy the global into the 
current module, but that extern extern(C) will read it right from 
the C code. Or maybe it means to say that using extern(C) alone 
will only specify a different calling convention for the variable 
you are declaring. It's honestly not clear. Homonym problem again.


3. typeof is an operator, sizeof is a property
 ...but not really :^). It seems like these are similar, they 
give compile time information about the object you pass them, but 
one is implemented as a function-looking operator in the classic 
C style while another is trying to mimic member access. It lacks 
consistency. And confuses as to what is a member and what isn't. 
Let the period operator be reserved for real member access and 
other operators be their own thing.


That's all for now. I don't really understand these choices. They 
seem to only confuse rather than clarify.


Re: CTFE thoughts & functional approach

2016-02-02 Thread Robert M. Münch via Digitalmars-d

On 2016-02-02 08:39:34 +, deadalnix said:

That is definitely true that the compile time API is kind of screwy. 
That's definitively not you. I think the best path forward at this 
stage is to provide nice API as a library on top of it.


And if we do this, it's only a small step to add a functional layer to 
deal with this API where I can chain tranformations to generate my code.


My point to discuss was, that I think the combination "compile time 
API" + "compile time suited language" is something different than the 
road currently followed.


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



Re: Variadic template parameters T... bounding

2016-02-02 Thread Daniel Kozak via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 14:47:43 UTC, Marc Schütz wrote:

On Tuesday, 2 February 2016 at 14:12:54 UTC, Daniel Kozak wrote:

On Tuesday, 2 February 2016 at 13:57:54 UTC, Marc Schütz wrote:
On Tuesday, 2 February 2016 at 13:52:55 UTC, Marc Schütz 
wrote:
The last call should work IMO, but it doesn't. I believe 
that's a compiler bug.


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


I would say it is not a bug
test!A(new B(), new C()); // works
which is what I expected


if you mix ints and floats, the common type is deduced 
correctly:


this is a bug for me :). I do not like this. I am ok with (u)byte 
to int conversion and similar, but mixing float and integral 
types does not seems to be OK.


[Issue 15640] type inference in variadic array params not working for classes

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=15640

--- Comment #2 from Marc Schütz  ---
(In reply to Marc Schütz from comment #1)
> Note also that the following works, too:
> 
> class A { }
> class B : A { }
> class C : A { }
> auto a = [new A(), new B()];
> pragma(msg, typeof(a));  // A[]

... should have been:

auto a = [new B(), new C()];

But the result is just the same.

--


Re: Switch with dynamic case

2016-02-02 Thread Daniel Kozak via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 15:01:57 UTC, anonymous wrote:

On 02.02.2016 15:07, Daniel Kozak wrote:

[...]


The key thing to understand is that the foreach is a "static" 
one. A static foreach is unrolled at compile-time.


[...]


Thanks :), this is all I need to know


Re: Interested in D, spec confuses me.

2016-02-02 Thread Jacob Carlborg via Digitalmars-d

On 2016-02-02 15:36, Bambi wrote:


1. const isn't constant
  To my mind, a const is a value that cannot change from the moment it
is defined. But D allows for modification of const values through
non-const references and pointers, and does not promise to optimize
const by placing it in read only memory or similar. Instead, it provides
immutable, which does promise an constant value throughout the lifetime
of the value. I'm not sure why this distinction was created, or what
const is supposed to accomplish here. It's just very confusing to have
two keywords that intuitively do the same thing but don't really.
Applying these keywords to methods would seem to make the data of the
parent object immutable to only the function. Which might be useful but
isn't immediately obvious from the written form.


"const" is like a read-only view of data.

int a = 3;
const(int*) b = 
assert(*b == 3);
a = 4;
assert(*b == 4);
*b = 5; // Error: cannot modify const expression *b

"const" also acts like a super set of immutable and mutable data:

const(int*) a = new int;
immutable(int)* b = new int;
int* c = new int;
foo(a);
foo(b);
foo(c);

void foo(const(int*) a) {}

That would mean that "foo" will not change "a" regardless of if the 
original data is immutable, const or mutable.



The example snippet ' immutable(int[]) bar() immutable {} ' brings back
bad memories of redundant declarations of the style ' Object object =
new Object(); '. And homonyms in programming languages seem like a bad
idea in general.


The first immutable means that "bar" returns an immutable array of ints. 
The second immutable means that "bar" cannot modify the "this" reference:


class Foo
{
int a = 3;

void bar() immutable
{
a = 4; // Error: cannot modify immutable expression this.a
}
}


2. when is an extern an extern?
  The wiki page on interfacing with C states that C globals require an
extra extern. The extern definition in the spec clarifies that extern(C)
alone will copy the global into the current module, but that extern
extern(C) will read it right from the C code. Or maybe it means to say
that using extern(C) alone will only specify a different calling
convention for the variable you are declaring. It's honestly not clear.
Homonym problem again.


"extern(C)" means C linkage and calling conventions. "extern" means that 
a symbol is defined in another object file.


extern (C) int foo;

Compiling that and running the "nm" command to print the symbols will 
list "foo":


00d0 S _foo

Adding "extern" and doing the same:

extern(C) extern int foo;

Will result in this output:

U _foo

That means "foo" is undefined. That is, the linker needs to find that 
symbol in some other library.


If you create bindings to a C library, you would use "extern(C) extern". 
If you create a library in D that some C code should access you would 
use "extern(C)".,


--
/Jacob Carlborg


Re: This feels wrong

2016-02-02 Thread Shachar Shemesh via Digitalmars-d

On 02/02/16 17:00, Steven Schveighoffer wrote:


Just put try around the opApply specific parts you want to monitor.
Don't guard the call to dg.
The call to dg is, obviously, part of a loop. That whole loop body is 
inside a try/catch.


What I ended up doing, instead, was to put a flag, and the call to dg 
is, effectively:


stuff...
{
scope(failure) flags=true;
dg();
}
more stuff...

and then, the catch:

catch(Exception ex) {
if( flags )
throw ex;

other stuff...
}

My problem isn't so much the actual how to solve it, but rather that it 
is a potential pitfall when implementing that I don't think is documented.


Shachar


Re: Variadic template parameters T... bounding

2016-02-02 Thread Voitech via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 13:52:55 UTC, Marc Schütz wrote:

On Tuesday, 2 February 2016 at 13:20:33 UTC, Voitech wrote:

[...]


Two possible solutions... If you don't need to know the number 
of arguments at compile time, you can use normal variadic 
arguments:


[...]


Thank you I'll try that.


Re: Variadic template parameters T... bounding

2016-02-02 Thread Marc Schütz via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 14:55:42 UTC, Daniel Kozak wrote:

On Tuesday, 2 February 2016 at 14:47:43 UTC, Marc Schütz wrote:
if you mix ints and floats, the common type is deduced 
correctly:


this is a bug for me :). I do not like this. I am ok with 
(u)byte to int conversion and similar, but mixing float and 
integral types does not seems to be OK.


I see. But it's also consistent with array type deduction 
elsewhere:


auto a = [1, 2.5];
pragma(msg, typeof(a));  // double[]

... and more importantly:

class A { }
class B : A { }
class C : A { }
auto a = [new A(), new B()];
pragma(msg, typeof(a));  // A[]


Re: Variadic template parameters T... bounding

2016-02-02 Thread Marc Schütz via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 14:12:54 UTC, Daniel Kozak wrote:

On Tuesday, 2 February 2016 at 13:57:54 UTC, Marc Schütz wrote:

On Tuesday, 2 February 2016 at 13:52:55 UTC, Marc Schütz wrote:
The last call should work IMO, but it doesn't. I believe 
that's a compiler bug.


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


I would say it is not a bug
test!A(new B(), new C()); // works
which is what I expected


The bug is that `T` is not automatically inferred to be `A`. 
That's not a restriction of type inference in general: if you mix 
ints and floats, the common type is deduced correctly, just not 
for classes.


Re: How would you implement this in D? (signals & slots)

2016-02-02 Thread Gerald via Digitalmars-d-learn

On Monday, 1 February 2016 at 21:44:28 UTC, Enjoys Math wrote:

On Monday, 1 February 2016 at 21:40:45 UTC, Enjoys Math wrote:

module signals_and_slots;

import std.algorithm: remove;

[...]



D's signals & slots:

https://dlang.org/phobos/std_signals.html


I looked at that and perhaps I'm not reading the exampes 
correctly but I'm not sure how useful std.signals is in the real 
world. If you have a bunch of slots which take the same parameter 
types, not unusual in the GUI world, how would that work? The 
other thing that bugs me is lack of naming for slots and signals, 
again in the GUI world where you typically have dozens of these 
on an an individual widget differentiation is quite important.


For my GtkD app where I need my own events between components 
outside of the built-in GTK ones I've just been rolling my own by 
hand using delegates similar to your example. It's pretty trivial 
but admittingly there is a bunch of boilerplate I'd love to 
eliminate via templates if there is a way to address the 
weaknesses with std.signals.


Re: This feels wrong

2016-02-02 Thread Steven Schveighoffer via Digitalmars-d

On 2/2/16 4:44 AM, Shachar Shemesh wrote:

Please consider the following program:
import std.stdio;

struct A {
 int opApply( scope int delegate(int) dg ) {
 foreach(int i; 0 .. 50) {
 try {
 int res = dg(i);
 if( res!=0 ) {
 writefln("Delegate returned %s", res);
 return res;
 }
 } catch(Exception ex) {
 writefln("Caught in loop: %s", ex.msg);
 }
 }

 return 0;
 }
}

void main() {
 try {
 A a;
 foreach(i; a) {
 writefln("Loop got %s", i);

 if( i==10 ) {
 throw new Exception("Excccption");
 }

 if( i==20 ) {
 break;
 }
 }
 } catch( Exception ex ) {
 writefln("Caught outside of loop: %s", ex.msg);
 }
}

When run, I expected the loop to break after 10 iterations due to the
exception being thrown. Instead, the loop continued.

The problem with this is that, sometimes, the task generating the loop
might, itself, require exception handling. Distinguishing between the
exceptions thrown inside the delegate and outside it becomes a somewhat
tricky exercise.

At the very least, I think this behaviour should be documented.

Thoughts?


Just put try around the opApply specific parts you want to monitor. 
Don't guard the call to dg.


-Steve



Re: Switch with dynamic case

2016-02-02 Thread anonymous via Digitalmars-d-learn

On 02.02.2016 15:07, Daniel Kozak wrote:

import std.stdio;
import std.typetuple : TypeTuple;

alias cs = TypeTuple!(0, 1, 2, 3);

void main(string[] argv)
{
 switch(argv.length)
 {
 default: writeln("Uknown number of args"); break;
 foreach(c; cs)
 {
 case c: writefln("%s args", c);
 break;
 }
 }
}

This works, but I dont know why or how, is there some documentation
about this feature?


The key thing to understand is that the foreach is a "static" one. A 
static foreach is unrolled at compile-time.


So that switch code is replaced at compile time with this, almost:


switch(argv.length)
{
default: writeln("Uknown number of args"); break;

case 0: writefln("%s args", 0);
break;

case 1: writefln("%s args", 1);
break;

case 2: writefln("%s args", 0);
break;
}


"But", I hear you ask, "it breaks when I put the default at the bottom. 
What's up with that?". Yeah, that's a bit weird/buggy.


The problem is with the break statement. It applies to the foreach, not 
to the switch. And while the foreach is unrolled at compile-time, the 
break is evaluated at run-time. The generated code really looks more 
like this:



switch(argv.length)
{
default: writeln("Uknown number of args"); break;

/* start of unrolled foreach */
case 0: writefln("%s args", 0);
goto behind_foreach;

case 1: writefln("%s args", 1);
goto behind_foreach;

case 2: writefln("%s args", 0);
goto behind_foreach;
/* end of unrolled foreach */
behind_foreach:
}


So, the breaks skip past the other cases that were created by the 
foreach, but they don't actually break out of the switch.


There are at least two open issues related to this:

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

Everything works fine when breaking the switch with a label:


sw: switch(argv.length)
{
foreach(c; cs)
{
case c: writefln("%s args", c);
break sw;
}
default: writeln("Uknown number of args"); break;
}


Unfortunately, the spec is rather quiet about static foreach. And you 
won't actually find the term "static foreach". The only thing I could 
find is a little "Foreach over Tuples" section on 
, which doesn't tell a lot.


Re: chain(const(array of class)) fails

2016-02-02 Thread Marc Schütz via Digitalmars-d-learn

The constraint that fails is the one with `CommonType`:

pragma(msg, CommonType!(const(B), const(C))); // void

`CommonType` uses the `?:` operator to derive the common type:

writeln(true ? b : c);
// Error: incompatible types for ((b) : (c)): 'const(B[])' 
and 'const(C[])'

writeln(true ? b[0] : c[0]);
// Error: incompatible types for ((b[0]) : (c[0])): 
'const(B)' and 'const(C)'


At the moment I can't see a reason why that shouldn't work.


Re: CTFE thoughts & functional approach

2016-02-02 Thread Ola Fosheim Grøstad via Digitalmars-d
On Tuesday, 2 February 2016 at 08:31:07 UTC, Robert M. Münch 
wrote:
No, my point is that CTFE and meta-programming seems to be much 
simpler and powerful if I can use a more functional programming 
approach for it. Working with powerful lists and data = code 
and code = data concept would simplify this.


Ultimately a restricted deductive programming language would be 
the better option. There is no need for compile time evaluation 
to be turing complete; after all, you want the compiler to finish 
within a fixed time limit.




This feels wrong

2016-02-02 Thread Shachar Shemesh via Digitalmars-d

Please consider the following program:
import std.stdio;

struct A {
int opApply( scope int delegate(int) dg ) {
foreach(int i; 0 .. 50) {
try {
int res = dg(i);
if( res!=0 ) {
writefln("Delegate returned %s", res);
return res;
}
} catch(Exception ex) {
writefln("Caught in loop: %s", ex.msg);
}
}

return 0;
}
}

void main() {
try {
A a;
foreach(i; a) {
writefln("Loop got %s", i);

if( i==10 ) {
throw new Exception("Excccption");
}

if( i==20 ) {
break;
}
}
} catch( Exception ex ) {
writefln("Caught outside of loop: %s", ex.msg);
}
}

When run, I expected the loop to break after 10 iterations due to the 
exception being thrown. Instead, the loop continued.


The problem with this is that, sometimes, the task generating the loop 
might, itself, require exception handling. Distinguishing between the 
exceptions thrown inside the delegate and outside it becomes a somewhat 
tricky exercise.


At the very least, I think this behaviour should be documented.

Thoughts?

Shachar


Re: reduce -> fold?

2016-02-02 Thread Atila Neves via Digitalmars-d
On Friday, 29 January 2016 at 12:08:01 UTC, Andrei Alexandrescu 
wrote:
As has been discussed before there's been discussion about 
std.algorithm.reduce taking the "wrong" order of arguments (its 
definition predates UFCS). I recall the conclusion was there'd 
be subtle ambiguities if we worked reduce to implement both 
orders.


So the next best solution is to introduce a new name such as 
the popular "fold", and put them together in the documentation.



Thoughts?

Andrei


Definitely yes.

Atila


Re: Interested in D, spec confuses me.

2016-02-02 Thread anonymous via Digitalmars-d

On 02.02.2016 15:36, Bambi wrote:

The example snippet ' immutable(int[]) bar() immutable {} ' brings back
bad memories of redundant declarations of the style ' Object object =
new Object(); '. And homonyms in programming languages seem like a bad
idea in general.


"immutable" is not a homonym here. It means the same thing ("cannot ever 
change"). And it's not redundant either, as the two instances apply to 
different targets. It's clear what the first "immutable" ties to: It 
qualifies the return type. The second one is less clear: It qualifies 
the type of the object, meaning the method can only be called on an 
immutable object.


Leaving either of them out changes the meaning of the signature:
`int[] bar() immutable {}` - Return type is mutable now.
`immutable(int[]) bar() {}` - Object type is mutable now. I.e., this 
method can be called on a mutable object, and it cannot be called on an 
immutable object.


Re: How would you implement this in D? (signals & slots)

2016-02-02 Thread Atila Neves via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 14:49:21 UTC, Gerald wrote:

On Monday, 1 February 2016 at 21:44:28 UTC, Enjoys Math wrote:

On Monday, 1 February 2016 at 21:40:45 UTC, Enjoys Math wrote:

module signals_and_slots;

import std.algorithm: remove;

[...]



D's signals & slots:

https://dlang.org/phobos/std_signals.html


I looked at that and perhaps I'm not reading the exampes 
correctly but I'm not sure how useful std.signals is in the 
real world. If you have a bunch of slots which take the same 
parameter types, not unusual in the GUI world, how would that 
work?


Switch on the value inside the slot. Or use different types by 
wrapping, say, an int or a string with a struct:



import std.stdio;
import std.signals;


struct String1 { string s; }
struct String2 { string s; }

class Observer {
void watch1(String1) { writeln("watch1"); }
void watch2(String2) { writeln("watch2"); }
}

class Signals {
mixin Signal!String1;
mixin Signal!String2;
}


void main() {
auto o = new Observer;
auto s = new Signals;
s.connect();
s.connect();
s.emit(String1("foo"));
s.emit(String2("bar"));
}

The other thing that bugs me is lack of naming for slots and 
signals, again in the GUI world where you typically have dozens 
of these on an an individual widget differentiation is quite 
important.


Slots are named: the methods are slots. Signals can be named if 
you use only one struct as the parameter, as above. The signals 
would be String1 and String2, the slots watch1 and watch2.


Atila


Re: Interested in D, spec confuses me.

2016-02-02 Thread jmh530 via Digitalmars-d

On Tuesday, 2 February 2016 at 15:21:29 UTC, Jacob Carlborg wrote:

[snip]


Does it make sense to add any of this to the spec?




Re: Interested in D, spec confuses me.

2016-02-02 Thread Daniel Kozak via Digitalmars-d
Everything is there already
Dne 2. 2. 2016 17:15 napsal uživatel "jmh530 via Digitalmars-d" <
digitalmars-d@puremagic.com>:

> On Tuesday, 2 February 2016 at 15:21:29 UTC, Jacob Carlborg wrote:
>
>> [snip]
>>
>
> Does it make sense to add any of this to the spec?
>
>
>


Re: chain(const(array of class)) fails

2016-02-02 Thread Marc Schütz via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 09:51:52 UTC, Marc Schütz wrote:

The constraint that fails is the one with `CommonType`:

pragma(msg, CommonType!(const(B), const(C))); // void

`CommonType` uses the `?:` operator to derive the common type:

writeln(true ? b : c);
// Error: incompatible types for ((b) : (c)): 'const(B[])' 
and 'const(C[])'

writeln(true ? b[0] : c[0]);
// Error: incompatible types for ((b[0]) : (c[0])): 
'const(B)' and 'const(C)'


At the moment I can't see a reason why that shouldn't work.


This change broke it:
https://github.com/D-Programming-Language/dmd/pull/125

I filed a bug report:
https://issues.dlang.org/show_bug.cgi?id=15638


[Issue 14965] [REG2.031] Forward reference to inferred return type of function call when using auto return type

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=14965

Andrea Fontana  changed:

   What|Removed |Added

 CC||tri...@katamail.com

--- Comment #4 from Andrea Fontana  ---
Recursive example:

auto guessreturn(uint i)
{
if (i == 0) return 0;
else return guessreturn(i-1);
}

--


[Issue 13742] undefined reference to __coverage

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=13742

Sönke Ludwig  changed:

   What|Removed |Added

 CC||slud...@outerproduct.org

--- Comment #4 from Sönke Ludwig  ---
For completeness sake, this is what I reduced from vibe.d:

foo.d
---
import bar;
void clear() {
  void foo() {}
  performLocked!(() => foo);
}
---

bar.d
---
import core.thread;
void performLocked(alias PROC)() { assert(false); }
---

main.d
---
import foo;
void main() {}
---

dmd -lib -oflib.a bar.d foo.d -cov
dmd -oftest lib.a main.d -cov
-> lib.a(foo.o):foo.d:function
_D3bar50__T13performLockedS28_D3foo5clearFZ9__lambda2MFZvZ13performLockedMFNaNbNiNfZv:
error: undefined reference to '__coverage'

--


[Issue 15639] New: std.experimental.allocator enables abstract class instantiation

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=15639

  Issue ID: 15639
   Summary: std.experimental.allocator enables abstract class
instantiation
   Product: D
   Version: D2
  Hardware: x86_64
OS: Linux
Status: NEW
  Severity: major
  Priority: P1
 Component: phobos
  Assignee: nob...@puremagic.com
  Reporter: olivier.pis...@laposte.net

With std.experimental.allocator.make, one can instantiate an abstract class.
Calling an abstract method segfaults.

Tested with both 2.069.2 and 2.070.

import std.experimental.allocator;
import std.stdio;

abstract class Toto
{
void f()
{
writeln("f() called");
}

abstract void g();
}

void main()
{
auto toto = theAllocator.make!Toto(); 
toto.f(); // prints "f() called"
toto.g(); // segfaults
}

--


[Issue 15638] New: no common type for const classes

2016-02-02 Thread via Digitalmars-d-bugs
https://issues.dlang.org/show_bug.cgi?id=15638

  Issue ID: 15638
   Summary: no common type for const classes
   Product: D
   Version: D2
  Hardware: x86_64
   URL: https://github.com/D-Programming-Language/dmd/pull/125
OS: Linux
Status: NEW
  Severity: normal
  Priority: P1
 Component: dmd
  Assignee: nob...@puremagic.com
  Reporter: schue...@gmx.net

import std.stdio;

class A { int val; }
class B : A { this() { val = 3; } } 
class C : A { this() { val = 4; } } 

void main()
{   
const B b;
const C c;

writeln(true ? b : c);
}   

Error: incompatible types for ((b) : (c)): 'const(B)' and 'const(C)'

AFAICS there is no reason why this should be disallowed, considering that the
following works:

const A a1 = b;
const A a2 = c;

The common type should be `const(A)`.

This seems to be an unintended side-effect of this PR:
https://github.com/D-Programming-Language/dmd/pull/125

Discovered by SimonN:
http://forum.dlang.org/post/vgwdoqmdzxyegnaut...@forum.dlang.org

--


Re: This feels wrong

2016-02-02 Thread Marc Schütz via Digitalmars-d
It seems this is a natural consequence of the lowering. As such, 
I'm not surprised by the behaviour, of course under the 
assumption I - as an end user - actually know that the given 
opApply catches the exception. I guess there could be a 
recommendation in opApply's specification that implementors 
shouldn't needlessly catch exceptions, especially not unspecific 
ones like `Exception`, but if they do, they should rethrow them, 
or better yet use scope(exit/finally) and try/finally as 
appropriate.


Variadic template parameters T... bounding

2016-02-02 Thread Voitech via Digitalmars-d-learn
Hi, Is it possible to bound T... in template with some type ? For 
single Parameter declaration it can be done by T:SomeType but 
variadics does not seems to have that possibility ?

Cheers


Re: Interested in D, spec confuses me.

2016-02-02 Thread jmh530 via Digitalmars-d

On Tuesday, 2 February 2016 at 16:23:01 UTC, Daniel Kozak wrote:

Everything is there already



Sure, but - as this post illustrates - there are clearly sections 
of the spec that could have their explanations improved.


Re: How would you implement this in D? (signals & slots)

2016-02-02 Thread Chris Wright via Digitalmars-d-learn
On Tue, 02 Feb 2016 15:59:06 +, Atila Neves wrote:
> struct String1 { string s; }
> struct String2 { string s; }

I've seen this sort of thing before. A blogger I used to follow, Jeremy 
Miller, implemented an event broker using this pattern. I don't like it. 
It requires a new type for each event, and you have to defensively use 
that pattern even if you only have one event at the moment. Every time I 
implemented an event system, I've gone with named events and no special 
type for their parameters.

With std.signals, you could do this:

struct Event(TArgs...) {
  mixin Signal!TArgs;
}

class Foo {
  Event!string usernameEntered;
  Event!string passwordEntered;
  Event!(long, string) someOtherEventHappened;
  void enterPassword(string s) { passwordEntered.emit(s); }
  void enterUsername(string s) { usernameEntered.emit(s); }
}

void main() {
  auto o = new Observer;
  auto f = new Foo;
  f.usernameEntered.connect();
  f.passwordEntered.connect();
  f.enterUsername("adelhurst");
  f.enterPassword("");
}


Re: How would you implement this in D? (signals & slots)

2016-02-02 Thread Gerald via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 15:59:06 UTC, Atila Neves wrote:
Slots are named: the methods are slots. Signals can be named if 
you use only one struct as the parameter, as above. The signals 
would be String1 and String2, the slots watch1 and watch2.


What I meant is that the connect call didn't seem to tie you to a 
specific slot, it looked like it determined the slot based on the 
types which is potentially error prone. Kagamin showed an example 
of explicitly connecting to a named slot so I'm happy with that, 
I'm looking forward to re-writing my event handlers using this 
technique.


Always nice to learn something new.



Re: chain(const(array of class)) fails

2016-02-02 Thread SimonN via Digitalmars-d-learn

On Tuesday, 2 February 2016 at 10:58:35 UTC, Marc Schütz wrote:

The constraint that fails is the one with `CommonType`:
`CommonType` uses the `?:` operator to derive the common type:

I filed a bug report:
https://issues.dlang.org/show_bug.cgi?id=15638


Interesting reduced case, so it wasn't chain after all. Thanks 
for filing the issue already; also thanks to Nic for good test 
cases.


I think Adam D. Ruppe wanted to push more informative template 
errors -- they'd come in handy. :-)


-- Simon


Re: questions about NetBSD port

2016-02-02 Thread Joakim via Digitalmars-d

On Tuesday, 2 February 2016 at 18:45:20 UTC, Nikolay wrote:
I am porting LDC/phobos/druntime to NetBSD. Currently my patch 
is merged into LDC master. I have several questions about 
phobos/druntime and general workflow.
As I can understand I should prepare pull requests for 
phobos/druntime master branches. LDC team will 
merge/cherry-pick changes into ldc branch from master later. Is 
it correct workflow?  Because it means that I can’t check my 
patch: there is no dmd compiler for NetBSD + phobos/druntime 
master branches.


You're probably better off porting dmd 2.068 first (as it's the 
last dmd written wholly in C++), using it to compile dmd git 
master on NetBSD, then porting druntime and phobos master.  
Porting dmd to NetBSD/x86 is likely easy: simply follow what the 
other BSDs have done, as you did for ldc.


Also I have a set of issues with real (long double) type. 
Several functions absent in NetBSD for real type (more specific 
- they are just aliases for functions with double). Other 
functions return less accurate values.

I have to disable a couple unit tests for NetBSD.
E.g. std/conv.d:2835 assert(to!string(r) == 
to!string(real.min_normal))
see related question:  
http://stackoverflow.com/questions/35090322/netbsd-long-double-trouble
But also there are a set of unit tests where I have to reduce 
accuracy. This problem affects 
std/internal/math/gammafunction.d, std/math.d, std/numeric.d, 
std/complex.d

E.g.  std/complex.d:792
assert(sin(complex(2.0L, 0)) == std.math.sin(2.0L));
I replace with:
assert(feqrel(sin(complex(2.0L, 0)).re, std.math.sin(2.0L)) > 
real.mant_dig-10);
My question is: should I wrap such changes with version(NetBSD) 
statement or it is acceptable reduce accuracy for all platforms?


This is the same issue Win64 and Android have had.  You should 
already see version blocks for those in some places, you can do 
the same.  Take a look at my Android patches for similar tweaks 
that are still unmerged:


https://gist.github.com/joakim-noah/d936d6a339426ad1fac3
https://gist.github.com/joakim-noah/5c03801fa6c59b1e90df


Re: questions about NetBSD port

2016-02-02 Thread Iain Buclaw via Digitalmars-d
On 3 Feb 2016 7:30 am, "Joakim via Digitalmars-d" <
digitalmars-d@puremagic.com> wrote:
>
> On Tuesday, 2 February 2016 at 18:45:20 UTC, Nikolay wrote:
>>
>> I am porting LDC/phobos/druntime to NetBSD. Currently my patch is merged
into LDC master. I have several questions about phobos/druntime and general
workflow.
>> As I can understand I should prepare pull requests for phobos/druntime
master branches. LDC team will merge/cherry-pick changes into ldc branch
from master later. Is it correct workflow?  Because it means that I can’t
check my patch: there is no dmd compiler for NetBSD + phobos/druntime
master branches.
>
>
> You're probably better off porting dmd 2.068 first (as it's the last dmd
written wholly in C++), using it to compile dmd git master on NetBSD, then
porting druntime and phobos master.  Porting dmd to NetBSD/x86 is likely
easy: simply follow what the other BSDs have done, as you did for ldc.
>

I doubt it. Using ldc/gdc usually means that it's just the library you need
to play with, not the compiler.


Re: First project: questions on how-to, and on language features

2016-02-02 Thread Alex Vincent via Digitalmars-d-learn

On Sunday, 24 January 2016 at 18:52:41 UTC, Chris Wright wrote:
There is no documentation, so I have no idea what you're trying 
to achieve here. So your questions about why this isn't in 
Phobos, whether there are any other libraries that do this, and 
whether there's a way to simplify your contracts are impossible 
for me to answer.


Objections have been noted and (hopefully) corrected:
https://github.com/ajvincent/d-experiments/blob/master/IntervalMap/source/intervalmap.d

I'm going for the concept of versioning data - first a single 
value, and then members of an array.  (I haven't implemented the 
versioning of arrays yet.)  That's why I said it's an inverse of 
Phobos ranges:  each iteration call to a range could give you a 
different value.  Here, several versions can point to one value.


Feedback is still most strongly welcomed.


TIOBE February 2016.... 15 ?!

2016-02-02 Thread cym13 via Digitalmars-d
It's all true, D rose up 6 positions: 
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html


I don't quite know what the leading factor for that change was 
but it sure will be great for its image.


  1   2   >