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: termcolor-d - Colors with writeln(...);

2018-11-22 Thread Shriramana Sharma via Digitalmars-d-announce
On Wednesday, 21 November 2018 at 18:36:06 UTC, Vladimirs 
Nordholm wrote:

https://github.com/vladdeSV/termcolor-d


https://github.com/jamadagni/textattr/

Saw a library recently which allowed you to color text, but it 
had an odd syntax.


Maybe the documentation, in trying to be exhaustive, hasn't 
showed how simple it can be. I'm not sure why it is perceived as 
odd. Can you clarify?


Since I already had some code for coloring text in terminals, I 
made this (hackish, POSIX only) project during lunch break. It 
in action:


import std.stdio : writeln;
import termcolor;


import textattr;


// Color → Green → Foreground
writeln(C.green.fg, "Green text", resetColor);


  writeln(ta("green"), "Green text", ta("off"));

*or* the shorter:

  writeln(ta("g"), "Green text", ta("f"));

*or* the even shorter:

  tawrite("@g", "Green text", "@f", '\n');

The @ indicates that it is an "at"tribute.

It's not an issue to add a tawriteln which adds the newline at 
the end. I first posted the basic library thinking to make 
additions as per demands later.



// Color → Red → Background
writeln(C.red.bg, "Red background", resetColor);


  tawrite("@/red", "Red background", "@off", '\n');

The / indicates that it's a background colour. This is stated in 
the HTML documentation, but maybe not clear within the 
limitations of the README.md. I'll see what I can do to improve 
it.


Having premade symbols in the library as you have done is easy 
enough for basic 16-colour or even attribute support, but adding 
256 colour or true colour support this way would unnecessarily 
use up too much memory.


Re: textattr library for text colors and attributes available in D

2018-11-22 Thread Shriramana Sharma via Digitalmars-d-announce

On Friday, 9 November 2018 at 22:28:28 UTC, JN wrote:
It looks to me like the textattr.d is all that is needed? 
Should be easy to put it in a separate package that could be 
uploaded to dub registry.


Yes indeed textattr.d is all that is needed! For C too 
textattr.c|h are all that are needed.


Re: textattr library for text colors and attributes available in D

2018-11-08 Thread Shriramana Sharma via Digitalmars-d-announce
On Thursday, 8 November 2018 at 19:26:15 UTC, Bastiaan Veelo 
wrote:
Cool, must remember this in case I need it one day. Do you have 
plans to add it to the dub registry?


Don't know how. Can follow instructions if provided. Does DUB 
also allow multi-language libs one of which is D?


Unfortunately my D usage isn't as much as I'd like it to be so 
haven't kept up so closely…


textattr library for text colors and attributes available in D

2018-11-08 Thread Shriramana Sharma via Digitalmars-d-announce

https://github.com/jamadagni/textattr/

textattr is a library and command-line tool that makes adding 
color and attributes to beautify the terminal output of your 
program easier by translating human-readable specs into ANSI 
escape codes.


The library is available for C, C++, Python and D. C++ and Python 
use the C code for internal processing but the D code is a 
separate implementation for easy inclusion of textattr.d in a D 
compilation command without requiring any external linking.


Copyright: Shriramana Sharma, 2018
License: BSD-2-Clause



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


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


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: 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: 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

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?


Can't use function with same name as module?

2017-10-17 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: Template version of ANSI color code lib useful?

2017-10-14 Thread Shriramana Sharma via Digitalmars-d
On Saturday, 14 October 2017 at 17:17:41 UTC, Petar Kirov 
[ZombineDev] wrote:
Why not simply add extern (C) wrappers for your D code? I see 
no point of using C, unless you want to be portable to arcane 
architectures.
With this approach you'll have both the portability of C and 
the advantages of using D.


Yes I admit this idea hadn't occurred to me earlier.



Re: Template version of ANSI color code lib useful?

2017-10-14 Thread Shriramana Sharma via Digitalmars-d

On Saturday, 14 October 2017 at 14:51:12 UTC, Adam D. Ruppe wrote:

My terminal.d works with most that stuff.


Yes I did look into existing solutions. Mainly my desire was not 
to work in D alone but something available at command line and as 
a library for shell-scripts and other languages too.


I think it is worthless - color output must be a runtime 
decision to handle non-terminals or even terminals that don't 
support color output.


Thank you for that most candid reply!


Template version of ANSI color code lib useful?

2017-10-14 Thread Shriramana Sharma via Digitalmars-d
Hello. I prepared a utility/library to output ANSI escape codes 
for terminal text attributes with capabilities as advertised at 
https://sites.google.com/site/jamadagni/files/temp/textattr-usage.html. (AFAIK this set of capabilities does not exist already in any existing package.)


This was first written in D and ported with much effort to C. 
This is the utility/library I refer to at 
http://forum.dlang.org/post/n6362a$1t7u$1...@digitalmars.com.


Now I would prefer to keep the single C source and just write a 
thin D wrapper to call the C library because C is also callable 
from many other languages (and people can write wrappers for 
their favourite one).


However the only disadvantage (as discussed in the above thread) 
is that the C library function is not CTFE-able in D and thus I 
cannot write a D template in the wrapper to evaluate the colour 
codes at compile time.


On the other hand, I am not sure whether it is really useful to 
evaluate colour codes at compile time because it is tantamount to 
hardcoding them, and this means that any program using the 
library is not able to switch off colour output at will if stdout 
is not connected to a terminal.


If the library is only called at runtime, I am able to add a 
boolean switch to just make the library always output an empty 
string for all calls effectively switching off colour code output 
which is useful when stdout is not a terminal.


My question: do people agree that there is not much point in 
enabling CTFE of colour codes?


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


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


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


`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


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=1915054=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


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


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


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


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:

> 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


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: 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


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

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


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:

> 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


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


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


Re: Slicing AliasSeq-s

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

>  Look down to
> where it handles tuples (AliasSeq is the user-visible name for
> what the compiler internally calls a tuple).

Ouch. So even if the terminology gets abolished from Phobos, it's still 
lurking in the compiler?

> Slicing a tuple creates a new tuple that refers to the same
> objects as the previous one. So it doesn't deep copy... but
> remember this is irrelevant to any D program

I realize that but just wanted to know whether the word slicing is used in 
this context in the same sense as elsewhere.

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


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


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


Slicing AliasSeq-s

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

Apart from the obvious need for changing the references to tuples to alias 
sequences (for which I'm working on a PR), my question:

Both the above page and http://dlang.org/phobos/std_meta.html refer to 
"slicing" alias sequences. In D slicing means just creating another 
reference to the same memory as the sliced object.

Given that AliasSeq-s cannot be written to[*], it's not possible for me to 
test whether it's actually sliced or a new AliasSeq with the same elements 
is created. Otherwise I could do something like this:

alias A = [int, 2, symbol];
alias B = A[1 .. $];
alias C = A[0 .. $ - 1];
A[1] = 3; // not possible
static assert(B[0] == 3 && C[1] == 3);

So out of curiosity I'd like to know how this is implemented in the 
compiler: as really a slice or a copy? (Posting this to D and not learn 
since it relates to compiler internals.)

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


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


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


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: 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


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


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


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


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: 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


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


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=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


Re: isExpressions -> isValuesSeq

2015-12-14 Thread Shriramana Sharma via Digitalmars-d
Mike Parker wrote:

> Consider what would happen if they did not evaluate expressions:

I never said they should not evaluate expressions. Expressions are always 
evaluated in any context in D, but they are immediately converted to values 
(so long as they are evaluable). But for this very reason, alias sequences 
can not "contain" or "encapsulate" expressions in un-evaluated form in any 
way (unlike, say 
http://docs.sympy.org/dev/modules/core.html#sympy.core.mul.Mul) in that the 
components of the expression are lost by the time the AliasSeq gets defined.

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


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


Better string representation for TypeSeq used as function arg type?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
Hello. By executing the following:

alias AS = AliasSeq!(int, double);
int foo(AS td)  // same as int foo(int, double);
{
writeln(typeof(td).stringof);
return td[0] + cast(int)td[1];
}

I get:

(int, double)

But it is not very clear as to what exactly the type of `td` is! I 
understand that the AliasSeq is presented to the function body *as if* it 
were a Tuple!(int, double) in that it can be accessed using [0] [1] etc, but 
it is not *really* (in the sense of RTTI) a Tuple, is it? In which case, 
what is it? Is it another "Voldemort" type?

-- 
Shriramana Sharma, Penguin #395953


What is the utility of .stringof with expressions?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
D currently supports:

writeln((1 + 2).stringof);

to print:

1 + 2

What is the real-world use case of this "feature"? I mean, everyone knows 
what the code they write looks like, so why would they want to have a 
language feature to get a string representation of it that they can print 
out to the user? I mean, if at all someone wants to print out 1 + 2, they 
can always say "1 + 2" and be done with it, instead of going to the 
convolution of .stringof...

One thing I observe however is that:

writeln((1+ 2).stringof);
writeln((1 +2).stringof);
writeln((1  +  2).stringof);

all print "1 + 2" (without the quotes) so it's not a simple compiler dumps 
to string thing, but still I don't understand what this can be useful for...

-- 
Shriramana Sharma, Penguin #395953


Re: Better string representation for TypeSeq used as function arg type?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
cym13 wrote:

> This is great, but please post them
> preferably in then Learn section of the forum where you will get
> more help, the General section is more for discussing the
> evolution of D itself.

Yes I understand that, but earlier when I asked questions on D.learn about 
advanced topics like interfacing to C++, I was asked to make them here. So I 
figured that "elementary" questions go there and more "complex" ones related 
to "higher" programming topics go here. Since this thread is about 
metaprogramming which didn't seem an "elementary" topic, I asked it here. I 
posted some "elementary" questions to D.learn even yesterday...

-- 
Shriramana Sharma, Penguin #395953


Re: What is the utility of .stringof with expressions?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
cym13 wrote:

> It could be useful combined with mixins to preprocess the code
> you write before compiling it.

Huh? Can you give me a concrete example? I'm not being intentionally dense 
but I can't imagine such a use case where you can't just write the string 
literal yourself...

-- 
Shriramana Sharma, Penguin #395953


Re: isExpressions -> isValuesSeq

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
Mike Parker wrote:

> All values, 3 and false included, *are* expressions. They are
> expressions with one operand and no operator, but they are still
> expressions.
> 
> https://en.wikipedia.org/wiki/Value_(computer_science)

That's true, but the fact remains that the AliasSeq stores only the 
resultant value of the expression and not the expression itself (which may 
be valid or not).

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


Re: Better string representation for TypeSeq used as function arg type?

2015-12-12 Thread Shriramana Sharma via Digitalmars-d
cym13 wrote:

> So, no, it's not a Voldemort type, it's exactly what the compiler
> tells you it is: the sequence of types (int, double).

Hmmm it seems to me that if it's not a runtime-valid type, then typeof() 
shouldn't work at all...

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


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


Replacing .tupleof

2015-12-11 Thread Shriramana Sharma via Digitalmars-d
Given that TypeTuple is replaced by AliasSeq (though many don't like the new 
name), it seems that .tupleof should be replaced by .fieldvalues like 
std.traits is proposed to have FieldIdentifiers and FieldTypes in 
https://github.com/D-Programming-Language/phobos/pull/3756. Thoughts?

-- 
Shriramana Sharma, Penguin #395953


How is `auto` and not `alias` appropriate for alias sequences?

2015-12-11 Thread Shriramana Sharma via Digitalmars-d
Hello. I just found that the following code compiles without any problem:

struct Foo { int val; string name; }
Foo foo = {1, "one"};
auto t = foo.tupleof;

Trying to use `alias` i.o. `auto` above fails.

Now IIUC, trying to take the address of t fails, so it's still a compile-
time-only construct without "real" i.e. runtime existence. The tuple is in 
fact an AliasSeq, no? In which case, I would have thought that `alias` (for 
compile-time symbols) and not `auto` (for runtime variables) would be the 
appropriate choice.

Can someone please explain this situation? Thanks.

-- 
Shriramana Sharma, Penguin #395953


Re: How is `auto` and not `alias` appropriate for alias sequences?

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

>>struct Foo { int val; string name; }
>>Foo foo = {1, "one"};
>>auto t = foo.tupleof;
>>
>> Trying to use `alias` i.o. `auto` above fails.
>>
>> Now IIUC, trying to take the address of t fails, so it's still
> 
> auto can refer only to run-time values.
> 
> foo is run-time value.

In which case, why should taking its address fail? If I try to do:

auto tp = 

I'm getting:

Error: tuple(__t_field_0, __t_field_1) is not an lvalue

What the!? *After* I assign it to a variable, it still says it's not an 
lvalue? I mean I understand if I can't take the address of a compiler-
created temporary rvalue, but why can't I take its address even after I 
assign it to a newly created variable? Does the variable t have an address 
in memory or not?

I understand that:

alias t2 = foo.tupleof; 

doesn't work since you cannot give an alias to an rvalue temporary, since t2 
would be pointing to nothing after the (immediate) destruction of the 
temporary tuple object. But I can still do:

alias t2 = t;

So why can't I do:

auto tp = 

???

Note that the following, which should be equivalent, works:

alias FooTuple = Tuple!(int, string);
FooTuple footu = FooTuple(1, "one");
auto ttp = 

-- 
Shriramana Sharma, Penguin #395953


Re: How is `auto` and not `alias` appropriate for alias sequences?

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

> In short, the current D terminology calls:
> compile-time lists -> AliasSeq
> (http://dlang.org/phobos/std_meta#AliasSeq)
> run-time values of type lists -> Tuple
> (http://dlang.org/phobos/std_typecons#.Tuple)

Excellent explanation. I keep looking for a "Like" or "Upvote" button on 
this forum. :-) Thanks!

-- 
Shriramana Sharma, Penguin #395953


isExpressions -> isValuesSeq

2015-12-11 Thread Shriramana Sharma via Digitalmars-d
This is w.r.t. http://dlang.org/phobos/std_traits.html#isExpressions:

I am trying the following code:

import std.stdio, std.meta, std.traits;
void main()
{
alias a = AliasSeq!(1 + 2, "foo" == "goo");
if (isExpressions!a) write("This AliasSeq contains expressions: ");
foreach (v; a) { write(v.stringof, ", "); } writeln();
writeln("This should be: ", (1 + 2).stringof, ", ", ("foo" == 
"goo").stringof);
}

The output is:

This AliasSeq contains expressions: 3, false, 
This should be: 1 + 2, "foo" == "goo"

Clearly, the AliasSeq is not able to store the expressions themselves since 
they are automatically evaluated at compile time. It stores only the values 
that the expressions evaluate to. Further, expressions which are not 
evaluable at compile time aren't permitted in the AliasSeq. (I tried it.) 
Thus the appropriate name would thus be isValuesSeq, no?

-- 
Shriramana Sharma, Penguin #395953


Re: How is `auto` and not `alias` appropriate for alias sequences?

2015-12-11 Thread Shriramana Sharma via Digitalmars-d
Another twist to this is that the tuple created by .tupleof doesn't really 
seem to be a new object of type Tuple!() but rather a "view" of sorts onto 
the original object itself in the form of a tuple, else the example provided 
at http://dlang.org/spec/class.html i.e.:

class Foo { int x; long y; }
void test(Foo foo)
{
foo.tupleof[0] = 1; // set foo.x to 1
foo.tupleof[1] = 2; // set foo.y to 2
foreach (x; foo.tupleof)
write(x);   // prints 12
}

wouldn't be able to set values to the original class instance via whatever 
.tupleof generates.

So the exact nature of the object produced by .tupleof is still a mystery to 
me. Would be good if someone threw more light on it.

Also: what is the use of presenting the members of a struct/class as a 
tuple? Is it iteration?

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


std.math: FloatingPointControl option to round to nearest + tie away from zero

2015-12-10 Thread Shriramana Sharma via Digitalmars-d
https://en.wikipedia.org/wiki/IEEE_floating_point#Roundings_to_nearest says 
that IEEE 754 provides two options for rounding to nearest: ties to even and 
ties away from zero. 

However, under 
https://github.com/D-Programming-Language/phobos/blob/master/std/math.d#L4539 
we have only one roundToNearest 
which, I presume, ties to even.

Is there a difficulty in providing the option for tieing away from zero?

Thanks.

-- 
Shriramana Sharma, Penguin #395953


Documentation of std.math: FloatingPointControl

2015-12-10 Thread Shriramana Sharma via Digitalmars-d
The enum members of FloatingPointControl are not documented individually at 
http://dlang.org/phobos/std_math.html and I would like to submit a PR for 
that. In connection with this, a few queries:

I note that there are already a few sparse ddoc comments such as at: 
https://github.com/D-Programming-Language/phobos/blob/master/std/math.d#L4539 
but they do not seem to be 
reflected in the generated documentation, presumably because they do not 
directly precede a symbol definition. This needs to be fixed. I propose to 
move it before the struct itself.

Finally I am looking at the enum value subnormalException at 
https://github.com/D-Programming-Language/phobos/blob/master/std/math.d#L4580 
which seems to be enabled in 
architectures other than PPC. The standard seems to define only 5 
exceptions: 
https://en.wikipedia.org/wiki/IEEE_floating_point#Exception_handling. So 
it's not clear what subnormalException refers to. Is it the "denormal 
operand exception" mentioned at 
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_handle.html?

Thanks.

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


%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


Short-circuit evaluation in D

2015-11-21 Thread Shriramana Sharma via Digitalmars-d
Hello. From http://dlang.org/expression.html#OrOrExpression and the 
subsequent AndAndExpression section it is clear to me that D does indeed 
employ short-circuit evaluation true to being part of the C family.

But I am disappointed to note that D is not mentioned at 
https://en.wikipedia.org/wiki/Short-circuit_evaluation.

I would edit it myself but the table also mentions eager operators and I'm 
not sure whether D has any such operators i.e. whether & and | are supposed 
to be eager in D as they are said to be (as per the table) in C++.

So I request someone more knowledgeable about D than me to do the edit and 
respond here too.

Thanks.

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


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


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


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


`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


Re: Please vote for the DConf logo

2015-11-10 Thread Shriramana Sharma via Digitalmars-d-announce
I prefer 3. It's simple, but effective. The graphic looks 
like an Olympic torch to me, which is good, indicating that D 
is a champion! :-)

IMHO 2 needs the graphic to be more stylistic, otherwise it's 
good and simple. If it is improved, maybe it can be used 
later/elsewhere.

But I don't get the message of 1. The graphic is too 
complicated, and the significance of its components is not 
self-evident.

Appreciate the work people are putting into this, though. No 
offence to any artist intended...

-- 
Shriramana Sharma, Penguin #395953


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


Dhee - tiny app to learn/try out D

2015-11-10 Thread Shriramana Sharma via Digitalmars-d-announce
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


  1   2   3   >