Dhee - tiny app to learn/try out D

2015-11-10 Thread Shriramana Sharma via Digitalmars-d-learn
I wrote up a small PyQt app to help me do quick coding of snippets in D to 
help me learn how D works.

https://github.com/jamadagni/dhee

I wish there was (a working) QtD so I wouldn't need to use Python, but 
well... Looked into GtkD a bit, but somehow Gtk never clicked with me...

P.S.: I only cross-posted as I thought this is relevant to both 
announce/learn.

-- 
Shriramana Sharma, Penguin #395953


why --shebang for rdmd?

2015-11-20 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. The following code works fine for me:

#! /usr/bin/env rdmd
import std.stdio;
void main() { writeln(2); }

So what is the use of the --shebang option of rdmd? 
http://dlang.org/rdmd.html does not shed much light on this.

Thanks.

-- 
Shriramana Sharma, Penguin #395953


`finally` is redundant?

2015-11-20 Thread Shriramana Sharma via Digitalmars-d-learn
The page http://dlang.org/exception-safe.html says:

"It's try-finally that becomes redundant."

IIUC this is because we have scope(exit).

Does this mean that `finally` should eventually be removed from the 
language?

-- 
Shriramana Sharma, Penguin #395953


D equivalent of Python's try..else

2015-11-20 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. In Python one has the syntax try..except..else.. where code in the 
else clause will only be executed if an exception does not occur. (Ref: 
http://stackoverflow.com/a/22579805/1503120)

In D, is there such an idiomatic/canonical construct? The D try statement 
only seems to support finally (apart from catch).

-- 
Shriramana Sharma, Penguin #395953


Re: D equivalent of Python's try..else

2015-11-20 Thread Shriramana Sharma via Digitalmars-d-learn
rsw0x wrote:

> scope(failure) can be used to run code when an exception is
> thrown inside the scope, and scope(success) only triggers if the
> scope exited successfully
> 
> http://ddili.org/ders/d.en/scope.html

Thanks but I know that and it executes only at the point of scope exit. But 
I want some code to run immediately after the try clause but only if an 
exception did not occur.

The Python else clause is for code which should be run only if an exception 
never occurred i.e. even if one occurred and it was handled. It will be 
executed before `finally`. Is there a D equivalent?

-- 
Shriramana Sharma, Penguin #395953


Re: D equivalent of Python's try..else

2015-11-20 Thread Shriramana Sharma via Digitalmars-d-learn
Shriramana Sharma wrote:

> In Python one has the syntax try..except..else.. where code in the
> else clause will only be executed if an exception does not occur. (Ref:
> http://stackoverflow.com/a/22579805/1503120)

Official Python documentation: 
https://docs.python.org/3/reference/compound_stmts.html#try

-- 
Shriramana Sharma, Penguin #395953


Re: D equivalent of Python's try..else

2015-11-21 Thread Shriramana Sharma via Digitalmars-d-learn
Russel Winder via Digitalmars-d-learn wrote:

> else on for and while, whilst technically redundant as well, does
> occasionally make for a nicer read, for very analogous reasons. It can
> generally avoid the need for extra booleans and other state variables.

Hmm – I forgot Python has `else` for `for` and `while` too. But it's a tad 
difficult to wrap one's mind around the meaning of the word `else` in this 
particular context whereas it actually means `nobreak`. Perhaps if this were 
added to D, `default` would be a better choice of keyword, since we all know 
that `default` (as in `switch`) is not executed if `break` happens.

So:

try { code_which_can_throw(); }
catch { handler(); }
default { only_if_didnt_throw(); }
finally { mandatory(); }

How does that look?

-- 
Shriramana Sharma, Penguin #395953


%s not producing string representation of enum?

2015-12-10 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I'm using DMD 2.069.2. As per http://ddili.org/ders/d.en/enum.html 
the following code is supposed to output the *names* of the suits:

import std.stdio;
void main()
{
enum Suit { spades, hearts, diamonds, clubs }
foreach (suit; Suit.min .. Suit.max + 1) { writefln("%s", suit); }
}

But I'm getting 0 1 2 3. Kindly advise.

-- 
Shriramana Sharma, Penguin #395953


Re: %s not producing string representation of enum?

2015-12-10 Thread Shriramana Sharma via Digitalmars-d-learn
Basile B.  wrote:

> You should rather use std.traits.EnumMembers to iterate the
> members of an enum:

Wow this is great! I was thinking that enum.max + 1 is not really befitting 
D's elegant approach to programming. Ali should really update that section 
of his book to use EnumMembers. This will both help avoid the above hack and 
only then will his reference to %s and %d having different effects for enums 
be true...

Thanks once more to Ali for his book and you people for the replies!

-- 
Shriramana Sharma, Penguin #395953


Using std.math: FloatingPointControl.enableExceptions

2015-12-10 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I'm trying to figure out how to use 
FloatingPointControl.enableExceptions. Upon enabling severeExceptions I 
would expect the division by zero to be signaled, but neither do I get a 
SIGFPE nor does ieeeFlags show the exception having been signaled. What am I 
doing wrong?

import std.stdio;
import std.math;
void main()
{
FloatingPointControl fc;
fc.enableExceptions(fc.severeExceptions);
real a = 1.0 / 0.0;
writeln(ieeeFlags.divByZero);
}

-- 
Shriramana Sharma, Penguin #395953


Re: Using std.math: FloatingPointControl.enableExceptions

2015-12-11 Thread Shriramana Sharma via Digitalmars-d-learn
rumbu wrote:

> Constant folding: a is evaluated at compile time to + infinity.

Hmm... I guess the compiler figures that if someone is hardcoding that 
expression then they don't want to see an exception. Thanks for the 
explanation.

-- 
Shriramana Sharma, Penguin #395953


Re: %s not producing string representation of enum?

2015-12-11 Thread Shriramana Sharma via Digitalmars-d-learn
Ali Çehreli wrote:

> http://ddili.org/ders/d.en/enum.html#ix_enum.EnumMembers,%20std.traits

Ali that's great! Thank you!

-- 
Shriramana Sharma, Penguin #395953


AliasSeq can contain template identifier too?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d-learn
https://github.com/D-Programming-Language/phobos/blob/master/std/meta.d#L790

Looks like an AliasSeq can contain a template identifier too. So should I 
understand that AliasSeq in general can refer to any identifier and any 
value? Hitherto I thought it was any *type* and any value...

-- 
Shriramana Sharma, Penguin #395953


isTemplate and isValue?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. Re my posting just now re AliasSeq being able to contain a template 
identifier too, I wonder whether it is possible to have a std.traits 
template to identify whether something is a template or not?

In connection with this, while is() is there to determine whether something 
is a type or not, what should I use to determine whether something is a 
value or not?

These would be useful to identify the kind of a member of an AliasSeq...

-- 
Shriramana Sharma, Penguin #395953


Inferring an integer literal as ubyte

2015-12-14 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I was trying to do something like this:

ubyte code = to!ubyte(spec, 6) + 16;

and got an error saying:

cannot implicitly convert expression (cast(int)to(spec, 6) + 16) of type int 
to ubyte

Looking at http://dlang.org/spec/lex.html#IntegerLiteral, sure enough 16 is 
specified to be inferred as an `int`.

I thought that integer literals used to be inferred as the smallest integral 
type that can fit them – am I mistaken?

-- 
Shriramana Sharma, Penguin #395953


Re: Inferring an integer literal as ubyte

2015-12-14 Thread Shriramana Sharma via Digitalmars-d-learn
Adam D.  Ruppe wrote:
> but yours won't because to!ubyte(spec, 6) might just be > 240.

Thanks for that explanation. That's clear now.

-- 
Shriramana Sharma, Penguin #395953


Why should file names intended for executables be valid identifiers?

2015-12-14 Thread Shriramana Sharma via Digitalmars-d-learn
I understand that module names need to be valid identifiers in that other 
modules would need to import them. But when a file is intended to be just an 
executable, why is it mandatory to give it a module declaration with a valid 
identifier? 

For instance, hyphens are often used as part of executable names on Linux, 
but if I do this:

$ dmd usage-printer.d

I get the following error:

usage-printer.d: Error: module usage-printer has non-identifier characters 
in filename, use module declaration instead

I expect it should not be difficult for the compiler to see that this D file 
is not a module being imported by anything else or even being compiled to a 
library which would need to be later imported. In which case, why does it 
insist that the file should be given a valid module name?

-- 
Shriramana Sharma, Penguin #395953


Testing if a file is connected to a terminal

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
Is there a canonical way to test in D whether stdout/stderr (or in general, 
a std.stdio.File) refers to a terminal or not? 

https://www.google.co.in/search?q=terminal&sitesearch=dlang.org/phobos turns 
out nothing.

I knew of C's (or rather POSIX's) isatty, and after some digging I found 
isatty defined under core.sys.posix.unistd, and I suppose I can just pass to 
it the output of std.stdio.File.getFP.

Is there any other way to do the desired test? Or is this the recommended 
way?

-- 
Shriramana Sharma, Penguin #395953


No documentation for core.sys?

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
In my recent search for D's equivalent of isatty, I found out that there is 
a core.sys.posix module only by rgrepping under /usr/include/dmd. Why isn't 
there a documentation page http://dlang.org/phobos/core_sys.html whereas 
lots of other core.* modules are documented?

-- 
Shriramana Sharma, Penguin #395953


Re: No documentation for core.sys?

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
Jakob Ovrum wrote:

> As with core.stdc, refer to the
> documentation for the equivalent C header.

I only know of even core.stdc's existence since I've been poking into the 
Phobos sources. At least the Phobos documentation should mention that such 
modules exist.

I note that in the proposed library documentation, core.stdc is mentioned: 
https://dlang.org/library/index.html, but core.sys.posix is not...

[sigh] This is why D's API version is still 0, as in 2.0.69.2 (at least my 
interpretation of the weird zero-prefixed numbering being used).

-- 
Shriramana Sharma, Penguin #395953


Re: Why should file names intended for executables be valid identifiers?

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
Adam D.  Ruppe wrote:

> It still has a module name that can be used in reflection, must
> be used in name disambiguation (at the linker level if nothing
> else, any functions are mangled with the module name so they
> don't conflict with C functions with the same name), and other
> things.

Sorry but I don't get this fully: can't a hyphen be part of such mangled 
names? Aren't they just strings that the linker hashes or something? (My 
knowledge of compiler/executable internals is limited.) And any reflection 
of the module name would also be just a string which need not be a valid 
identifier no?

-- 
Shriramana Sharma, Penguin #395953


exit(1)?

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
http://dlang.org/phobos/std_getopt.html has a line in an example saying 
exit(1);

Surely this works only if core.stdc.stdlib is imported? Should the example 
be modified to show the import?

And is exit() the canonical way to exit the current process even in D?

-- 
Shriramana Sharma, Penguin #395953


Re: Testing if a file is connected to a terminal

2015-12-16 Thread Shriramana Sharma via Digitalmars-d-learn
Jakob Ovrum wrote:

> Where's the reference documentation?

There's a README: http://code.dlang.org/packages/consoled, and the source 
does seem to have DDoc comments...

-- 
Shriramana Sharma, Penguin #395953


Re: exit(1)?

2015-12-17 Thread Shriramana Sharma via Digitalmars-d-learn
Jakob Ovrum wrote:

> The example should be restructured to `return 1;`
> from `main`.

https://github.com/D-Programming-Language/phobos/pull/3875

-- 
Shriramana Sharma, Penguin #395953


function without "this" cannot be const?

2015-12-20 Thread Shriramana Sharma via Digitalmars-d-learn
I'm trying to interface to a C function:

extern(C) const char * textAttrN(const char * specString, size_t n);

and getting the error:

Error: function .textAttrN without 'this' cannot be const

Please advise as to what I'm doing wrong?! :-(

-- 
Shriramana Sharma, Penguin #395953


Re: function without "this" cannot be const?

2015-12-20 Thread Shriramana Sharma via Digitalmars-d-learn
Basile B.  wrote:

> without the parens, 'const' means that the function doesn't
> mutate the state of the object or of the struct it's declared in.
> So it's meaningless for a global function.

Thank you people.

-- 
Shriramana Sharma, Penguin #395953


C string to D without memory allocation?

2015-12-20 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I have the following code:

import std.stdio, std.conv;
extern(C) const(char) * textAttrN(const (char) * specString, size_t n);
string textAttr(const(char)[] specString)
{
const(char) * ptr = textAttrN(specString.ptr, specString.length);
writeln(ptr);
return to!string(ptr);
}
void main()
{
auto s = textAttr("w /g");
writeln(s.ptr);
}

Now I'm getting different pointer values printed, like:

7F532A85A440
7F532A954000

Is it possible to get D to create a D string from a C string but not 
allocate memory? 

I thought perhaps the allocation is because C does not guarantee 
immutability but a D string has to. So I tried changing the return type of 
textAttr to const(char)[] but I find it is still allocating for the return 
value. Is this because a slice can potentially be appended to but it may 
overflow a C buffer?

Finally, I just want to return a safe D type encapsulating a C string but 
avoid allocation – is it possible or not?

Thanks!

-- 
Shriramana Sharma, Penguin #395953


Re: C string to D without memory allocation?

2015-12-20 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

> string myCString = cast(string)ptr[0 .. strLen];

Thanks but does this require that one doesn't attempt to append to the 
returned string using ~= or such? In which case it is not safe, right?

-- 
Shriramana Sharma, Penguin #395953


Re: C string to D without memory allocation?

2015-12-20 Thread Shriramana Sharma via Digitalmars-d-learn
Jakob Ovrum wrote:

> Use std.string.fromStringz. to!string assumes that pointers to
> characters are null-terminated strings which is not safe or
> general 

I suppose what you mean is, the onus of guaranteeing that const(char)* 
refers to a null-terminated string is upon the person calling the to! 
function? Yes I understand, and Phobos documentation does say that using a 
pointer for input makes this "@system". Wouldn't it be better to just reject 
pointer as input and force people to use fromStringz?

> > (unlike std.format, which safely assumes they are
> pointers to single characters); 

I see that "%s".format(str) where str is a const(char)* just prints the 
pointer value in hex. So perhaps one should say that std.format just treats 
it like any other pointer (and not specifically that it treats it as a 
pointer to a single char)?

> > it is a poor design. fromStringz
> is explicit about this assumption.

OK thank you.

-- 
Shriramana Sharma, Penguin #395953


Deimos recommendation still official?

2015-12-21 Thread Shriramana Sharma via Digitalmars-d-learn
http://dlang.org/spec/interfaceToC.html refers one to Deimos 
(https://github.com/D-Programming-Deimos) to look for existing bindings to C 
libraries. Is this recommendation still valid? I ask because less than one 
fourth of the repos there seem to have been active in this year 2015. Or is 
it just because the other C libraries haven't changed (!)...

-- 
Shriramana Sharma, Penguin #395953


Template specialization using traits?

2015-12-21 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I want to define a template specialization using traits:

import std.stdio, std.traits;
void func(T)(T t) { writeln(1); }
void func(T)(T t) if(isIntegral!T) { writeln(2); }
void main()
{
func(1);
}

But I'm getting an error saying that the called function matches both. If it 
were a single type, I know I have to put the specialization as in:

void func(T: int)(T t) { writeln(2); }

and that works, but how to make it more generic than that?

-- 
Shriramana Sharma, Penguin #395953


Re: C string to D without memory allocation?

2015-12-21 Thread Shriramana Sharma via Digitalmars-d-learn
Jonathan M Davis via Digitalmars-d-learn wrote:

> If it isn't, all that means is that the
> array's capacity will be 0, so it's going to have to reallocate

So it's safe to return a string produced by fromStringz without having to 
worry that the user would append to it?

Then why is it marked @system? Only because one cannot be sure that the 
input point refers to a valid null-terminated string?

-- 
Shriramana Sharma, Penguin #395953


Re: Template specialization using traits?

2015-12-21 Thread Shriramana Sharma via Digitalmars-d-learn
Thanks all for your replies. One question:

Jonathan M Davis wrote:
> Alternatively, you can use static if, though you're only dealing
> with one template in that case. e.g.

But if we wanted to deprecate one of the alternatives, then we necessary 
need to declare two templates with the same name and complementary 
constraints right?

-- 
Shriramana Sharma, Penguin #395953


What other than a pointer can be converted implicitly to const(char)*?

2015-12-21 Thread Shriramana Sharma via Digitalmars-d-learn
https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L878

The `static if` condition here says if something is a pointer and if it is 
implicitly convertible to const(char)*. The isPointer! part seems 
superfluous. Is there something that is not a pointer yet implicitly 
convertible to const(char)*?

-- 
Shriramana Sharma, Penguin #395953


Is a type not a symbol?

2015-12-22 Thread Shriramana Sharma via Digitalmars-d-learn
http://dlang.org/spec/template.html#TemplateTupleParameter

says that an AliasSeq (wording needs to be updated) "is a sequence of any 
mix of types, expressions or symbols."

Is a type not a symbol? I mean, alias can refer to both, no?

-- 
Shriramana Sharma, Penguin #395953


: in template specialization vs constraint

2015-12-22 Thread Shriramana Sharma via Digitalmars-d-learn
import std.stdio;
void func(T)(T v) { writeln(1); }
void func(T: int)(T v) { writeln(2); }
void func(T)(T v) if (is(T: int)) { writeln(3); }
void main()
{
func(100);
ubyte s = 200;
func(s);
}

The above code prints 2 twice. A fwe questions:

1) At func(100) why isn't the compiler complaining that it is able to match 
two templates i.e. the ones printing 2 and 3? Is it that since the second 
one is specialized but the third one apparently isn't, the compiler just 
ignores the third one?

2) How come func(s) doesn't invoke the template that prints 3? `T: int` in 
the context of specialization means an exact match but in the context of 
constraints it means implicitly convertible, no? The specialization section 
under http://dlang.org/spec/template.html is not very clear about this IMHO.

-- 
Shriramana Sharma, Penguin #395953


CTFE with C functions not possible?

2015-12-31 Thread Shriramana Sharma via Digitalmars-d-learn
Using DMD 2.0.69.2, the following code:

extern (C) double sqrt(double x);
enum q = sqrt(4.0);

gives the error:

Error: sqrt cannot be interpreted at compile time, because it has no 
available source code

But if I do:

import std.math;
enum q = sqrt(4.0);

There is no problem. So two questions:

1) Why exactly can't the compiler call a C function at compile time whereas 
it can call a D function?

2)  ... which itself only in the end calls that very same C 
function IIANM?

I see druntime/import/core/math.d l 91:

double sqrt(double x);  /* intrinsic */

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2015-12-31 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

> It will make it very hard to split std.math up.

I have no desire to split std.math up. :-)

What I desire to do is be able to call a C library from a D template like 
octal to compute a string at compile time.

Is this possible or not?

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2015-12-31 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

>> Is this possible or not?
> 
> No, source is not available.

Why, is it because the D compiler is already linked to the C library (and 
hence knows where the functions are located and such), but not to my 
library? I mean, I even gave -L-lmylib and all that, but of course now I 
realize that that is only telling the *linker* about the lib. How do I tell 
the compiler to the lib? If Python CTypes can query and find out any library 
with the SO filename I throw at it, can't a D compiler?

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2015-12-31 Thread Shriramana Sharma via Digitalmars-d-learn
Shriramana Sharma wrote:

> What I desire to do is be able to call a C library from a D template like
> octal to compute a string at compile time.

To be more explicit, I wrote a library in C since it's much leaner size-wise 
than the D code (although admittedly much *much* more tedious to write 
especially with all those string manipulations) and since it's callable from 
other languages like Python too.

None of those other languages have CTFE AFAICS. I would like to provide at 
least the D wrapper to the C library with a template which will enable CTFE 
computation via the library (it's just a string to string conversion). But 
the D compiler is complaining that it cannot call the C function at compile 
time even though the library is installed under /usr/local/lib and Python is 
able to access it via CTypes.

Please help!

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2015-12-31 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

> You misunderstand, its hardcoded into the CTFE evaluator. That is what
> an intrinsic is.

What do you mean hardcoded into the CTFE evaluator? Surely you aren't 
suggesting that the D compiler contains its own implementation of the 
functions already implemented in libc?

-- 
Shriramana Sharma, Penguin #395953


@property not available for classes?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I'm trying the following code:

import std.stdio;
class TimeSpan
{
immutable double start, end;
@property double length() { return end - start; }
}
void main()
{
auto p = TimeSpan(1, 2);
writeln(p.length);
}

...and I'm getting the error:

Error: no property 'opCall' for type '.TimeSpan'

If I change the class to struct the @property is callable without parens but 
I need TimeSpan to be a class since I need to inherit from it.

http://dlang.org/property.html and 
http://dlang.org/spec/function.html#property-functions don't say anything 
about @property not being applicable for classes. 

Am I stuck with having to use the () for this even in D?

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

> Either port it to D and extern(C) it so it is accesible from other
> languages or not have CTFE support.

I already wrote it in D, then I ported to C with much effort. The option to 
extern(C)-ing it didn't occur to me. :-( Also, the D version is really much 
too bulky.

I suppose I could always maintain both the C and D versions separately.

-- 
Shriramana Sharma, Penguin #395953


Why can't a Regex object be immutable?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. With this code:

import std.stdio, std.regex;
void main()
{
immutable numbers = regex(r"\d+");
foreach (match; "a1b2c3d4e5".matchAll(numbers))
writeln(match[0]);
}

compiling gives the error:

(4): Error: cannot implicitly convert expression (regex("\\d+", "")) of 
type Regex!char to immutable(Regex!char)
(5): Error: template std.regex.matchAll cannot deduce function from 
argument types !()(string, immutable(Regex!char)), candidates are:
/usr/include/dmd/phobos/std/regex/package.d(859):
std.regex.matchAll(R, RegEx)(R input, RegEx re) if (isSomeString!R && 
is(RegEx == Regex!(BasicElementOf!R)))
/usr/include/dmd/phobos/std/regex/package.d(867):
std.regex.matchAll(R, String)(R input, String re) if (isSomeString!R && 
isSomeString!String)
/usr/include/dmd/phobos/std/regex/package.d(874):
std.regex.matchAll(R, RegEx)(R input, RegEx re) if (isSomeString!R && 
is(RegEx == StaticRegex!(BasicElementOf!R)))

If I use `auto` all is fine. Why is it impossible for a Regex object to be 
`immutable`?

-- 
Shriramana Sharma, Penguin #395953


Re: Why can't a Regex object be immutable?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
Shriramana Sharma wrote:

> Why is it impossible for a Regex object to be
> `immutable`?

I find that I can't declare it as `const` either... This is most curious!

-- 
Shriramana Sharma, Penguin #395953


Re: @property not available for classes?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
John wrote:

> It's nothing to do with the @property attribute. So you need to
> define a constructor. Also, use "new" when creating instances.

Thanks Simon and John. First actual usage of D classes and mistaken 
assumption that C++ syntax is valid. :-)

-- 
Shriramana Sharma, Penguin #395953


Why isn't field-wise constructor automatic for structs and not classes?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
If I have:

struct TimeSpan { double start, end; }

Then both the following automatically work:

auto s = TimeSpan();
auto t = TimeSpan(1, 2);

But if I make it a class (I need to) then I have to explicitly define a 
field-wise constructor else only a constructor with no args is automatically 
defined. Why can't the field-wise functionality be automatic for classes 
too?

-- 
Shriramana Sharma, Penguin #395953


Re: Why can't a Regex object be immutable?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
cym13 wrote:

> I think it's because regex() only compiles the regex at runtime
> so it needs to be modified later ; 

Aw come on. The immutability of the variable is *after* it has been created 
at runtime.

> > you'll find that using
> ctRegex() instead will allow you to declare it immutable for
> example. I didn't look at the implementation to identify a
> precise cause though.

You mean ctRegex!(), but nope:

immutable numbers = ctRegex!r"\d+";

or doing const there gives the same error and using auto doesn't.

-- 
Shriramana Sharma, Penguin #395953


Re: CTFE with C functions not possible?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
Rikki Cattermole wrote:

> How exactly is a D version more bulky then C?
> After all everything C can do, D can do with a very similar syntax.

Source-code wise D is much leaner than C, obviously, but object-code wise it 
is *huge* even with dynamically linking Phobos:

The binary size of compiling my C version is 20271 and that of the D version 
with exact same functionality is 1031061. 

I thought maybe it's because I'm using a few ctRegex-es and that's getting 
included into the source code, but using ordinary regex actually increases 
the size to 1112343.

I suppose 1 MB is not a big deal these days, and if I cared about quick 
programming and not worry about buffer overflows, I have to sacrifice 
*something*, but still comparing to C, I can't help but feel that most of 
that 1 MB is functionality that the program never uses but I'm not expert 
enough to find out. If DMD had something like -fdata-sections -ffunction-
sections, passing --gc-sections might be able to slim that down, I dunno...

-- 
Shriramana Sharma, Penguin #395953


Re: Why can't a Regex object be immutable?

2016-01-01 Thread Shriramana Sharma via Digitalmars-d-learn
cym13 wrote:

> Is it that you
> can't make an immutable regex()? In that case it is a
> runtime-related issue and those variables just have to be
> mutable. Or is it that you want to be able to use an immutable or
> const regex (be it from regex() or ctRegex!()) with matchAll()?
> In the latter case it is matchAll's fault for not garanteeing the
> immutability of the regex (and may even qualify as a bug IMHO)
> but you can « cast(Regex!char)numbers » it if you must so it
> isn't hard to work arround it.

Yes after your comments I realized that it's not so much that I cannot 
create an immutable or const symbol referring to a Regex object but that I 
cannot use it with matchAll etc. But of what use is a Regex object if it 
cannot be used with matchAll etc?

-- 
Shriramana Sharma, Penguin #395953


immutable promise broken in unions?

2016-01-02 Thread Shriramana Sharma via Digitalmars-d-learn
import std.stdio;
union EarthLocation
{
struct { immutable double lon, lat, alt; }
double[3] data;
}
void main()
{
EarthLocation d = {data: [4, 5, 6]};
writeln(d.data);
d.data = [1, 2, 3];
writeln(d.data);
}

I get the output:

[4, 5, 6]
[1, 2, 3]

I thought the promise of `immutable` was: never changes, whether via this 
interface or otherwise. How does then the above work?

Using DMD 2.0.69.2 on Kubuntu 64 bit.

-- 
Shriramana Sharma, Penguin #395953


Re: immutable promise broken in unions?

2016-01-02 Thread Shriramana Sharma via Digitalmars-d-learn
John Colvin wrote:

> Casting away immutable can sometimes be necessary (e.g. when
> talking to other languages), so I'm not sure it should be
> disallowed, but it'd be great if it was somehow easier to catch
> these bugs.

Yes it was in the context of talking to C that I needed to make such a 
union. But already making a union is breaking the type system in a way, no?

-- 
Shriramana Sharma, Penguin #395953


Re: Why isn't field-wise constructor automatic for structs and not classes?

2016-01-02 Thread Shriramana Sharma via Digitalmars-d-learn
John Colvin wrote:

> Strictly speaking you aren't calling a constructor there, you're
> writing a struct literal.

Why do you say I'm not calling a constructor?

And that still doesn't answer the question of why can't we have an automatic 
field-wise constructor for classes...

-- 
Shriramana Sharma, Penguin #395953


mixed-in ctor not on par with explicit one?

2016-01-12 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. Compiling the following code:

mixin template intCtor() { this(int i) {} }
struct Test { mixin intCtor; this(string s) {} }
void main()
{
auto a = Test("hello");
auto b = Test(1);
}

...gives the error:

(6): Error: constructor .Test.this (string s) is not callable 
using argument types (int)

What is the problem in calling the mixed-in ctor?

-- 
Shriramana Sharma, Penguin #395953


Re: mixed-in ctor not on par with explicit one?

2016-01-13 Thread Shriramana Sharma via Digitalmars-d-learn
Hello and thanks for your reply.

Jacob Carlborg wrote:

> [1] http://dlang.org/spec/template-mixin.html - search for "Alias
> declarations can be used to overload together functions declared in
> different mixins"

But I'm not able to do that with `this`:

mixin template myCtors()
{
this(int i) {}
this(char c) {}
}
struct Test
{
mixin myCtors;
alias this = myCtors.this;
this(string s) {}
}
void main()
{
auto a = Test("hello");
auto b = Test(1);
auto c = Test('c');
}

But I get the error:

(9): Error: identifier expected following '.', not 'this'
(9): Error: cannot use syntax 'alias this = myCtors', use 'alias 
myCtors this' instead

Even actually giving the mixin instance an identifier doesn't help:

mixin myCtors!() myCtorsInst;
alias this = myCtorsInst.this;

(9): Error: identifier expected following '.', not 'this'
(9): Error: cannot use syntax 'alias this = myCtorsInst', use 'alias 
myCtorsInst this' instead

This is not what alias <> this is supposed to do, right? So how am I 
supposed to get the mixed in ctors work?

-- 
Shriramana Sharma, Penguin #395953



Re: mixed-in ctor not on par with explicit one?

2016-01-13 Thread Shriramana Sharma via Digitalmars-d-learn
Jacob Carlborg wrote:

> Looks like a limitation in the language.

Apparently already reported as well: 
https://issues.dlang.org/show_bug.cgi?id=11500

-- 
Shriramana Sharma, Penguin #395953


Compiler complaining about ~ used on static array in @nogc fn

2016-01-13 Thread Shriramana Sharma via Digitalmars-d-learn
Referring to: 
https://auto-tester.puremagic.com/show-run.ghtml?projectid=1&runid=1915054&isPull=true,
 the lines in question are 
phobos/std/utf.d (66, 67):

UnsignedStringBuf buf = void;
msg ~= " (at index " ~ unsignedToTempString(index, buf, 10) ~ ")";

rgrepping through the druntime and phobos sources for this symbol 
UnsignedStringBuf I found:

./druntime/src/core/internal/string.d:16:alias UnsignedStringBuf = char[20];

So if it's a static array, then it has nothing to do with the GC, and 
appending will not use the GC, right? So why is the compiler complaining 
that I cannot use ~ inside a @nogc function?

-- 
Shriramana Sharma, Penguin #395953


`static` symbol needs to be `immutable` for compile-time access?

2016-01-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. This is a minimal abstraction of a part of my program:

int func(string s)
{
static int [] i = [5, 6, 7];
return i[2];
}
template temp(string s) { enum temp = func(s); }
void main() { static assert(temp!"str" == 7); }

With the above code I get:

(4): Error: static variable i cannot be read at compile time
(6):called from here: func("str")
(7): Error: template instance .temp!"str" error instantiating

I find that if I either replace `static` by `immutable` or even just *add* 
`immutable` after `static`, the error goes away. Do all values which need to 
be readable at compile time need to be declared `immutable`?

In C/C++ the `static` here is used to avoid the array being created every 
time the function is entered; in D too it does the same thing, no? So if I 
have an array of constants in a function that I need to be accessible to a 
template at compile time, and I (for obvious reasons) don't want to be 
initialized at every function call, do I have to declare it `static 
immutable`?

-- 
Shriramana Sharma, Penguin #395953


Re: `static` symbol needs to be `immutable` for compile-time access?

2016-01-22 Thread Shriramana Sharma via Digitalmars-d-learn
Thanks to all who replied.

anonymous wrote:
>> Do all values which need to
>> be readable at compile time need to be declared `immutable`?
> 
> Yes, `static immutable` or `enum`.

It would seem that in the case of arrays, the former is preferable to the 
latter, as per the para above this header:

http://ddili.org/ders/d.en/const_and_immutable.html#ix_const_and_immutable.variable,
%20immutable

But a further question, if I don't declare them as `static immutable` but 
just as `immutable`, would that mean that those arrays are necessarily 
created (meaning memory allocation) every time the function is run?

-- 
Shriramana Sharma, Penguin #395953


Unable to instantiate template with same name as function

2016-03-02 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I have a function I want to make CTFE-able as a template.

string ta(string s) { return s ~ "1"; }
template ta(string s) { enum ta = ta(s); }
void main() { string s = ta!"s"; }

Compiling the above I get the errors:

(2): Error: forward reference of variable ta
(3): Error: template instance .ta!"s" error instantiating

Please clarify what I am doing wrong? Thanks!

-- 
Shriramana Sharma, Penguin #395953


Re: Unable to instantiate template with same name as function

2016-03-03 Thread Shriramana Sharma via Digitalmars-d-learn
Hello people and thanks for your replies.

Jonathan M Davis via Digitalmars-d-learn wrote:

> You can't overload a function and an eponymous template like that. They
> need to have distinct names. 

Why is it not possible for the overload to happen? After all, the compiler 
should be able to identify which to use by seeing whether it is followed by 
! or (), no?

> > Now, that being said, I don't understand why
> you'd need to do anything with a template for CTFE in this case. Just
> write the function and then call it in a context that requires a
> compile-time result, and it should work. e.g.

OK but say I have a function which returns an array. If I use enum to CTFE 
its result, then it is repeatedly included explicitly in all places it is 
used, thereby using more memory. So I want to do:

string s = ta!"s";

Obviously, I can still do the different name approach, so it brings us back 
to the question as to why the name can't be re-used.

-- 
Shriramana Sharma, Penguin #395953


Re: Unable to instantiate template with same name as function

2016-03-04 Thread Shriramana Sharma via Digitalmars-d-learn
cym13 wrote:

> Note that parentheses are optional when no argument is provided.

Yes I know that but the point is I expected the compiler to identify 
ta!"string" to refer to a different symbol than ta("string") where the one 
is obviously a template and the other is obviously a function call. The fact 
that parantheses are optional for invocations of zero-arity functions or for 
templates taking a single argument or able to infer its arguments is 
irrelevant.

Anyhow, this is all moot, since actually the compiler *is* able to make the 
difference at the point of invocation and the problem was just a limitation 
in name lookup within the template itself:

string ta(string s) { return s ~ "1"; }
template ta(string s) { enum ta = .ta(s); }
void main()
{
import std.stdio;
writeln(ta("a"), ' ', ta!"b");
}

outputs a1 b1 as expected.

Filed https://issues.dlang.org/show_bug.cgi?id=15764 just for the record.

-- 
Shriramana Sharma, Penguin #395953


Re: Unable to instantiate template with same name as function

2016-03-04 Thread Shriramana Sharma via Digitalmars-d-learn
ag0aep6g wrote:

> On 03.03.2016 07:12, Shriramana Sharma wrote:
>> string ta(string s) { return s ~ "1"; }
>> template ta(string s) { enum ta = ta(s); }
> 
> In `ta(s)` here, `ta` is the enum itself again. It's similar to `int x =
> x;`. Can't do that, of course.
> 
> Add a leading dot to refer to the module level `ta` symbols instead:
> `enum ta = .ta(s);`.

Wonderful! So it's just a scope issue and not a "can't do that" issue! 
Although it would seem that the compiler 'should' be able to identify a 
different kind of ta, I can't expect too much of it and the D compiler is 
much more powerful syntax-wise than other language compilers.

I confirm that the following outputs "s1" as expected with the function call 
inside the template having the dot added in front:

string ta(string s) { return s ~ "1"; }
template ta(string s) { enum ta = .ta(s); }
void main()
{
import std.stdio;
writeln(ta!"s");
}

-- 
Shriramana Sharma, Penguin #395953


Re: Unable to instantiate template with same name as function

2016-03-04 Thread Shriramana Sharma via Digitalmars-d-learn
@AliCehreli: you may consider including Jonathan's trick in your book in the 
para above this heading: 
http://ddili.org/ders/d.en/const_and_immutable.html#ix_const_and_immutable.variable,
%20immutable

Jonathan M Davis via Digitalmars-d-learn wrote:

> yes, having
> 
> enum s = ta("s)";
> 
> and using s all over the place will result in an allocation each time that
> s is used. However, you can combine the two and avoid that problem. e.g.
> 
> enum e = ta("s");
> string s = e;
> 
> The ta is run at compile time, and it's only evaluated once.

-- 
Shriramana Sharma, Penguin #395953


Can't use function with same name as module?

2017-10-16 Thread Shriramana Sharma via Digitalmars-d-learn

Hello.

fun.d:
import std.stdio;
void fun() { writeln("Hello"); }

main.d:
import fun;
void main() { fun(); }

$ dmd -oftest fun.d main.d
main.d(2): Error: function expected before (), not module fun of 
type void


Why can't I use a function of the same name as the module? IIUC 
import fun imports all the top-level symbols within module fun as 
well as the symbol fun referring to the module itself. This is 
just another case of overloading, no? Can't the compiler 
understand that I am trying to call the function fun.fun() and 
not the module even when it is followed by ()?


Thanks!



Re: Can't use function with same name as module?

2017-10-17 Thread Shriramana Sharma via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 07:33:15 UTC, evilrat wrote:
Compiler made that way so it doesn't guess or assume too much, 
because later on it will bite you when you don't even expect 
that, and in some unpredictable place too.


Can you give an example for when it will bite me? It seems very 
natural to name a module with the name of the main class or 
function implemented in that module. Python modules like datetime 
follow this. What is the problem?


Especially in D the compiler is all-powerful and knows when to 
resolve to which symbol. If D compiler can resolve between 
multiple overloads in other cases, why not resolve here?


Re: Can't use function with same name as module?

2017-10-17 Thread Shriramana Sharma via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 08:26:12 UTC, Daniel Kozak wrote:

You can:
import fun : fun;


Yes I found this but it is unnecessarily verbose.

At the same time I also find that it is possible to declare a 
struct or class with the same name as module:


str.d:
struct str { int a; }

strmain.d:
import str;
void main() { str var; var.a = 2; }

cla.d:
class cla { int a; }

clamain.d:
import cla;
void main() { auto var = new cla; var.a = 2; }

$ dmd -ofstr str.d strmain.d
$ dmd -ofcla cla.d clamain.d

Problem only with function. If there can be a class or struct 
then what's the problem with function? Doesn't look like any of 
the problems which "will come and bite you later" in this case…


Re: Can't use function with same name as module?

2017-10-17 Thread Shriramana Sharma via Digitalmars-d-learn

Have reported https://issues.dlang.org/show_bug.cgi?id=17907


Re: Getting a safe path for a temporary file

2017-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
On Saturday, 17 January 2015 at 17:16:41 UTC, Tobias Pankrath 
wrote:

You're looking for core.sys.posix.stdlib : mkstemp.

I think that should be used by std.stdio.File as well, care to 
create an enhancement request in bugzilla?


Though this thread is old, I ran into the issue when wanting to 
create a temporary file in my D program and so filed this: 
https://issues.dlang.org/show_bug.cgi?id=17926


For my program right now I'm using a souped-up version using a 
static array:


import std.stdio;

struct TempFile
{
string name;
private File handle;
alias handle this;
}

TempFile tempFileOpen()
{
char[20] name = "/tmp/XX";
File handle;

import core.sys.posix.stdlib: mkstemp;
handle.fdopen(mkstemp(name.ptr), "w");

import std.string: fromStringz;
return TempFile(fromStringz(name.ptr).idup, handle);
}

void main()
{
TempFile tfile;
tfile = tempFileOpen();
writeln(tfile.name);
tfile = tempFileOpen();
writeln(tfile.name);
}



Re: Getting a safe path for a temporary file

2017-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
On Sunday, 22 October 2017 at 15:21:37 UTC, Shriramana Sharma 
wrote:
For my program right now I'm using a souped-up version using a 
static array:


char[20] name = "/tmp/XX";


Hmm I was wondering if I needed it to be static, and verily, 
substituting:


char[] name = "/tmp/XX".dup;

instead gives a proper output *some* of the time but mostly gives 
the error:


std.exception.ErrnoException@std/stdio.d(630):  (Bad file 
descriptor)


??:? @safe shared(core.stdc.stdio._IO_FILE)* 
std.exception.errnoEnforce!(shared(core.stdc.stdio._IO_FILE)*, 
"std/stdio.d", 
630uL).errnoEnforce(shared(core.stdc.stdio._IO_FILE)*, lazy 
immutable(char)[]) [0x44bd31]
??:? @trusted void std.stdio.File.fdopen(int, const(char[]), 
immutable(char)[]) [0x44294a]
??:? @safe void std.stdio.File.fdopen(int, const(char[])) 
[0x4428b1]

??:? .TempFile .tempFileOpen() [0x43d4fd]
??:? _Dmain [0x43d5ce]

Is it because the D slice is subject to relocation and C is 
occasionally not able to access the proper pointer?


Why is length being tested on an int?

2017-10-27 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I want a function to be able to take any arguments like 
write() and print them out but quoting string arguments of length 
more than 1. So I write the following quote:


import std.stdio;
string myFunc(string arg) { return '\"' ~ arg ~ '\"'; }
void myWrite(T ...)(T args)
{
foreach (arg; args)
if (is(typeof(arg) == string) && arg.length > 1)
write(myFunc(arg));
else
write(arg);
}
void main() { myWrite("Hello", 1, "c"); }

However I am getting the error even when compiling:

(6): Error: no property 'length' for type 'int'
(7): Error: function .myFunc (string arg) is not 
callable using argument types (int)
(11): Error: template instance .myWrite!(string, int, 
string) error instantiating


I am not sure why, given short circuit evaluation, it is testing 
the length of the int argument? Or is it that the problem is at 
compile time itself so short circuit doesn't come into play?


How to rewrite the function so I don't get the error?

Thanks!



Re: Getting a safe path for a temporary file

2017-10-27 Thread Shriramana Sharma via Digitalmars-d-learn

On Wednesday, 25 October 2017 at 00:35:29 UTC, Ali Çehreli wrote:

> char[] name = "/tmp/XX".dup;

remain valid. The actual issue is the missing '\0'. So, 
consider toStringz in this case:


  https://dlang.org/library/std/string/to_stringz.html


Thanks for your reply, but can you clarify exactly I should use 
this?


char[] name = "/tmp/XX".toStringz;

gives

(13): Error: cannot implicitly convert expression 
`toStringz("/tmp/XX")` of type `immutable(char)*` to `char[]`


So I tried:

char[] name = "/tmp/XX".toStringz.dup;

which gives

(13): Error: template object.dup cannot deduce function from 
argument types !()(immutable(char)*), candidates are:
/usr/include/dmd/druntime/import/object.d(1943):
object.dup(T : V[K], K, V)(T aa)
/usr/include/dmd/druntime/import/object.d(1979):
object.dup(T : V[K], K, V)(T* aa)
/usr/include/dmd/druntime/import/object.d(3764):
object.dup(T)(T[] a) if (!is(const(T) : T))
/usr/include/dmd/druntime/import/object.d(3780):
object.dup(T)(const(T)[] a) if (is(const(T) : T))


And:

char[] name = "/tmp/XX".dup.toStringz;

gives the error (13): Error: cannot implicitly convert 
expression `toStringz(dup("/tmp/XX"))` of type 
`immutable(char)*` to `char[]`


So I'm not sure what to do?!


Recommendation for parallelism with nested for loops?

2022-08-18 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I want to parallelize a computation which has two for 
loops, one nested within another. All 
inner-loop-param+outer-loop-param combinations can be computed 
independent of one another.


As I suspected, 
[https://forum.dlang.org/post/xysyidbkjdinclmrx...@forum.dlang.org](this forum post) says that only one loop can be parallelized. Will it be an error or inefficient or useless if I try to do both?


Also, what is the best way to do parallelism in such a situation?


Re: Using in as a parameter qualifier

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hello people. I'm once more looking at D since I participated here a
bit last year. Since I'm still not 100% sure about committing myself
to using D i.o. C++ for my work, I'd really like to resurrect this
thread to clear my lingering doubts (the full thread is at
http://forum.dlang.org/post/mailman.469.1369978600.13711.digitalmars-d-le...@puremagic.com
if people need context):

On 6/1/13, Jonathan M Davis  wrote:
> The compiler will move an object rather than copy it when it can. So, for
> instance, if you pass the function a temporary, it'll move that temporary
> rather than copying it. However, if it's called with an lvalue, odds are
> that
> it's going to have to make a copy (though it might be moved if it were the
> last time in the caller that the variable was referenced).

I read the Bartosz Milewski article that someone (Ali?) recommended
once more. What I understood is that D avoids the copy-*constructor*
when given an rvalue as a function parameter. But the article seems to
indicate that D will still make a *blit* copy.

However, Jonathan's comment above indicates otherwise (or am I
misreading?). What is actually meant above by "move an object rather
than copy"? In C++(11), move semantics seem to mostly involve a swap
of pointers ponting to the data. Here we are talking about struct
objects directly containing the data.

Does "move" means that the content is going to be "moved" to a new
location in memory i.e. copied and then the old memory freed?

What I'd really like to see D do (please tell me if it does that
already) is to avoid constructing the struct twice, once at the caller
site and second time at the callee site when I'm passing an rvalue
struct as argument. For example:

bezier.di:
struct Bezier { int p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y ; }
void draw(Bezier b) ;
--
test.d:
void main () {
  draw(Bezier(100, 100, 133, 200, 166, 200, 200, 200)) ;
}

should only ever cause the one Bezier struct object to be constructed
because the rvalue is not used at the caller site. Does D do that
already?

And even if what I'm passing to the draw function is an lvalue, say a
Bezier b which I have declared in the previous line to draw under
main(), if it is passed in with "in" keyword which implies "const",
then the function is not going to change the value anyway, so there
isn't any need to make a copy and so it makes sense if D actually
directly uses the content of the variable declared under main(). Does
D do this already too?

A further thought: If instead of draw(Bezier), I have Bezier.draw(),
then the values will be taken from the Bezier object directly whether
it is an lvalue or rvalue at the calling site, right?

And extending this, given that UFCS exists in D, draw(Bezier) and
Bezier.draw() should be equivalent, meaning that if Bezier.draw()
doesn't make a copy (even a blit) then draw(Bezier) shouldn't
[assuming of course that it doesn't alter the contents of the object],
right?

Sorry if some of my statements above sound presumptuous, but I'm
really really excited about D, and really really want to get away from
C++, so please bear with me... Thanks!

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Why do some language-defined attributes have @ and some not?

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. See http://dlang.org/attribute. 3 attributes starting at
http://dlang.org/attribute#disable have a @ in front. Apparently safe,
trusted and system also do, though these are documented elsewhere:
http://dlang.org/function.html#function-safety.

Why are some language-defined attributes starting with @ and others
not? Wouldn't it be consistent and less-confusing to, say, only use @
for user-defined attributes and not these language-defined ones?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Why do some language-defined attributes have @ and some not?

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
I thought D was beyond carrying historical baggage. DMD 2.x is not
necessarily language-compatible with DMD 2.(x+1) since the language is
still evolving. You can deprecate one syntax and enforce the other in
a later version.

I submit that the syntax for attributes should be streamlined. Shall I
go and open a Bugzilla item?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Constructor params with same name as members

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. Please see the following code:

import std.stdio ;
struct Pair {
int x, y ;
this (int x, int y) { x = x ; y = y ; }
}
void main() {
auto P = Pair(1, 2) ;
writeln(P.x, ' ', P.y) ;
}

This outputs 0 0, whereas the equivalent C++ code outputs 1 2 correctly:

# include 
struct Pair {
int x, y ;
Pair(int x, int y) : x(x), y(y) {}
} ;
int main() {
auto P = Pair(1, 2) ;
std::cout << P.x << ' ' << P.y << std::endl ;
}

It seems to me that D should either not permit argument names to
shadow the member names, since it has no initializer lists and all
members are automatically initialized. Comments?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Returning a ref to a temporary already possible?

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
IIUC the whole deal with not allowing ref parameters to point to
rvalues is the fear that they may be returned outside the function,
but it seems this is already possible:

module reftest ;
import std.stdio ;
struct Pair {
int x, y ;
this (int x_, int y_) { x = x_ ; y = y_ ; writeln("Pair constructed") ; 
}
auto handle() { return this ; }
}
void main() {
auto P = Pair(1, 2).handle ;
writeln(typeof(P).stringof) ;
P.x = 3 ;
writeln(P.x, ' ', P.y) ;
}

Running this makes it clear that only the one Pair object is ever
constructed. But I don't understand how it is that the type of P is
Pair and not ref(Pair).

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Using in as a parameter qualifier

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hi Jonathan and thanks again for your kind replies.

On 10/23/14, Jonathan M Davis via Digitalmars-d-learn
 wrote:
> That will result in a move operation. No copying will take place.
> And it technically, it may not actually move anything it all and
> just use the object where it's initially constructed. I'm not
> sure what the actual, generated machine code ends up doing in
> that regard. But there's no copying or double-construction.

Well blitting is copying isn't it? I read your SE answer where you
define a move as a blit without the postblit. Hmm. Somehow the name
"move" seems to be misleading...

To clarify that, is this the same as the C++11 move behaviour or is it
subtly different? IIUC in case of a C++ vector, a move would mean that
the length and possibly other direct members of the class including
the pointer to the heap-allocated managed data would be copied to the
target (same as blit I guess) and the managed data itself is not
dupped (i.e. postblit is not called) and we call it a move, yeah? But
it's actually better called a shallow copy, no?

Or is a shallow copy different from a move in any other way?

> const does _not_ mean that a copy doesn't need to be made. It has
> zero effect on that. In fact, if you're passing an lvaue to a
> function that doesn't take its arguments by ref, it's almost a
> guarantee that a copy will be made. The only exception would be
> if the compiler determines that the lvalue in question is never
> used after that call, in which case, it might just move the
> object rather than copy it.

But that doesn't seem logical. If the compiler is able to determine
that the lvalue in question is not modified in the function at all
(either heuristically or by the programmer defining it as "in" or
"const") then it should be able to optimize by not even making the
move aka shallow copy, no?

Of course I understand it doesn't *have* to do an optimization, and
that D believes that ideally optimization opportunities should be
recognized and acted upon by the compiler and the user should not need
to specify places where this is possible (I listened to the
Andrei/Walter panel talk where IIUC they were saying this is the ideal
behaviour and keywords like "pure" "nothrow" etc shouldn't ideally be
needed), but I just want to be sure whether I'm understanding right
that there is indeed the possibility in the present case.

> So, you mean if draw was a member function of Bezier, and you did
> something like
> Bezier(100, 100, 133, 200, 166, 200, 200, 200).draw()
> you want to know whether a copy of the Bezier object would be
> made? The this member of a struct is a ref - in this case ref
> Bezier - so it doesn't make a copy.

Actually it doesn't even make a move aka shallow copy right? If that's
right, then sorta here we are seeing how a ref to a temporary can
indeed exist, i.e. implicitly within the member functions. (I'll post
separately on that topic.)

> If draw is a free function, then
> Bezier(100, 100, 133, 200, 166, 200, 200, 200).draw()
> is literally transformed into
> draw(Bezier(100, 100, 133, 200, 166, 200, 200, 200))
> by the compiler, so the behavior of those two lines is identical.
> And as I said above, that means that a move is made.

OK so if I read this right, if the function is defined as a free
function, then calling it on a temporary will make a shallow copy (and
I can't use an explicit ref on the temporary argument), but if it is
defined as a member then calling it on a temporary will not even make
a shallow copy. Because of UFCS, how I'm *calling* the function will
not have an effect on whether the shallow copy is made or not, but how
I *defined* it will. Correct?

> I'm not sure why it would sound presumptious if you're asking
> whether you're understanding or guesses about how D works are
> wrong. Questions are certainly welcome.

That's very nice of you. I only added the advance apology because
sometimes some friends of mine have commented that I come across high
and mighty in saying "this should be like this and this and not like
that" in technical fora where people more knowledgeable than me exist.
As Andrei said in his opening address, it's nice to see that one big
strength of D is the patient and friendly replies of the D community.
:-)

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Why do some language-defined attributes have @ and some not?

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
On 10/23/14, Jonathan M Davis via Digitalmars-d-learn
 wrote:
> So, yes, we do have historical baggage, albeit nowhere near as
> much as C++ does.

OK understood, but I may just go and file that bug so that if there is
a future D 3 series, then stuff like this can be cleaned up. :-) I'm
finicky like that! ;-)

> Walter and Andrei very much want D to be being used in production
> at this point,

We all do, no? Not only those two! :-)

So I agree with you that for now this is not an urgent need. I guess
when we clean out all that !> <>= stuff this can be done too, or
something like that...

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Constructor params with same name as members

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I perfectly realize that it's not advisable to take advantage
of shadowing. In fact, I asked the question because I thought D
specifically *didn't* allow shadowing, but here it is, being silently
permitted to mishappen... I seem to read to have read that (D didn't
allow shadowing) but I'm not able to point to where...

BTW I compiled it with LDC 0.14.0 and separately with D 2.066.0 and
both give the same result.

So shouldn't the compiler ideally complain about the arguments
shadowing members?


-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Constructor params with same name as members

2014-10-22 Thread Shriramana Sharma via Digitalmars-d-learn
Oh OK here it is:
http://dlang.org/deprecate.html#Variable%20shadowing%20inside%20functions

But it says "it is an error to use the feature" by 2.061 and I'm using 2.066!

Doesn't the scope of that deprecation cover struct members too? In
general it should be like "variables in inner scopes should not shadow
those in outer scopes" irrespective of what the scopes are, right?

Of course, for clarity we could add "except when the inner scope is a
separate namespace", so it is made clear that enum/struct/class
members do not shadow outer variables...


-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Returning a ref to a temporary already possible?

2014-10-23 Thread Shriramana Sharma via Digitalmars-d-learn
Hi thanks for the reply.

So should I understand that "return this" doesn't really return the
ref but the object actually? Or it does return a reference but since
it's assigned a name, it lives on under that name and so only the
single struct object P is ever created? Otherwise one would wonder how
a temporary can have lifetime beyond the line in which it is created.

I'd really like to know what's exactly happening in that line:

auto P = Pair(1, 2).handle ;

Thanks!


-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Why do some language-defined attributes have @ and some not?

2014-10-24 Thread Shriramana Sharma via Digitalmars-d-learn
Hi people and thanks for weighing in. It's nice to note that there's
already a DIP on this. I hope it's refined and implemented in a future
version in a meaningful manner. Is it OK to edit the wiki to add one's
opinions?

And in this case, personally I'm not sure why people are talking about
code *breakage*, which is a big word IMO. It's after all removing or
adding @ in a few cases. It's relatively straightforward a fix to
automate. If there can be a dfix to relocate the const from before to
after the function name, then this should be much easier, no? It
wouldn't even need a D3, but could be done in a future D2 point
release. And as someone else said, there's a difference between
outright breakage and planned deprecation.

As for the cases when serious changes to the grammar are needed, I
feel the Py2 to Py3 transition is a good example to emulate. Lots of
cleanup happened in Py3, Py2 is still supported, and there exists
tools like 2to3 and six (https://pypi.python.org/pypi/six) to help
people bridge the gap.

Finally in general I'd also like to suggest that rather than saying
something like "you won't be able to convince Walter of this because
it's not important", which IMHO tends to somewhat put off newbies who
are excited by the language and want to contribute, and tends to put
the project masters in an autocratic light (which people won't like to
hear), one might consider saying something like "D 2 is now aiming for
stability so we are trying to minimize the number of grammar changes".

Thanks again, all!

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



non-const method permitted on rvalue?

2014-10-24 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I realize the wording "non-const method" is probably a C++-ism
but please see the following code. In both C++ and D, the compilers
are complaining only when I try to assign directly to the member of an
rvalue, but if I try to assign via a non-const ref returned by a
non-const method, then it's apparently fine?!! At least shouldn't D
prohibit this? [Yet another case of rvalue refs being allowed to
escape?]

nonconst.d:
--
struct Pair {
int x, y ;
ref Pair handle() { return this ; }
}
void main () {
Pair(1, 2).x = 5 ;
Pair(1, 2).handle.x = 5 ;
}
--
nonconst.cpp:
--
struct Pair {
int x, y ;
Pair(int x, int y) : x(x), y(y) {}
Pair & handle() { return *this ; }
} ;
int main () {
Pair(1, 2).x = 5 ;
Pair(1, 2).handle().x = 5 ;
}

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Two cases for improving error messages

2014-10-25 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. Please see the following and say whether they're OK to submit
as bugs for improving the error messages. Thanks.

ref int foo(ref int x) { return x ; }

void main () {
foo(3) ;
// Error: function rvalue_argument.foo (ref int x) is not callable
using argument types (int)
// Comment: "argument ref int x of function rvalue_argument.foo cannot
bind to an rvalue" would be clearer IMO

int i ;
ref ir = i ;
// Error: variable ref_type.main.ir only parameters or foreach
declarations can be ref
// Comment: add ", return values" after "parameters"
}


-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Two cases for improving error messages

2014-10-25 Thread Shriramana Sharma via Digitalmars-d-learn
On Sat, Oct 25, 2014 at 8:00 PM, H. S. Teoh via Digitalmars-d-learn
 wrote:
>
> I agree with submitting both of these as enhancement requests. Please
> tag them with "diagnostic" in the keywords field.

Done:

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

You did say *requests* in the plural so I filed them separately.

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Interfacing with C++

2014-11-01 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I really really need to be able to interface well with a C++
library which contains lots of classes if I am going to further invest
time into D.

Now from the http://dlang.org/cpp_interface I find out the current
status of built-in C++ interfacing support. I'm working on Linux so
using the COM support is not an option for me (whatever COM may be!).

A few queries:

1) How mature is the SWIG support for wrapping a library into D?
Specifically does the above SWIG support take advantage of the
built-in C++ support features like connecting directly to virtual
functions?

2) Is there any further work underway to implement support for static
and non-virtual class member functions? Or is this not at all
possible? If so, why?

3) The page speaks about having to integrate an entire C++ compiler
into the D compiler. Could the usage of libclang help here in having
to avoid writing a new C++ compiler module or am I talking through my
(non-existent) hat?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



char16_t and char32_t

2014-11-01 Thread Shriramana Sharma via Digitalmars-d-learn
In the following pages (which have differing file naming patterns for
whatever reason!):

http://dlang.org/interfaceToC.html
http://dlang.org/cpp_interface

I would suggest to add the info that wchar is compatible with the
char16_t and dchar with char32_t of C11. See:

http://en.wikipedia.org/wiki/C11_%28C_standard_revision%29#Changes_from_C99

Currently wchar and dchar are marked as being compatible with wchar_t
depending on the sizeof(wchar_t). That's true, but I guess
char{16,32}_t provide a stable mapping.

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



D int and C/C++ int etc not really compatible when interfacing to C/C++

2014-11-01 Thread Shriramana Sharma via Digitalmars-d-learn
In the following pages:

http://dlang.org/interfaceToC.html
http://dlang.org/cpp_interface

the "Data Type Compatibility" section says D int is compatible with
C/C++ int. Isn't this actually false because D's integer types are
fixed-size whereas C/C++'s are variable? So D int is only compatible
with C++ int32_t, and who knows what that is typedef-ed to? Likewise
for uint, long, short etc.

So how to ensure, when calling C/C++, that the D int etc are being
mapped to the correctly-sized C/C++ type? Does the compiler ensure
that since the compatibility is being advertised as built-in?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Problem with spec doc?

2014-11-01 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I already posted this via the forum interface:
http://forum.dlang.org/thread/yqhwwpskwmkdefarj...@forum.dlang.org

But for whatever reason I didn't get any replies so I worry if it
actually reached people or not...

-- Original message --

At http://dlang.org/spec.html I read: "This is also available as a PDF
document" where "PDF document" is a link to
http://dlang.org/dlangspec.pdf. However, the PDF is just as 4 page doc
with only the TOC. The individual pages don't seem to have PDFs
either. I hope this is not intentional.

Can the full spec please be posted as a single PDF? Thanks.

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Problem with spec doc?

2014-11-01 Thread Shriramana Sharma via Digitalmars-d-learn
Thank you very much. But this is curious -- isn't Andrei himself able
to directly commit or answer that pull request?!!

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Learning D for a non computer science background person : pre-requisite knowledge?

2014-12-02 Thread Shriramana Sharma via Digitalmars-d-learn
On Tue, Dec 2, 2014 at 10:45 PM, Mayuresh Kathe via
Digitalmars-d-learn  wrote:
> Okay, if that is the case, I'll dive into Mr. Alexandrescu's book as soon as
> I get my copy.
> BTW, how come all of you address him as Andrei?

Heh -- possibly you haven't interacted on international technical
mailing lists like this. For us (you and me) in India we are used to
employ/expect such honorifics, and in fact it would be considered
somewhat disrespectful if we didn't, but in my early days interacting
with people from "western" countries on the net, I was actually
discouraged from using "Mr" because it made people feel "old"! :-)

FWIW while we're talking honorifics, he's *Dr* Alexandrescu as in Ph D
doc. :-) [I'm one too, but you won't find me having mentioned it
anywhere earlier! :-) That's informal.]

Re Andrei's book versus Ali's, the latter is a more starting from the
basics approach whereas Andrei's book is more targeted at people
coming from other languages. (This is a judgment I read somewhere --
perhaps on this forum? -- and which I agree with, sorta.)

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Re: Why the DMD Backend?

2014-12-02 Thread Shriramana Sharma via Digitalmars-d-learn
On Wed, Dec 3, 2014 at 8:03 AM, ketmar via Digitalmars-d-learn
 wrote:
>
> that is exactly the reason i'm against LLVM: it's license. i believe
> that compiler and compiler construction tools must be [L]GPLed or
> proprietary, but not MITed/BSDLed/SIMILARed.

Heh -- fine for whatever compiler tools *you* create, but if someone
else creates it, and is willing to distribute it under a more liberal
license, why should you find it unacceptable, I'm not sure!

Isn't LGPL largely the same way versus the GPL?

And I'm pretty sure I read somewhere that even the Linux kernel code
(or most big popular L/GPL libs like Qt) has some BSD-licensed stuff
inside it...

BTW isn't Phobos Boost-licensed? And that's almost the same as
BSD/MIT/ISC terms?

-- 
Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



Why isn't global operator overloading allowed in D?

2015-10-14 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I just came upon a need in my program to make binary arithmetic 
operators valid between two real[] in my programs, and thought of writing a 
global opOpAssign, but then looked through the documentation, found nothing 
on operator overloading allowed at the global level (even within a single 
module), and searched through the forum and saw this thread: 
http://forum.dlang.org/post/jeyaozvegcnivcppu...@forum.dlang.org

Why isn't global operator overloading allowed in D?

Having to construct a class just to write a quick operator overload for two 
built-in types isn't a clean solution, so please don't suggest that (like it 
was suggested in the other thread).

Thanks.

Shriramana Sharma.



Re: Why isn't global operator overloading allowed in D?

2015-10-14 Thread Shriramana Sharma via Digitalmars-d-learn
Shriramana Sharma wrote:

> Hello. I just came upon a need in my program to make binary arithmetic
> operators valid between two real[] in my programs, and thought of writing
> a global opOpAssign, but then looked through the documentation, found
> nothing on operator overloading allowed at the global level (even within a
> single module), and searched through the forum and saw this thread:
> http://forum.dlang.org/post/jeyaozvegcnivcppu...@forum.dlang.org
> 
> Why isn't global operator overloading allowed in D?

Hmm, just now saw this one too: 
http://forum.dlang.org/post/l7nnnb$1ma0$1...@digitalmars.com -- posted that too 
hastily.

But really, it's too bad built-in types are different from user-made types 
unlike in Python. In Python, I can inherit from list and dict and whatnot 
(yes I have used them in real apps)...



Re: Why isn't global operator overloading allowed in D?

2015-10-15 Thread Shriramana Sharma via Digitalmars-d-learn
John Colvin wrote:

> On Wednesday, 14 October 2015 at 15:02:02 UTC, Shriramana Sharma
> wrote:
> What binary arithmetic operators do you need that real[] doesn't
> already support?

OMG silly me! I can already do a[] /= b[]... D is great! :-D Thanks a lot!



Why can't function expecting immutable arg take mutable input?

2015-10-16 Thread Shriramana Sharma via Digitalmars-d-learn
Hello. I still haven't wrapped my mind around the const/immutable thing yet 
and am still stuck in C/C++ mode. :-(

A function that takes mutable arguments cannot be called with immutable 
input at the call site since it does not promise to *not* mutate the input. 
That's of course clear.

Why can't a function that takes an immutable argument be called with a 
mutable input at the call site?

IOW, why isn't mutable implicitly convertible to immutable?

I just finished writing a string processing module which calls multiple 
subroutines, and all of them carrying arguments with type `string` viz. 
`immutable(char)[]` IIUC, and I tried to pass it something which came from 
File.byLine(), then got the error:

function textattr.applyTextAttr (string text) is not callable using argument 
types (char[])

I understand that const can refer to either mutable or immutable, so does 
this mean I should replace all occurrences of `string` in arguments and 
return values of functions by `const(char)[]`?

-- 
Shriramana Sharma, Penguin #395953


Why does File.byLine() return char[] and not string

2015-10-16 Thread Shriramana Sharma via Digitalmars-d-learn
Is there a particular reason that File.byLine() returns char[] and not 
string i.e. immutable(char)[]? Is it just to avoid being overly restrictive? 
It seems that having to .idup it is inefficient...

-- 
Shriramana Sharma, Penguin #395953


Re: Why does File.byLine() return char[] and not string

2015-10-16 Thread Shriramana Sharma via Digitalmars-d-learn
Thanks people, for the replies. That's very clear now.

-- 
Shriramana Sharma, Penguin #395953


  1   2   >