Re: extended characterset output

2022-04-08 Thread anonymous via Digitalmars-d-learn

On Friday, 8 April 2022 at 15:06:41 UTC, Ali Çehreli wrote:

On 4/8/22 02:51, anonymous wrote:

> Weird, I got this strange feeling that this problem stemmed
from the
> compiler I'm using (GDC)

Some distribution install an old gdc. What version is yours?

Ali


Not sure actually. I just did "apt install gdc" and assumed the 
latest available. Let me check. Here's the version output 
(10.3.0?):


anon@ymous:~/$ gdc --version
gdc (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  
There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE.





Re: extended characterset output

2022-04-08 Thread anonymous via Digitalmars-d-learn

On Friday, 8 April 2022 at 08:36:33 UTC, Ali Çehreli wrote:
[snip]
However, isControl() below won't work because isControl() only 
knows about the ASCII table. It would miss the unprintable 
characters above 127.

[snip]

This actuall works because I'm using std.uni.isControl() instead 
of std.ascii.isControl().




Re: extended characterset output

2022-04-08 Thread anonymous via Digitalmars-d-learn

On Friday, 8 April 2022 at 08:36:33 UTC, Ali Çehreli wrote:

On 4/7/22 23:13, anonymous wrote:
> What's the proper way to output all characters in the
extended character
> set?

It is not easy to answer because there are a number of concepts 
here that may make it trivial or complicated.


The configuration of the output device matters. Is it set to 
Windows-1252 or are you using Unicode strings in Python?


I'm running Ubuntu and my default language is en_US.UTF-8.


>
> ```d
> void main()
> {
>  foreach(char c; 0 .. 256)

'char' is wrong there because 'char' has a very special meaning 
in D: A UTF-8 code unit. Not a full Unicode character in many 
cases, especially in the "extended" set.


I think your problem will be solved simply by replacing 'char' 
with 'dchar' there:


  foreach (dchar c; ...


I tried that. It didn't work.

However, isControl() below won't work because isControl() only 
knows about the ASCII table. It would miss the unprintable 
characters above 127.


>  {
> write(isControl(c) ? '.' : c);
>  }
> }
> ```


Oh okay, that may have been the reason.


This works:

import std.stdio;

bool isPrintableLatin1(dchar value) {
  if (value < 32) {
return false;
  }

  if (value > 126 && value < 161) {
return false;
  }

  return true;
}

void main() {
  foreach (dchar c; 0 .. 256) {
write(isPrintableLatin1(c) ? c : '.');
  }


Nope... running this code, I get a bunch of digits as the output. 
The dot's don't even show up. Maybe I'm drunk or lacking sleep.


Weird, I got this strange feeling that this problem stemmed from 
the compiler I'm using (GDC) so I installed DMD. Would you 
believe everything worked fine afterwords? To include the 
original version where I used isControl and 'dchar' instead of 
'char'. I wonder why that is?


Thanks Ali.


extended characterset output

2022-04-08 Thread anonymous via Digitalmars-d-learn
What's the proper way to output all characters in the extended 
character set?


```d
void main()
{
foreach(char c; 0 .. 256)
{
   write(isControl(c) ? '.' : c);
}
}
```

Expected output:
```
 
!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[.]^_`abcdefghijklmnopqrstuvwxyz{|}~..¡¢£¤¥¦§¨©ª«¬.®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

```

Actual output:
```
 
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~.

```

Works as expected in python.

Thanks


Re: Get pointer or reference of an element in Array(struct)

2017-12-08 Thread anonymous via Digitalmars-d-learn
On Saturday, 9 December 2017 at 06:15:16 UTC, Arun Chandrasekaran 
wrote:
Is there a way to get the pointer or reference of an element in 
Array(T)?

[...]

auto d2 = gallery[0];


auto d2 = [0];


What is this error message telling me?

2017-04-11 Thread Anonymous via Digitalmars-d-learn
I was watching a dconf presentation from last year and wanted to 
try this out: https://github.com/luismarques/parnas72. It doesn't 
compile / run as it is and the problem seems to be in the 
function below.


import std.algorithm;
import std.range;
import std.uni;
/// Performs [["foo", "bar"], ["baz"]] -> ["baz", "foo bar"]
auto alphabetized(Range)(Range range)
{
return range
.map!(line => line.joiner(" "))
.array
.sort!((a, b) => icmp(a, b) < 0);
}

void main()
{
auto a = alphabetized([["foo", "bar"], ["baz"]]);
}


More specifically, icmp doesn't seem to be allowed as the 
predicate for sort:


Here's the error message I get:

C:\D\dmd2\windows\bin\..\..\src\phobos\std\uni.d(7082): Error: 
function 'std.algorithm.searching.skipOver!(Result, 
dstring).skipOver' is not nothrow
C:\D\dmd2\windows\bin\..\..\src\phobos\std\uni.d(7055): Error: 
nothrow function 'std.uni.fullCasedCmp!(Result).fullCasedCmp' may 
throw
C:\D\dmd2\windows\bin\..\..\src\phobos\std\uni.d(7136): Error: 
template instance std.uni.fullCasedCmp!(Result) error 
instantiating

test.d(14):instantiated from here: icmp!(Result, Result)
C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm\sorting.d(1851):
instantiated from here: __lambda3!(Result, Result)
test.d(14):instantiated from here: sort!((a, b) => 
icmp(a, b) < 0, cast(SwapStrategy)0, Result[])
test.d(19):instantiated from here: 
alphabetized!(string[][])

C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm\sorting.d(1863): Error: static 
assert  "Invalid predicate passed to sort: __lambda3"
test.d(14):instantiated from here: sort!((a, b) => 
icmp(a, b) < 0, cast(SwapStrategy)0, Result[])
test.d(19):instantiated from here: 
alphabetized!(string[][])



My question is, how do I begin to understand error messages like 
the above? I looked at the signature for sort and icmp and don't 
get what the problem is.


Thanks.




Re: how to mark an extern function @nogc?

2016-07-12 Thread anonymous via Digitalmars-d-learn

On Tuesday, 12 July 2016 at 14:04:55 UTC, Seb wrote:
D is entirely driven by highly motivated volunteers. (this will 
change soon with the new D foundation)


With the fundation, volunteers wont be highly motivated anymore. 
Fundations are real motivation-killers.






Re: Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

On Monday, 6 June 2016 at 02:21:03 UTC, docandrew wrote:

On Sunday, 5 June 2016 at 21:26:56 UTC, Anonymous wrote:

On Sunday, 5 June 2016 at 21:16:36 UTC, Andrej Mitrovic wrote:
On 6/5/16, Anonymous via Digitalmars-d-learn 
<digitalmars-d-learn@puremagic.com> wrote:

[...]


You can report it here: https://issues.dlang.org


[...]


null is simpler from a reader's perspective. :)


[...]


Interesting that they would use such code in the book. Which 
chapter is it?


Thanks. I agree it's simpler and switched to `null`.

The example is in chapter 3.


That it works on OSX but not on Windows makes me think it 
should definitely be reported as a bug.


-Jon


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


Re: Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

On Sunday, 5 June 2016 at 21:16:36 UTC, Andrej Mitrovic wrote:
On 6/5/16, Anonymous via Digitalmars-d-learn 
<digitalmars-d-learn@puremagic.com> wrote:
Should I report this as a dmd bug then? Not sure where / how 
to do that.


You can report it here: https://issues.dlang.org

I think I'll just let it go; I was able to work passed it 
anyway using "static Note[] empty;", and `null` works too. Is 
either one better?


null is simpler from a reader's perspective. :)

By the way, this is from an example I found in "D Web 
Development" by Kai Nacke.


Interesting that they would use such code in the book. Which 
chapter is it?


Thanks. I agree it's simpler and switched to `null`.

The example is in chapter 3.


Re: Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

On Sunday, 5 June 2016 at 20:16:54 UTC, Andrej Mitrovic wrote:
On 6/5/16, Anonymous via Digitalmars-d-learn 
<digitalmars-d-learn@puremagic.com> wrote:

static Note[0] empty;

Note[] getNotes(string id)
{
return (id in store) ? store[id] : empty;
}


It's likely an accepts-invalid bug, meaning it should be a 
compiler error instead. I don't think it makes sense that the 
compiler tries to slice a fixed-length array of length zero.. 
tho perhaps it should just equate that to returning null.


In any case you can return `null` instead of "empty". 
Fixed-length arrays of length zero aren't really all that 
well-defined. Some would say they make no sense, but there is a 
weird benefit to them when used with the built-in hashmaps (a 
void[0] value type wouldn't allocate memory, AFAIR and if that 
is still true).


Should I report this as a dmd bug then? Not sure where / how to 
do that.


I think I'll just let it go; I was able to work passed it anyway 
using "static Note[] empty;", and `null` works too. Is either one 
better?


By the way, this is from an example I found in "D Web 
Development" by Kai Nacke.


Re: Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

On Sunday, 5 June 2016 at 18:45:36 UTC, docandrew wrote:

On Sunday, 5 June 2016 at 18:36:13 UTC, Anonymous wrote:

On Sunday, 5 June 2016 at 18:30:25 UTC, Anonymous wrote:

[...]


Should have included:

OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
ns.obj(ns)  Offset 0BA0AH Record Type 009D
 Error 16: Index Range
--- errorlevel 1


Hmm, on OSX w/ dmd v2.071.0 I'm unable to duplicate. Can you 
try upgrading to v2.071 and see if that works?


-Jon


I upgraded, but I still get the same error:

dmd ns.d

 OPTLINK (R) for Win32  Release 8.00.17
 Copyright (C) Digital Mars 1989-2013  All rights reserved.
 http://www.digitalmars.com/ctg/optlink.html
 ns.obj(ns)  Offset 00678H Record Type 009D
  Error 16: Index Range
 --- errorlevel 1

dmd --version
DMD32 D Compiler v2.071.0
Copyright (c) 1999-2015 by Digital Mars written by Walter Bright


Re: Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

On Sunday, 5 June 2016 at 18:30:25 UTC, Anonymous wrote:

Why does the following give a linker error?

If I change static Note[0] empty; to static Note[] empty;, all 
is well.
Or if I leave it as Note[0] empty; and don't use it in 
getNotes, all is well.


struct Note
{
string topic;
string content;
}

class NoteStore
{   

Note[][string] store;

static Note[0] empty;

Note[] getNotes(string id)
{
return (id in store) ? store[id] : empty;
}   
}

void main() {}

dmd --version
DMD32 D Compiler v2.070.0
Windows 10


Should have included:

OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
ns.obj(ns)  Offset 0BA0AH Record Type 009D
 Error 16: Index Range
--- errorlevel 1


Linker error

2016-06-05 Thread Anonymous via Digitalmars-d-learn

Why does the following give a linker error?

If I change static Note[0] empty; to static Note[] empty;, all is 
well.
Or if I leave it as Note[0] empty; and don't use it in getNotes, 
all is well.


struct Note
{
string topic;
string content;
}

class NoteStore
{   

Note[][string] store;

static Note[0] empty;

Note[] getNotes(string id)
{
return (id in store) ? store[id] : empty;
}   
}

void main() {}

dmd --version
DMD32 D Compiler v2.070.0
Windows 10


Re: How to return a const handle (view) to a mutable member of an agregate

2016-03-13 Thread anonymous via Digitalmars-d-learn

On Sunday, 13 March 2016 at 22:34:54 UTC, Chris Wright wrote:
In theory, it can't be modified. As a practical matter, unions 
and casts will allow people to modify it.


Saying that it *can't* be modified is slightly besides the point, 
yeah. It *must* not be modified. Casting away const and then 
mutating will probably just work as expected much of the time. 
But it's not allowed by the language. One must not do it.


I think it's important not to give the impression that it's ok in 
practice to cast away const and then mutate.


By the way, I don't think unions are in the exact same boat as 
casts here. With a union of const and mutable types, I'd say it's 
perfectly fine to mutate the data through the mutable one. Such a 
union is similar to having const and mutable pointers to the same 
data. Unions of immutable and mutable types are weird, though.


Decorating your code with @safe is intended to prevent these 
holes (and other types of unsafe code).


But even in non-@safe code, the compiler doesn't just accept 
mutating through a const reference. It requires a cast, which is 
an explicit signal to just do what the programmer says. There's a 
similar signal for ignoring @safe: @trusted.


Re: How to return a const handle (view) to a mutable member of an agregate

2016-03-13 Thread anonymous via Digitalmars-d-learn

On Sunday, 13 March 2016 at 20:10:57 UTC, Basile B. wrote:

ref const(Array!Type) view(){}

Unless the result is explicitly cast later it can't me modified.


No, it can't be modified, period. Casting away const and then 
mutating is not allowed, it has undefined behavior.


Re: template mixins vs alias

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

On Monday, 22 February 2016 at 13:35:10 UTC, Andrea Fontana wrote:

Check this code:
http://dpaste.dzfl.pl/fcf876acbbdc

Structs A and B do the same things, in different way.

Is there any difference/limitation between those?

Andrea


The mixin variant generates a method. That means, you can 
reference members of the struct in the function.


Silly example:

mixin template Test(T)
{
auto returnX() { return x; }
}
struct A
{
int x;
mixin Test!int;
}


With the alias variant you get an alias to a free function, not a 
method. So you couldn't reference x like above.


What's nicer about the alias version is that you see what symbol 
is being generated. It's obvious that `alias returnInit = 
returnInitImpl!int;` creates a symbol "returnInit". In the mixin 
variant, you have to read the template's source to see that.


Re: compilation issues (dmd, rdmd, ldc2)

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

On 21.02.2016 22:51, kraxli wrote:

On Sunday, 21 February 2016 at 21:35:55 UTC, anonymous wrote:

[...]

a) do it the linker way: `dmd -L-L~/.dub/packages/consoled-1.0.0/
-L-lconsoled ...`, or
b) do it the dmd way: `dmd
~/.dub/packages/consoled-1.0.0/libconsoled.a ...`.


b) works! :-) Many thanks!!
a) doesn't work, I need to search for more information on linking as I
would like to understand these kind of basics in D :-). The books I
consulted so far (Learn D and D cookbook) did not help me to understand
the linking so far ...


I investigated a bit on option a. The tilde (~) is the problem. Tilde 
expansion is only done when it's the first character of a word. So you 
either have to replace the tilde with "/home/foo", or somehow make it 
the first character of a word for the shell. Since you can't just put a 
space there, you would have to hack around a bit. For example:


dmd -L-L`echo ~`/.dub/packages/consoled-1.0.0/ ...

Regarding learning about linking: dmd's -L flag just forwards its 
argument to the linker. The linker isn't D-specific. To learn about 
linking in D you can learn about compiling/linking in general (what's a 
compiler, what's a linker, what's an object file, etc.), and you can 
learn about the command line interface of the specific linker that dmd 
invokes.


On Ubuntu, dmd calls gcc for linking, which in turn calls ld. So if you 
want to know what to put into those -L arguments, you have to learn the 
gcc/ld command lines.


Re: compilation issues (dmd, rdmd, ldc2)

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

On Sunday, 21 February 2016 at 21:21:30 UTC, kraxli wrote:
Thanks for coming back on that! The problem is the 
consoled-package which has the library:

~/.dub/packages/consoled-1.0.0/libconsoled.a

So I link it (or aim to do it ;-) ) but dmd cannot find it:

$ dmd -I~/.dub/packages/consoled-1.0.0/source  
-L-l~/.dub/packages/consoled-1.0.0/libconsoled  appX.d
/usr/bin/ld: cannot find 
-l~/.dub/packages/consoled-1.0.0/libconsoled

collect2: error: ld returned 1 exit status
--- errorlevel 1


I don't think it works like that. If I remember correctly, you 
can either
a) do it the linker way: `dmd -L-L~/.dub/packages/consoled-1.0.0/ 
-L-lconsoled ...`, or
b) do it the dmd way: `dmd 
~/.dub/packages/consoled-1.0.0/libconsoled.a ...`.


I don't know what's going on there, but there shouldn't be a 
std/range.d with recent versions of phobos. It's a package 
since 2.067.0. Maybe a leftover from a previous installation?


I just reinstalled it and it seems as it would have installed 
in the directory mentioned by ldc2:

-- Installing: /usr/local/include/d/std/range
-- Installing: /usr/local/include/d/std/range/primitives.d
-- Installing: /usr/local/include/d/std/range/package.d
-- Installing: /usr/local/include/d/std/range/interfaces.d


But is there a file /usr/local/include/d/std/range.d? If so, 
that's apparently not from your latest install, and it may 
confuse ldc. If there is no such file, then I can't make any 
sense of the error messages.


Re: compilation issues (dmd, rdmd, ldc2)

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

On Sunday, 21 February 2016 at 20:04:34 UTC, kraxli wrote:
What is going on here and what is the difference between dmd 
and rdmd?


dmd compiles the modules that you specify on the command line. By 
default, it then links an executable from the generated object 
files. The linking can only work when you give dmd all the code, 
either in source form or in compiled object form. When something 
is missing, you get "undefined reference" errors.


That means, when your program has multiple source files 
(including libraries), you must put them all on the dmd command 
line. Or you can compile modules individually (without linking, 
-c flag), and then put the generated object files on the command 
line when linking.


rdmd is a wrapper around dmd (or another, compatible compiler). 
It reads the dependency tree of the modules, and runs dmd on all 
of the source files at once. That means, you only need to put the 
root module on the command line for rdmd. rdmd reads the imports 
and generates a full list of source files for dmd.


Moreover, ldc2 has conflicts with modules which is probably due 
to installation, linking and scope issues. How can I shrink the 
scope for ldc2 such that it only looks at the "right place" for 
modules (and where is that?) ?


$ ldc2 -I~/.dub/packages/consoled-1.0.0/source/  appX.d
/usr/local/include/d/std/range.d(287): Error: module std.range 
from file /usr/local/include/d/std/range.d conflicts with 
package name range


I don't know what's going on there, but there shouldn't be a 
std/range.d with recent versions of phobos. It's a package since 
2.067.0. Maybe a leftover from a previous installation?


Re: Confusion regarding struct lifecycle

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

On 17.02.2016 17:36, Matt Elkins wrote:

I tried this, and got the same issue. Actually, I was still able to
reproduce the original reported issue as well, which leads me to believe
either the bug was not actually fixed or (and this is more likely) I
screwed something up with my install. Do I need to do anything special
to install a nightly build (I'm on Windows)?


For reference, link to the issue:
https://issues.dlang.org/show_bug.cgi?id=15661

As you can see on the bugzilla page, the fix was pushed to the 'stable' 
branch. But nightlies are probably built from 'master'. So the fix isn't 
in the nightlies until 'stable' gets merged into 'master'. At the 
latest, that should happen again with the 2.071 release.


You can build a 'stable' dmd from git. I just did that and I can say 
that the test code for issue 15661 now prints



HERE1a
HERE1b
HERE2


which seems to be the correct output, indicating that the issue got fixed.

However, the code from this thread still prints


Before 8
Before 1
Foo being destroyed: 0
Before 2
Foo being destroyed: 0
Before 3
Foo being destroyed: 0
After Foo construction
About to lose scope
Foo being destroyed: 0
Foo being destroyed: 3
Foo being destroyed: 2
Foo being destroyed: 1 


Foo being destroyed: 8


So, different issue?


Re: static array of structs clarification questions

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

On 12.02.2016 22:08, WhatMeWorry wrote:

question #1: The static array must contain the fat pointers to str
variables. But where is the string data itself actually held: the stack?
the heap? somewhere else? (does it vary depending on location or scope)


Depends on how the string was created. You can create dynamic arrays 
over any memory. (Remember: string is an alias of immutable(char)[], 
i.e. a dynamic array.)


I'm not sure where strings from literals are located. Could be some 
static data section in the executable, or some such. That's beyond me.



question #2: If the above struct was to contain the same struct and the
second one contains a third, how would the lower structs be allocated?
Is it "turtles all the way down?


Struct data is put right where the variable is. Unlike classes and 
arrays, structs are not references to some other location.


When a struct has a struct member, then the data of the member is put 
right next to the parent's data. The size of the member is added to the 
parent's size.


One consequence of this is that you can't have trees with just structs: 
`struct Node {Node left; Node right;}` - not gonna fly.



question #2: Of what use is the nulls in the array elements? When I took
out the member function: void info(), the nulls went away.


My guess is that you declared the struct in a function (e.g. main), and 
the null is the context pointer. Put the struct declaration at module 
scope, or make it `static`, and the null thing should go away.


A context pointer is needed when the struct references data from the 
surrounding function scope. You don't do that here, but the compiler is 
apparently not smart enough to figure that out.


Re: why mkdir can't create tree of dirs?

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

On Tuesday, 9 February 2016 at 20:20:59 UTC, Suliman wrote:
It's look like that I can only create one nesting level sub 
folder, for example there is exists dir: D:\foo

I can't create dir D:\foo\bar\baz I can only create D:\foo\bar


http://dlang.org/phobos/std_file.html#.mkdirRecurse


td.windows.syserror.WindowsException@C:\D\dmd2\windows\bin\..\..\src\phobos\stdfile.d(2048):
 F:\foo\imgs_projected\jma_vis\1602\123: ╨б╨╕╤Б╤В╨╡╨╝╨╡ ╨╜╨╡ ╤Г╨┤╨╨╡╤В╤Б╤П 
╨╜╨░╨╣╤В╨╕ ╤Г╨║╨░╨╖╨░╨╜╨╜╤Л╨╣ ╨┐╤Г╤В╤М. (error 3)


What's up with that garbled text?


Re: UFCS on Enum in Member Function

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

On Tuesday, 9 February 2016 at 21:05:50 UTC, jmh530 wrote:
For instance, in the code below, I could use Baz but not Caz. 
It seems to work when I use the alternate version of Caz 
calling a non-member function.


Bug?


No bug; works as intended. UFCS can only be used with free 
functions, not with methods.


Re: Odd Destructor Behavior

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

On 07.02.2016 22:49, Matt Elkins wrote:

 From this non-reduced situation, does anything jump out? Am I missing
something about struct lifetimes? This is the only place I instantiate a
TileView.


Looks weird. I presume this doesn't happen with simpler constructor 
parameters/arguments, like int instead of Texture.Handle? I don't see 
how the parameter types would make a destructor call appear. Might be a bug.


Can you post the code for Texture, makeInputStream, etc, so that we have 
a full, reproducible test case?


Re: Odd Destructor Behavior

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

On 07.02.2016 23:07, Márcio Martins wrote:

The destructor you are seeing is from the assignment:

m_tileView = TileView(...);

This creates a temporary TileView, copies it to m_tileView, and then
destroys it. I suppose you want to move it instead. You need to copy the
handles from the temporary into the destination, and then clear them out
from the temporary to prevent them from being released.


I think you're mistaken here. The result of a struct literal is usually 
moved implicitly.


Code:

import std.stdio;

struct S
{
~this() {writeln("dtor");}
}

void main()
{
auto s = S();
writeln("end of main");
}


Output:

end of main
dtor


If there was a copy that's destroyed after the assignment, there should 
be another "dtor" before "end of main".


Re: Odd Destructor Behavior

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

On 07.02.2016 23:49, Matt Elkins wrote:

Oi. Yes, I can, but it is quite a lot of code even if you don't count
that it is dependent on OpenGL, GLFW, and gl3n to run to this point.
This is why I was disappointed that simpler reproducing cases weren't
appearing. I should probably spend more time trying to reduce the case
some...


Minimal test cases are great, but if you're not able to get it down in 
size, or not willing to, then a larger test case is ok, too. The problem 
is clear, and I'd expect reducing it to be relatively straight-foward 
(but possibly time-consuming). Just don't forget about it completely, 
that would be bad.


Also be aware of DustMite, a tool for automatic reduction:

https://github.com/CyberShadow/DustMite


Re: foreach seems to work with opIndex()

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

On 06.02.2016 15:43, Tofu Ninja wrote:

Foreach seems to work if there is an opIndex() with no arguments that
returns a range interface, is this documented? I can't seem to find
anything that say this is supposed to happen. I am not really
complaining, its nice, but I just didnt really expect it because I feel
like I remember this being an error some time ago.


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


Re: DMD OSX / Segfault 11

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

On 03.02.2016 14:16, Robert M. Münch wrote:

Well, it should of course be:

BaseOperator: Value {
}


Still missing "class". I know I'm being pedantic, but if you're being 
sloppy here, how do I know that you're not being sloppy where it matters?



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


Yes, that's what I need.


Do that then. Cast between class types. Pointers don't by you anything here.


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


I tried this, but that doesn't work either.


Yeah, you can't check if the downcast succeeded this way. Casts between 
pointers always succeed (and then fail horribly at run-time).



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


But am I not getting a copy then? I want to avoid copying objects as
much as possible.


No, you're not getting a copy. Classes are reference types. That means, 
variables of class types are references already. They're pointers in 
disguise.


Re: How do you get a hexstring from a base10 string -or- from a number?

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

On 04.02.2016 00:45, Enjoys Math wrote:

On Wednesday, 3 February 2016 at 23:43:45 UTC, Enjoys Math wrote:
body { // is currently:
   return to!string(this.toHash());
}

and is returning a base10 string, so how would I return a hex string so
I can compare numbers displayed to the debugger addresses in visual D?


to!string has an optional radix (aka base) parameter:

  return to!string(this.toHash(), 16);


Re: Why this code can't take advantage from CTFE?

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

On 03.02.2016 16:34, Andrea Fontana wrote:

void main()
{
 enum first = very_very_long_function(10);
 writeln("First is ", first);

 auto second = very_very_long_function(12);
 writeln("Second is ", second);

 auto third = first;
 third += 1;
 writeln("Third is ", third);
}

Why second init doesn't work with CTFE? It could be something like
third, but with one less copy. What am I missing?


The compiler doesn't try to apply CTFE everywhere, because it could take 
forever. So CTFE is only done when the programmer requests it by using a 
function in a static context.


The compiler is still free to precompute the value at compile time, if 
it thinks that's a good idea, but that's just an optimization. And while 
it's evaluation of a function at compile time, it's not CTFE in the 
sense of __ctfe.


Re: const and immutable member variables in classes

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

On 02.02.2016 23:48, Ali Çehreli wrote:

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

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

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

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


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


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


Re: DMD OSX / Segfault 11

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

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

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

Value: {}

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

BaseOperator: Value : {
}


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



Now comes the code using this:

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


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


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


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


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


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


Re: Switch with dynamic case

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

On 02.02.2016 15:07, Daniel Kozak wrote:

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

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

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

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


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


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


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

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

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

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


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


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



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

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

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

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


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


There are at least two open issues related to this:

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

Everything works fine when breaking the switch with a label:


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


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


Re: Declaring rvalue function arguments

2016-01-31 Thread anonymous via Digitalmars-d-learn

On 31.01.2016 18:21, Matt Elkins wrote:

I know I can mark an argument ref to require lvalues, so I'm wondering
whether there is an equivalent for rvalues; that is, is there a way to
specify that an argument to a function MUST be an rvalue?

For example, in C++ I can do this:
[code]
void foo(int && x) {...}

foo(5); // Works fine
int y = 5;
foo(y); // Compile error; y is not an rvalue
[/code]

This functionality turns out to be really useful when dealing with
transferring ownership of resources.


I don't know if this works in all cases, but it passes that simple test:


@disable void foo(ref int x);
void foo(int x) {}

void main()
{
foo(5); /* works */
int y = 5;
foo(y); /* error */
}



Re: Problem when calling toJSON()

2016-01-31 Thread anonymous via Digitalmars-d-learn

On 01.02.2016 01:29, Alex Herrmann wrote:

This problem is solved! Sorry for not updating the question.

It was actually a problem with me not iduping it, and the memory being
reclaimed or something similar. I did also change to stdx.data.json
(std_data_json on dub).


You don't seem to be clear on what exactly went wrong. So here's an 
explanation:


On 31.01.2016 23:52, Alex Herrmann wrote:
>  auto outmd5 = JSONValue(cast(string) toHexString(md5_hash));

That cast is bad. You're casting a fixed-size char array to string, 
effectively slicing it. The data will get corrupted when the fixed-size 
array goes out of scope. Which happens immediately here, as you don't 
store the result of the toHexString call anywhere.


As you mentioned, .idup instead of cast is the proper way to do this. 
std.conv.to!string is another option.


Generally, casts should be avoided. It's easy to mess up with them in 
subtle ways.


Re: How do you initialize a class instance which has static storage within another class?

2016-01-30 Thread anonymous via Digitalmars-d-learn

On 30.01.2016 22:52, Enjoys Math wrote:


class A { static B b; } class B {}

doing b = new B() does NOT work.

Nor could I create a this() {} at module level


It works when you make b const/immutable:

class A {static immutable B b = new B;} class B {}

If you want/need b to be mutable, you can use a static constructor 
(`static this`), either in the class or the module:


class A {static B b; static this() {b = new B;}} class B {}
class A {static B b;} static this() {A.b = new B;} class B {}

You could also set it in `main` or another function that runs before b 
is used, of course.


Re: Error using templates: "cannot use template to add field to aggregate ''"

2016-01-25 Thread anonymous via Digitalmars-d-learn

On 25.01.2016 15:51, pineapple wrote:

class unitvalue{
 double coefficient;
 int[unit] exponents;

 unitvalue copy(){
 unitvalue value = new unitvalue();
 value.coefficient = this.coefficient;
 value.exponents = this.exponents.dup;
 return value;
 }

 template opmethod(string methoddef, string methodcall){
 const char[] methodtemplate =


Can't have variables like that in templates. Make it a "manifest 
constant" with  enum. Also, if you want opmethod!("foo", "bar") to 
evaluate to the code, then methodtemplate needs to be renamed to 
"opmethod". I.e., make this line:


enum opmethod =


Also, opmethod doesn't need to be template. A function would work as well:

static string opmethod(string methoddef, string methodcall)
{
return
"unitvalue " ~ methoddef ~ "{
unitvalue copy = this.copy();
copy." ~ methodcall ~ ";
return copy;
}"
;
}

mixin(unitvalue.opmethod(
"sum(in unitvalue value)", "add(value)"
));



 "unitvalue " ~ methoddef ~ "{
 unitvalue copy = this.copy();
 copy." ~ methodcall ~ ";
 return copy;
 }"
 ;
 }

 mixin(unitvalue.opmethod!(
 "sum(in unitvalue value)", "add(value)"
 ));
 void add(in unitvalue value){
 if(!this.samedimensions(value)){
 throw new Exception("Cannot add values of differing
dimensions.");
 }else{
 this.coefficient += value.coefficient;
 }
 }

 bool samedimensions(in unitvalue value){
 return this.exponents == value.exponents;


This gives me an error, too: "Error: incompatible types for 
((this.exponents) == (value.exponents)): 'int[int]' and 'const(int[int])'"


(I've aliased unit to int.)

As far as I can tell, this should work. There's a bugzilla issue for it:
https://issues.dlang.org/show_bug.cgi?id=13622

You can work around the bogus error message by using a const temporary 
for this.exponent:


const this_exponents = this.exponents;
return this_exponents == value.exponents;



 }
}





Re: Templates, templates, templates...

2016-01-24 Thread anonymous via Digitalmars-d-learn

On 24.01.2016 10:02, Voitech wrote:

I added base class for Rule -> BaseRule. But this class is just a shell
without implementation.
Is there any way to avoid this ?


What's the problem with BaseRule not having any implementation? When the 
different Rule instantiations don't have any common operations that can 
be put there, then BaseRule's purpose is only to be a common supertype.


Re: core.thread.Thread.start is marked as "nothrow" but documentation says it throws

2016-01-23 Thread anonymous via Digitalmars-d-learn

On 23.01.2016 12:44, tcak wrote:

https://dlang.org/phobos/core_thread.html#.Thread

final nothrow Thread.start()

Looking at the code, no "throw new ..." is seen, but the function
"onThreadError" is called
which has "throw" in it.

Most weird thing is that "onThreadError" function is marked as "nothrow"
but it still throws.

I would think that yes, maybe the compiler might not be able to see it
because throw is found
in another function, but how come "onThreadError" throws with nothrow.


onThreadError [1] throws a ThreadError [2] which derives from Error, as 
the name suggests. nothrow functions may throw Errors, because Errors 
are considered a way of force-exiting the program. Errors are not 
supposed to be caught.


So onThreadError is fine. And if Thread.start can actually only throw 
ThreadError, and not ThreadException, then that one is ok too, but the 
documentation is wrong and should be fixed.



[1] 
https://github.com/D-Programming-Language/druntime/blob/33f1962747801be35a48f4875c909e16747fdcce/src/core/thread.d#L2972
[2] 
https://github.com/D-Programming-Language/druntime/blob/33f1962747801be35a48f4875c909e16747fdcce/src/core/thread.d#L88


Re: Templates, templates, templates...

2016-01-23 Thread anonymous via Digitalmars-d-learn

On 23.01.2016 12:30, Voitech wrote:

Ok so i want to hold different types in LogicRule maybe Algebraic
implementation would do?

private alias ControllTemplate(T) =Rule!(T,ControllFlag);
private alias SymbolRule =ControllTemplate!(SymbolType);
private alias StringRule =ControllTemplate!(SymbolRule[]);
private alias LogicTemplate(T...)
=Rule!(Algebraic!(ControllTemplate(T))[],LogicFlag); <--error


You're missing an exclamation mark there, and you've got the order of 
Algebraic and ControllTemplate wrong. This compiles:


private alias LogicTemplate(T...) = 
Rule!(ControllTemplate!(Algebraic!T)[],LogicFlag);



private alias AlgebraicLogicRule = LogicTemplate!(SymbolRule,StringRule);

error:
Error: cannot pass type (Rule!(SymbolType, ControllFlag),
Rule!(Rule!(SymbolType, ControllFlag)[], ControllFlag)) as a function
argument

[...]

Is there any nicer way to handle this case ?


Instead of Algebraic you could use a common base class, or interface, 
for the Rule instantiations:


abstract class RuleBase
{
... whatever common functionality rules have ...
}
class Rule(V,F) : RuleBase { ...}

But I have to say that I'm having trouble making sense of all that class 
and template complexity, and how it helps in actually validating user input.


Since this is a parsing thing, you may want to look into writing parsers 
an/or using a parse generator. I think Pegged is the most popular one 
for D. http://code.dlang.org/packages/pegged


Re: D ASM. Program fails

2016-01-22 Thread anonymous via Digitalmars-d-learn

On 22.01.2016 21:34, Iakh wrote:

This code returns 0 for any input v


It seems to return 5 here: http://dpaste.dzfl.pl/85fb8e5c4b6b


Re: D ASM. Program fails

2016-01-22 Thread anonymous via Digitalmars-d-learn

On 22.01.2016 06:59, Iakh wrote:

import std.stdio;
import core.simd;

int pmovmskb(inout byte16 v)
{
 asm
 {
 movdqa XMM0, v;
 pmovmskb EAX, XMM0;
 ret;
 }
}
void main()
{
 byte16 a = [-1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
 auto i = pmovmskb(a);
}


I don't know much about these things, but it seems to be the `ret;`.

This doesn't segfault:

int pmovmskb(byte16 v)
{
int r;
asm
{
movdqa XMM0, v;
pmovmskb EAX, XMM0;
mov r, EAX;
}
return r;
}


Removed the `inout` because it doesn't make sense. You may be looking 
for `ref`.


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

2016-01-22 Thread anonymous via Digitalmars-d-learn

On 22.01.2016 10:56, Shriramana Sharma wrote:

Do all values which need to
be readable at compile time need to be declared `immutable`?


Yes, `static immutable` or `enum`.


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?


Yes, it's the same in D.

But without `immutable` you could make `func` return a different value 
per call, i.e. `func` would not be pure. Impure compile time 
calculations are not allowed. One reason for that is that it would 
require specifying an order in which they're done, which would be weird, 
especially with separate compilation of modules.



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


Yes, without `immutable` they're not constants to the compiler.


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

2016-01-22 Thread anonymous via Digitalmars-d-learn

On 22.01.2016 15:33, Shriramana Sharma wrote:

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


The link doesn't work for me, but yes, `static immutable` is usually 
better for arrays than `enum`.



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?


I guess compilers may reuse the same array for all calls, seeing that 
the value is a constant, but I don't think they're required to do so.


Re: writeln wipes contents of variables ?

2016-01-21 Thread anonymous via Digitalmars-d-learn

On 22.01.2016 01:49, W.J. wrote:

How can I identify those ranges, or, how can I tell if any particular
range has value semantics ? I didn't read any of this in the manual -
not that I could remember anyways.


Generally you shouldn't. If you care about it either way, use .save or 
std.range.refRange.


If you don't want some range r to be consumed by some operation, pass 
r.save instead of plain r. If you want r to be consumed, pass 
refRange(). Only if you don't care if r is consumed or not, should you 
pass simply r.


If you know for a fact that copying r is the same as r.save, then you 
can just pass (and copy) r, of course. We know it's that way with 
dynamic arrays, because of their nature as pointer+length structures. 
But there's nothing wrong with calling .save on an array anyway.


Also, when a function takes a range via a ref parameter, then you don't 
need refRange, of course. The ref parameter ensures that no copy is made 
and that the original range is affected by the function.


Re: Unions and Structs

2016-01-18 Thread anonymous via Digitalmars-d-learn

On 18.01.2016 18:10, Russel Winder via Digitalmars-d-learn wrote:

So this is an error?

union flob {
ulong data;
struct thingy {
uint data;
uint bits;
}
thingy burble;
};

because you cannot have a union field with a name that is also the name
of a struct field defined within the union.


I don't see the problem. You have to access the thingy's 'data' through 
the 'burble' member, so there is no ambiguity, is there?


This would be different, and dmd rejects it accordingly:

union flob {
ulong data;
struct {
		uint data; /* test.d(4): Error: variable test.flob.data conflicts with 
variable test.flob.data at test.d(2) */

uint bits;
}
}




copying directories recursively

2016-01-17 Thread anonymous via Digitalmars-d-learn

TL;DR: Is there a simple way to copy directories recursively?

My goal is to copy the directories ./src/dlang.org/{css,images,js} and 
their contents to ./ddo/{css,images,js}.


Naively I tried this:


void main()
{
import file = std.file;
auto outputPath = "./ddo/";
foreach (dir; ["css", "images", "js"])
{
file.copy("./src/dlang.org/" ~ dir, outputPath ~ dir);
}
}


But that fails with "std.file.FileException@std/file.d(3154): 
src/dlang.org/css: Is a directory".


`copy` doesn't have a parameter to enable copying directories, and I 
can't find any `copyDir` or `copyRecurse` or some such.


As it looks I'll end up implementing my own `copyRecurse`:


void copyRecurse(string from, string to)
{
import std.file: copy, dirEntries, isDir, isFile, mkdirRecurse, 
SpanMode;

import std.path: buildNormalizedPath, buildPath;

from = buildNormalizedPath(from);
to = buildNormalizedPath(to);

if (isDir(from))
{
mkdirRecurse(to);

auto entries = dirEntries(from, SpanMode.breadth);
foreach (entry; entries)
{
auto dst = buildPath(to, entry.name[from.length + 1 .. $]);
// + 1 for the directory separator
if (isFile(entry.name)) copy(entry.name, dst);
else mkdirRecurse(dst);
}
}
else copy(from, to);
}


Is there a simpler way to do this?


Re: Functions that return type

2016-01-16 Thread anonymous via Digitalmars-d-learn
On Saturday, 16 January 2016 at 21:22:15 UTC, data pulverizer 
wrote:
Is it possible to create a function that returns Type like 
typeof() does? Something such as:


Type returnInt(){
return int;
}


No. A function cannot return a type. A template can evaluate to a 
type, though:



template returnInt(){
alias returnInt = int;
}



More to the point what is the Type of a type such as int?


Types don't have types. You can check if something is a type with 
an IsExpression: `is(T)` is true if T is a type.


Re: Index a parameter tuple with a run-time index

2016-01-15 Thread anonymous via Digitalmars-d-learn

On 15.01.2016 21:42, Nordlöw wrote:

How do I index a function parameter tuple with a run-time index?


With a switch and a static foreach:


void f(A...)(size_t i, A a)
{
import std.stdio: writeln;
switch_: switch (i)
{
foreach (iT, T; A)
{
case iT: writeln(T.stringof); break switch_;
}
default: writeln("??"); break;
}
}

void main()
{
f(0, "foo", 42); /* string */
f(1, "foo", 42); /* int */
f(2, "foo", 42); /* ?? */
}



Re: How to declare an alias to a function literal type

2016-01-12 Thread anonymous via Digitalmars-d-learn

On 12.01.2016 16:41, ParticlePeter wrote:

// alias MF = void function( int i );  // not working
// alias void function( int i ) MF;  // not working


These are both fine. The first one is the preferred style.



MF myFunc;
myFunc = MF { myCode };


This line doesn't work. Function literals don't take a type before the 
curly braces. They have their own syntax. See 
http://dlang.org/spec/expression.html (search for "Function Literals").


Since most of the stuff in function literals can be inferred from the 
context, something as simple as this works:

myFunc = (i) { myCode };


Re: How to declare an alias to a function literal type

2016-01-12 Thread anonymous via Digitalmars-d-learn

On 12.01.2016 17:55, ParticlePeter wrote:

When I pass a parameter to otherFunc I use this syntax for an anonymous
function parameter:

otherFunc( void function( ref int p1, float p2, ubyte p3 ) { myCode; } );


You don't. That's not valid code. You can be using this:

otherFunc( function void ( ref int p1, float p2, ubyte p3 ) { myCode; } );

Note the different position of the `function` keyword.


Re: [Dlang] Delegate Syntax Question

2016-01-10 Thread anonymous via Digitalmars-d-learn

On 10.01.2016 15:32, Jack wrote:

//


class Foo()


Those parentheses make this a (zero parameter) class template. I suppose 
you just want a plain class. Drop them then.



{
  void bar()
  {
  writeln("Hello World");
  }
}

class Bar()


ditto


{

void delegate() action;

   void setAction(void delegate() dele)
   {
action = dele;
   }

}

void main()
{
Foo foo = new Foo();
Bar bar = new Bar();
bar.setAction();
bar.action();
}

/

Is this correct? Because I've been having trouble calling the delegate
when passing the method and I read many documentation concerning
function and delegates. I'm just confused. (Disclaimer: My code's
pattern is the same as above but it's not really my exact code)


Aside from the mentioned parentheses (and a missing import), 
everything's correct.


Re: Nothrow front() when not empty()

2016-01-06 Thread anonymous via Digitalmars-d-learn

On 06.01.2016 14:52, Nordlöw wrote:

At

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

it would be nice if

 return !haystack.empty && haystack.front.unaryFun!pred

was made nothrow.

Is this possible somehow?



try return !haystack.empty && pred(haystack.front);
catch (Exception e) assert(false);


You must be 100% sure that the code cannot actually throw an Exception, 
of course.


Alternatively, you could change `.front` to assert instead of throwing 
an Exception, considering it a programmer error when `.empty` is not 
checked before accessing `.front`.


Re: About Immutable struct members and arrays.

2016-01-06 Thread anonymous via Digitalmars-d-learn

On 06.01.2016 23:04, Jack Applegame wrote:

import std.algorithm;

struct Bar {
 const int a;
 int b;
}

void main() {
 Bar[1] arr;
 Bar bar = Bar(1, 2);
 bar[0].b = 4;


Assuming you meant `arr[0].b = 4;`. Just overwriting the mutable part of 
bar[0] is ok, of course.



 move(bar, arr[0]);   // ok


I consider it a bug that this compiles. You're overwriting immutable 
data, which shouldn't be possible (without casting). 
https://issues.dlang.org/show_bug.cgi?id=15315



 arr[1] = bar;// fail, why?


Assuming you meant `arr[0] = bar;`.

The error message isn't too bad here: "Error: cannot modify struct 
arr[0] Bar with immutable members". You're trying to overwrite immutable 
data, that's not allowed.



 move(Bar(1, 2), arr[0]); // fail, why source parameter isn't auto ref?


I'm not sure about the details. Maybe it would make sense for `move` to 
accept rvalues, maybe not. Breaking immutable is certainly not a good 
reason to do it, though.



}


Re: to!double different from cast(double)

2016-01-04 Thread anonymous via Digitalmars-d-learn

On 04.01.2016 09:22, Ali Çehreli wrote:

void main() {
 const l = long.max;

 assert(l != l.to!double);  // passes
 assert(l != cast(double)l);// FAILS
}

Is there a good explanation for this difference? I would expect both
expressions to be compiled the same way. (I am aware that the !=
operator takes two doubles, meaning that the left-hand side is converted
to 'double' before the comparison.)


I suspect this is due to D allowing floating point operations to happen 
with higher precision than requested by the program.


The comparisons may be done with `real` precision, and `l.to!double` is 
cut down to double precision while `cast(double)l` is not.


Re: Call C function - Access violation

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 21:32, TheDGuy wrote:

If i type:
gcc -c -otest.c.o

the 'test.c.o' file is generated but if i type:

dmd main.d test.c.o i get: 'Error: unrecognized file extension o'?


You're probably on Windows then? dmd doesn't recognize the .o extension 
on Windows, use .obj instead.


Re: Call C function - Access violation

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 22:37, TheDGuy wrote:

If i rename "test.o" to "test.obj" i get:

'Error: Module or Dictionary corrupt'


My guess is, that means that dmd can't handle the object file format 
that gcc produces.


Disclaimer: I don't know much about object formats, gcc, and Windows. I 
may be mistaken in what I write here.


I think there are three object file formats that are relevant for us:

* OMF: the format dmd uses by default on 32 bit Windows,
* COFF: the format dmd uses on 64 bit Windows and in 32 bit mode with 
the -m32mscoff switch,
* ELF: the format gcc uses by default (on Linux at least, maybe on 
Windows too).


You should probably try to find out what gcc produces (by reading gcc 
documentation, I supppose).


Then you need to get your D compiler and your C compiler to produce the 
same format.


As mentioned, dmd has some switches that affect the used/expected object 
format: -m32 (OMF) -m64 (COFF) -m32mscoff (COFF).


You can also try to get gcc to produce another format. I don't know how 
to do that.


Or you can use another C compiler that produces a different format than gcc.

I'd expect Digital Mars's (i.e. Walter's) dmc to be compatible with dmd 
and produce OMF files. Looks like there's a free download:

http://www.digitalmars.com/download/freecompiler.html

dmd's COFF mode is supposed to be compatible with Microsoft's Visual 
Studio. So that would be another option.


Re: Call C function - Access violation

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 14:12, anonymous wrote:

You shouldn't get a segfault, though. You should get some compile/link
error. Are you compiling the right files? Can the segfault be from
something other than your program?


Oh, I see what's probably happening:

You compile the D program, but you don't compile and/or don't link the C 
object file. It segfaults then when trying to call the C function.


You need to compile the C file and pass it to dmd or the linker. For 
example:


gcc -c -otest.c.o test.c
dmd test.d test.c.o
./test


Re: Call C function - Access violation

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 14:01, TheDGuy wrote:

Okay, i think this C code should work (checked with cpp.sh):

#import 
char* write(char* text){
 return text;
}
int main(void){
 return 0;
}


Uh, no. 1) In C it's include, not import. 2) Now you have two main 
functions, that can't work.


You shouldn't get a segfault, though. You should get some compile/link 
error. Are you compiling the right files? Can the segfault be from 
something other than your program?


Re: Repeated struct definitions for graph data structures and in/out naming conflict in C library

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 14:30, data pulverizer wrote:

I am trying to access functionality in the glpk C library using
extern(C). It has graph structs in its header file that are specified in
an odd recurring manner that I cannot reproduce in D:


I don't see what's odd about this. What exactly are your struggling with?


typedef struct glp_graph glp_graph;
typedef struct glp_vertex glp_vertex;
typedef struct glp_arc glp_arc;


You can just drop these. http://dlang.org/ctod.html#tagspace


struct glp_graph
{
  ...
   glp_vertex **v; /* glp_vertex *v[1+nv_max];
};


Drop the semicolon after the struct declaration, and move the asterisks 
one place to the left (purely style):


struct glp_graph
{
glp_vertex** v;
}


struct glp_vertex
{
   ...
   glp_arc *in;
   glp_arc *out;
};


As above, and rename in/out to something else, e.g. in_ and out_:

struct glp_vertex
{
glp_arc* in_;
glp_arc* out_;
}


struct glp_arc
{
   glp_vertex *tail;
   glp_vertex *head;
   glp_arc *t_prev;
   glp_arc *t_next;
   glp_arc *h_prev;
   glp_arc *h_next;
   
};


Nothing new here.


you may also spot that the in, and out keywords are used as members in
the struct, which gives an error in D. These structs are required for
functions in the library so need to be included in the D interface file.


Just rename them to something else. In D code that uses the struct, you 
use the new names. C code doesn't need to be changed, as the name 
doesn't matter when compiled.


Re: Call C function - Access violation

2016-01-03 Thread anonymous via Digitalmars-d-learn

On 03.01.2016 13:30, TheDGuy wrote:

I get an access violation with this code:

extern(C) char* write(char* text);

void main(string[] args){
 char[] text = "Hello World".dup; //.dup converts string to char[]
 text ~= '\0'; //append

 char* result = write(text.ptr); //you need .ptr
 const(char)[] s = cstr2dstr(result);
 writeln(s);
 readln(); //keep the window open
}

auto cstr2dstr(inout(char)* cstr)
{
 return cstr ? cstr[0 .. strlen(cstr)] : "";
}

--

#include std.stdio;

char* write(char* text){
 return text;
}



Works for me after adding the needed imports and removing the wrong 
include from the C file. Is this really the actual code you're running? 
Doesn't your C compiler reject that include? gcc does.


Re: Deducing a template argument from an aliased parameter

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

On 31.12.2015 23:37, rcorre wrote:

struct Vector(T, int N) { }
alias Vector2(T) = Vector!(T, 2);

void fun1(T)(Vector!(T, 2) vec) { }
void fun2(T)(Vector2!T vec) { }

unittest {
   fun1(Vector!(float, 2).init);
   fun2(Vector!(float, 2).init);
}

Why can fun1 deduce `T`, but fun2 can't?

Failure:
"template d.fun2 cannot deduce function from argument types
!()(Vector!(float, 2))"?


Vector2 is a little more than just an alias, it's a template for aliases.

Your Vector2 is short for this:

template Vector2(T)
{
alias Vector2 = Vector!(T, 2);
}


You can see that such a template could map different T types to the same 
result type. For example, Vector2!int and Vector2!long could both become 
aliases to Vector!(long, 2). Deducing T from a Vector!(long, 2) argument 
would be ambiguous then. T could be int or long, and there is no way to 
tell what it should be.


That's just how I make sense of this, though. I'm not sure if it's the 
whole picture.


Re: regex - match/matchAll and bmatch - different output

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

On 30.12.2015 12:06, Ivan Kazmenko wrote:

import std.regex, std.stdio;
void main ()
{
 writeln (bmatch   ("abab",  r"(..).*\1"));  // [["abab", "ab"]]
 writeln (match("abab",  r"(..).*\1"));  // [["abab", "ab"]]
 writeln (matchAll ("abab",  r"(..).*\1"));  // [["abab", "ab"]]
 writeln (bmatch   ("xabab", r"(..).*\1"));  // [["abab", "ab"]]
 writeln (match("xabab", r"(..).*\1"));  // []
 writeln (matchAll ("xabab", r"(..).*\1"));  // []
}

As you can see, bmatch (usage discouraged in the docs) gives me the
result I want, but match (also discouraged) and matchAll (way to go) don't.

Am I misusing matchAll, or is this a bug?


The `\1` there is a backreference. Backreferences are not part of 
regular expressions, in the sense that they allow you to describe more 
than regular languages. [1]


As far as I know, bmatch uses a widespread matching mechanism, while 
match/matchAll use a different, less common one. It wouldn't surprise me 
if match/matchAll simply didn't support backreferences.


Backreferences are not documented, as far as I can see, but they're 
working in other patterns. So, yeah, this is possibly a bug.



[1] 
https://en.wikipedia.org/wiki/Regular_expression#Patterns_for_non-regular_languages


Re: DMD -L Flag, maybe a bug?

2015-12-26 Thread anonymous via Digitalmars-d-learn

On 26.12.2015 02:04, Bubbasaur wrote:

On Friday, 25 December 2015 at 23:45:42 UTC, anonymous wrote:
It's almost like the example in the URL you showed:

dmd test.d -LC:/gtkd/src/build/GtkD.lib


Note that in the docs I linked it's `dmd hello.d -L+gtkd.lib` with a 
plus sign. I'm not sure if it's significant, but it's a difference.


Also, and this may be it, the link.exe that's distributed with dmd 
doesn't like forward slashes as path separators. You can try it with 
backslashes instead:


dmd test.d -LC:\gtkd\src\build\GtkD.lib


But if you do a search for problems like: Linking problem or Symbol
Undefined most command lines uses this: "-Lpath/to/whatever" (Without
Space). And another thing... there is other flag commonly used "-I" with
doesn't need space, so most people will assume the same for -L.


-L doesn't take a space, either. Putting a space there isn't even 
optional, it's wrong. The stuff after the space is not passed to the 
linker, it's interpreted by dmd.


Re: Understand typeof trick

2015-12-25 Thread anonymous via Digitalmars-d-learn

On 25.12.2015 13:10, Joakim Brännström wrote:

In http://forum.dlang.org/post/ojawnpggfaxevqpmr...@forum.dlang.org Adam
uses findSkip as an example and especially points out the "D idiom with
is/typeof".

I'm not quite sure I understand it correctly. Please correct me if I
have misunderstood anything regarding the idiom.

findSkip: http://dlang.org/phobos/std_algorithm_searching.html#.findSkip
bool findSkip
   (alias pred = "a == b", R1, R2)
   (ref R1 haystack, R2 needle)
 if (isForwardRange!R1 &&
 isForwardRange!R2 &&
 is([C]
typeof( [B]
   binaryFun!pred(  [A]
  haystack.front, needle.front;

[A]
Nothing special. findSkip's pred is passed on to binaryFun. binaryFun's
constraints thus apply to findSkip's pred.
See http://dlang.org/phobos/std_functional.html#.binaryFun


Yup, and then the resulting function is called with arguments 
`haystack.front, needle.front`. The template instantiation, and the 
function call can fail compilation (more precisely: semantic analysis). 
In that case, A is marked as being "broken".



[B]
Evaluates to the function type "constructed" by binaryFun.


Almost. It evaluates to the type of the expression. The expression is a 
function call, so typeof evaluates to the return type of the generated 
function.


If A has been marked broken, then B does not become a proper type, and 
it's marked "broken" as well.



[C]
The is expression is true if A->B is valid "code".


It's true if the argument, i.e. B, is a proper type. In particular, B 
must not be marked "broken".


If B is "broken", then C is false. Any error messages that would usually 
be printed for the broken A/B are suppressed.



It is used to convert any compiler errors to "false" (thus the
constraint wouldn't be fulfilled).


Yes, but be aware that this only works on semantic errors, not on syntax 
errors.


For example, `is(foo())` and `is(typeof(foo(); bar();))` don't give you 
false, but they error out in the syntax checking phase.


That second one leads us to the longest form of the is-typeof idiom: 
`is(typeof({foo(); bar();}))`. Wrapping the code in a delegate so that 
it's an expression, which can be passed to typeof.



Question:
I guess that binaryFun is used in the implementation of findSkip.


Yeah, the constraint wouldn't make sense otherwise.


The reason for using this type of idiom is to avoid "compilation errors"
to occur in the implementation when pred/R1/R2 is "funky". It "confuses"
the user.
The idiom is thus used to move errors to the call site?
"D idiom: constraint error at call site"?


I think Adam meant just the is(typeof(...)) thing itself, regardless of 
where it appears.


Constraints are used to reject bad instantiations early on, yes. They're 
also used to distinguish different template "overloads".


Re: DMD -L Flag, maybe a bug?

2015-12-25 Thread anonymous via Digitalmars-d-learn

On 25.12.2015 15:40, Bubbasaur wrote:

But at least on Windows, you need to put a space between -L and the
PATH. Which It's weird, since with "-I" flag you don't need any space.


I don't think that's right. Unless something awful is going in Windows 
dmd, that should be processed as two separate entities: "-L" passes 
nothing to the linker, and whatever you try to send the linker is 
interpreted independently by dmd.


You can try removing the "-L" entirely. If it still works, then dmd is 
apparently able to handle things for you, and you don't need to go the 
linker yourself.


What exactly are trying to pass to the linker?


It took me 30 minutes until I find why my program wasn't compiling. (I
found the tip on a forum elsewhere).


Can you give a link to that?


Re: DMD -L Flag, maybe a bug?

2015-12-25 Thread anonymous via Digitalmars-d-learn

On 25.12.2015 19:32, Bubbasaur wrote:

On Friday, 25 December 2015 at 15:06:27 UTC, anonymous wrote:
In fact it works without the "-L". Which makes me wonder if I was using
it wrongly?


I'm convinced that putting a space between "-L" and its argument is 
nonsense. The "-L" part just means "pass the empty string to the 
linker", which doesn't do anything. And the argument is interpreted by 
dmd then, not by the linker.



What exactly are trying to pass to the linker?


A lib: GtkD.


That means a .lib file, right?

dmd knows how to handle .lib files [1], so it's no surprise that things 
work when you pass the .lib file to dmd.


The GtkD docs say to use -L though [2], so I suppose that should work 
too. Maybe show your exact complete command line, if you want to find 
out why it doesn't work for you.



[1] http://dlang.org/dmd-windows.html#switches
[2] 
https://github.com/gtkd-developers/GtkD/wiki/Installing-on-Windows#testing-installation


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

2015-12-21 Thread anonymous via Digitalmars-d-learn

On 21.12.2015 21:20, Steven Schveighoffer wrote:

This seems like an incorrect feature then. Why wouldn't I want S to be
treated like any other const(char)*? Seems like it's explicitly saying
"treat this like a const(char)*"


To my understanding, `alias this` means "is implicitly convertible to 
X", and not "is the same thing as X".


That is, `is(S == const(char)*)` is false, but `is(S : const(char)*)` is 
true. It makes sense to me that isPointer behaves like the `==` variant.


And for sure, the `alias this` doesn't make S interchangeable with a 
pointer. S may have a different size, the pointer may not be at a zero 
offset in S, etc.


For the phobos code in question it comes down to what's less surprising, 
I guess. Having such an `alias this` resolved before stringification, or 
not. I'm not sure.


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

2015-12-21 Thread anonymous via Digitalmars-d-learn

On 21.12.2015 17:02, Shriramana Sharma wrote:

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


A struct/class with an `alias this` to a `const(char)*`:


import std.traits: isPointer;

struct S
{
const(char)* ptr;
alias ptr this;
}

static assert(!isPointer!S && is(S : const(char)*)); /* passes */



Re: Problems with string literals and etc.c.odbc.sql functions

2015-12-19 Thread anonymous via Digitalmars-d-learn

On 19.12.2015 14:20, Marc Schütz wrote:

As this is going to be passed to a C function, it would need to be
zero-terminated. `.dup` doesn't do this, he'd have to use
`std.string.toStringz` instead. However, that function returns a
`immutable(char)*`, which would have to be cast again :-(


Ouch, I totally missed that. Looks like we don't have a nice way to do 
this then?


Re: Problems with string literals and etc.c.odbc.sql functions

2015-12-18 Thread anonymous via Digitalmars-d-learn

On 18.12.2015 23:14, Fer22f wrote:

By the use of this tutorial
(http://www.easysoft.com/developer/languages/c/odbc_tutorial.html), I
thought it would be very straightforward to use etc.c.odbc.sqlext and
etc.c.odbc.sql to create a simple odbc application. But as soon as I
started, I noticed a quirk:

 SQLRETURN ret;
 SQLHDBC dbc;
 ret = SQLDriverConnect(dbc, null, "DNS=*mydns*;", SQL_NTS,
 null, 0, null, SQL_DRIVER_COMPLETE);

This gives me an error: function etc.c.odbc.sqlext.SQLDriverConnect
(void* hdbc, void* hwnd, char* szConnStrIn, short cbConnStrIn, char*
szConnStrOut, short cbConnStrOutMax, short* pcbConnStrOut, ushort
fDriverCompletion) is not callable using argument types (void*,
typeof(null), string, int, typeof(null), int, typeof(null), int)

After some casting, I found out it's all related to the string literal.
I thought it would work straight off the box, after reading the
"Interfacing to C" spec (http://dlang.org/spec/interfaceToC.html).

When I remove the string literal and replace it with null, it compiles.
.ptr and .toStringz both give immutable char* references, and don't
work. A "cast(char *)"DNS=*maydns*;"" works, but it feels a lot like a
hack that will not work in the long run.


If the parameter is de facto const, then the cast is ok. Though, maybe 
it should be marked const then.


If the parameter is really not const, i.e. the function may mutate the 
argument, then the cast is not ok. You can use `.dup.ptr` instead to get 
a proper char* from a string.


Also, remember that D's GC doesn't scan foreign memory. So if the 
function keeps the string around, and that's the only reference, then 
the GC would collect it. The function probably doesn't keep the string 
around, though.


Re: Problems with string literals and etc.c.odbc.sql functions

2015-12-18 Thread anonymous via Digitalmars-d-learn

On 19.12.2015 01:06, Fer22f wrote:

Documentation on casts say:

Casting a pointer type to and from a class type is done as a type paint
(i.e. a reinterpret cast).



That sentence doesn't apply. string is not a class, it's an alias for 
immutable(char)[], i.e. it's an array.



Reinterpretation is rather dangerous if strings are stored differently.

But this test gives me a good hope on this case:

 writeln(*(cast(char*) "Test"));

Casting is what I'm going with. .dup.ptr is less clear in this case.


Correctness beats clarity.

I'd like to advise you not to use casts unless you know for sure that 
they're safe.


Here, you need to know what a string is exactly, what the cast does 
exactly, and what exactly the called function does with the pointer.


Re: D float types operations vs C++ ones

2015-12-17 Thread anonymous via Digitalmars-d-learn

On 17.12.2015 12:50, drug wrote:

I have two implementation of the same algorithm - D and C++ (that is
port of D version). I assume that running these implementations on the
same data should give the same results from both. But with some data the
results differ (5th decimal digit after point). For my purpose it isn't
important and I can ignore this difference. But I'd like to have the
same results totally (I mean bit to bit) to easy maintanence of the
implementations. Question is - can I rely that D and C++ float types
operations should give the same result because D and C are similar or no
and I should use more portable way and compare floats with some epsilon?


D explicitly allows compilers to use greater precision in calculations 
than the involved types have [1]. For example, an expression involving 
`float`s may be evaluated at double or real precision.


That means, you cannot rely on getting the same results even when 
looking only at D. Compiler A may produce higher precision code than 
compiler B; or machine X offers a larger maximum precision than machine 
Y (and the compiler makes use of it).



[1] http://dlang.org/spec/float.html


Re: isBidirectionalRange fails for unknown reasons

2015-12-16 Thread anonymous via Digitalmars-d-learn

On 16.12.2015 21:43, Jack Stouffer wrote:

I'm trying to add a ReferenceBidirectionalRange range type to
std.internal.test.dummyrange so I can test some range code I'm writing,
but I've hit a wall and I'm not sure why. For some reason, the
isBidirectionalRange check fails even though back and popBack are
present. Any help here would be appreciated.


[...]


class ReferenceForwardRange(T) : ReferenceInputRange!T
{
 this(Range)(Range r) if (isInputRange!Range) { super(r); }
 final @property ReferenceForwardRange save()
 {return new ReferenceForwardRange!T( _payload); }
}

class ReferenceBidirectionalRange(T) : ReferenceForwardRange!T
{
 this(Range)(Range r) if (isInputRange!Range) { super(r); }
 final @property ref T back(){ return _payload.back; }
 final void popBack(){ _payload.popBack(); }
}


The `.save` primitive of forward ranges must return the very same type 
that the range has. But your ReferenceBidirectionalRange!T.save returns 
a ReferenceForwardRange!T, because it's inherited. That makes 
isForwardRange!(ReferenceBidirectionalRange!T) fail, and everything that 
depends on it.


You can override `save` in ReferenceBidirectionalRange or try something 
clever like using a template this parameter:


@property auto save(this This)() {return new This( _payload);}



Re: How to check if result of request to DB is empty?

2015-12-12 Thread anonymous via Digitalmars-d-learn

On 12.12.2015 08:44, Suliman wrote:

string query_string = (`SELECT user, password FROM otest.myusers where
user LIKE ` ~ `'%` ~ request["username"].to!string ~ `%';`);


Don't piece queries together without escaping the dynamic parts.
Imagine what happens when the user enters an apostrophe in the
username field.


Do you mean to wrap:
  request["username"].to!string
in quotes?


no


Re: How to check if result of request to DB is empty?

2015-12-11 Thread anonymous via Digitalmars-d-learn

On 11.12.2015 22:05, Suliman wrote:

I am using https://github.com/buggins/ddbc

string query_string = (`SELECT user, password FROM otest.myusers where
user LIKE ` ~ `'%` ~ request["username"].to!string ~ `%';`);


Don't piece queries together without escaping the dynamic parts. Imagine 
what happens when the user enters an apostrophe in the username field.


Also, are you using LIKE when authenticating the user? O_O


How I can check if SQL request returned empty result?


When the result is empty, then rs.next() returns false on the first 
call, I presume.


Re: The @@@BUG@@@ the size of China - std.conv.d - Target parse(Target, Source)(ref Source s, uint radix)

2015-12-07 Thread anonymous via Digitalmars-d-learn

On 07.12.2015 21:56, John Carter wrote:

So whilst attempt to convert from a hex string (without the 0x) to int I
bumped into the @@@BUG@@@ the size of China

https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L2270


Is there a bugzilla issue number tracking this?

Searching for conv and parse  in the issue tracker didn't turn it up

Is this a phobos bug or a compiler bug?

I followed the example in the unit test to get a workaround but I
don't understand why the workaround works!


I'm not sure if there's a bug. `parse` takes the string via `ref`, but 
string literals are not lvalues so they cannot be passed that way. This 
should also make it clear why the workaround works: A string literal is 
not an lvalue, but a variable is.


Maybe whoever added that note thinks that string literals should be 
lvalues. That would make it a compiler bug. I think that would be a 
controversial viewpoint, though.


Or the author thinks that `parse` should work with non-lvalues. That 
would make it a phobos issue. We have std.conv.to for that, though. So 
weakening the requirements on `parse` isn't exactly necessary. Just use 
`to` when you don't care about popping the input.


Re: Comparison operator overloading

2015-12-07 Thread Anonymous via Digitalmars-d-learn
On Monday, 7 December 2015 at 17:18:20 UTC, Dominikus Dittes 
Scherkl wrote:
Hmm. But it works just fine! It overloads also the special 
floatingpoint operators <> !<> !<= and so on.


Those are deprecated: 
http://dlang.org/deprecate.html#Floating%20point%20NCEG%20operators


And how else could I handle a self-defined type that happens to 
have a NaN value (like my save-signed intergers do)?


Something like this:
http://dlang.org/phobos/std_math.html#isNaN

Or maybe this:
http://dlang.org/phobos/std_typecons.html#Nullable

Obviously, you'd want to do what makes sense for your type and 
its semantics. That probably doesn't involve using NCEG operators.


Re: benchmark on binary trees

2015-12-05 Thread anonymous via Digitalmars-d-learn

On 05.12.2015 01:40, Alex wrote:

found and tried out the -vgc option...
Is there a way to deactivate the GC, if it stands in way?


You can call core.memory.GC.disable to disable automatic collections. 
.enable to turn them on again.


http://dlang.org/phobos/core_memory.html#.GC


Yes, I thought in the same direction. That's why I tried to reimplement
the c++ version. The idea was: as I can't compete with the GC of C#, I
could try to compete by applying another approach. I don't try to write
something which compete with c++ either (I would have to take c++, then?
;) ), but something which clearly outperforms the languages with a
virtual machine...


Your C++ inspired version still allocated via the GC, though. If that 
eats performance, then you'd have to mirror more closely what the C++ 
version actually does. It most probably doesn't use a GC.


I presume this is the C++ version you took as inspiration:
http://benchmarksgame.alioth.debian.org/u64q/program.php?test=binarytrees=gpp=6

That uses a boost::object_pool for the nodes. Assuming that that's being 
used for a reason, you could probably get a performance boost by doing 
something similar. I'm not really familiar with 
std.experimental.allocator, maybe there's something like object_pool in 
there. Otherwise, you'd have to implement it yourself.


Generally, I think most of the time you can write a program in D that's 
as fast as one written in C++. But you may have to give up on some 
convenience, and the libraries may not be there to support you.


Re: using parse with string slice

2015-12-05 Thread anonymous via Digitalmars-d-learn

On 05.12.2015 22:59, Quentin Ladeveze wrote:

---
import std.conv;

string s = "1B2A";

int value = parse!int(s[0..2], 16); //template std.conv.parse cannot
deduce function from argument types !(int)(string, int)
---

Does someone have an idea of why it happens ? The version of parse that
is used here is :

---
std.conv.parse(Target, Source)(ref Source s, uint radix) if
(isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target ==
enum))
---

And I can't see which template constraint is not respected when I call
it with a slice.


It's the `ref` part. A slice expression cannot be passed in a ref 
parameter. You can use std.conv.to instead or assign the slice to a 
variable first.


Re: benchmark on binary trees

2015-12-04 Thread anonymous via Digitalmars-d-learn

On 04.12.2015 15:06, Alex wrote:

3. The compilation was done by:
dmd -O -release -boundscheck=off [filename.d]
Is there anything else to improve performance significantly?


You forgot -inline.

By the way, I'm not a fan of using -boundscheck=off like a general 
optimization flag. It undermines @safe, and as the documentation says, 
it should be used with caution.


http://dlang.org/dmd-windows.html#switch-boundscheck


Re: benchmark on binary trees

2015-12-04 Thread anonymous via Digitalmars-d-learn

On 04.12.2015 21:30, Alex wrote:

Yes, I missed this, sorry. The main part of the question was probably
about the class and struct difference. I thought handling with structs
and pointers would be faster then with classes.


When you use a struct directly, without going through a pointer, that 
can be significantly faster than using a class. But structs through 
pointers are pretty much the same as classes, performance-wise.


[...]

Why the parallel version is slower then the sequential?
If you set
int n = 14 in the main function
the parallel version is MUCH slower then the sequential. At my machine
7x slower. Shouldn't it be the other way round?


I don't know what's going on here. You're allocating a lot of 
`TreeNode`s, though. That's probably not very parallelizable. The GC 
could also play a role.


[...]

As ldc doesn't have the experimental part of the includes, compared on
the first version. The result was: program compiled with ldc2, same
params, was 5% slower... nothing crucial, I think...


"The experimental part" is std.experimental.allocator, right? I may be 
wrong here, but I think the default allocator is essentially just `new`. 
So that wouldn't give you any performance boost.


[...]

Yeah... so the answer here for me, is that I can stay with my way of
thinking in c# style. :)


In this case, I think you're fine. Generally, be aware that D doesn't 
shine when you create lots of throw-away objects. The GC can't compete 
with those of C# or Java, so when you translate code from those 
languages too closely, performance may be worse.


Re: benchmark on binary trees

2015-12-04 Thread anonymous via Digitalmars-d-learn

On 04.12.2015 15:06, Alex wrote:

1. I wrote the C++ inspired version after the C# inspired, hoping it
would be faster. This was not the case. Why?

[...]

Why did you expect the C++ inspired version to be faster? Just because 
the original was written in C++?


From a quick skim the two versions seem to be pretty much identical, 
aside from names and struct vs class.


Names don't make a difference of course. It would be easier to compare 
the two versions if you used the same names, though.


The differences between structs on the heap and classes are subtle. It's 
not surprising that they don't have an impact here.


If there are substantial differences between the two versions, please 
point them out.



2. I failed trying to implement some kind of parallelism in the second
version. I tried something like

auto depthind = iota(min_depth, max_depth+1, 2);
foreach(dummy_i, d; taskPool.parallel(depthind))

for the for-loop in the main function, but then, the program never ends.
Do you have a hint what was wrong?


Works for me. Maybe show the exact full program you tried, and tell what 
compiler version you're using.



3. The compilation was done by:
dmd -O -release -boundscheck=off [filename.d]
Is there anything else to improve performance significantly?


The other compilers, ldc and gdc, usually produce faster code than dmd.


4. This is some ambiguous question. I come originally from the C#
corner, so I natively think in terms of the first approach. Can one
general make the statement, that for D one of the approaches above will
be always faster then the other?


Just reiterating what I said re the first question: I don't really see a 
difference. If you think there is, please point it out. Or if you're not 
sure, feel free to ask about specific parts.


Re: DDOC adds emphasis on symbols, so how to use $(LINK a) properly?

2015-12-01 Thread anonymous via Digitalmars-d-learn

On 01.12.2015 16:15, kraybit wrote:

 /**
 *  Also see $(LINK mylib.image.pixel.html)
 */
 module mylib;
 ...


This will generate a link, but the href will be
"mylib.image.pixel.html", which won't work in my browser at least
(Chromium). This can be fixed with:


 $(LINK _mylib.image.pixel.html)


Ok, great. But wait a minute. How do I know that 'image' and 'pixel'
won't be emphasized symbols in the future?


'mylib' is emphasized because it's the module name and you're 
documenting the module declaration there. That is, identifiers are only 
emphasized automatically when they're used in the declaration that is 
being documented. 'image' or 'pixel' would only be emphasized if you 
changed the module name to 'image' or 'pixel'.


Re: DDOC adds emphasis on symbols, so how to use $(LINK a) properly?

2015-12-01 Thread anonymous via Digitalmars-d-learn

On 01.12.2015 16:52, kraybit wrote:

Hm, I see, so it's contextual? Would 'pixel' then be emphasized if I'm
in the documentation of void pixel()?


Yes and yes.


I just get the feeling I need to think before using LINK. I'd like to
not think, too  much.


It's a clever feature for sure. Maybe too clever, or not clever enough.


It doesn't also seem clear when this happens. Will
$(LINK forum.com/pixel/98) work? Or does it need a "_"?


I don't have memorized what's a word boundary for Ddoc, and the 
documentation is sparse. You'd have to try it out, I guess.


Re: having problem with `std.algorithm.each`

2015-11-30 Thread anonymous via Digitalmars-d-learn

On 30.11.2015 11:50, visitor wrote:

though i don"t understand why it fails silently ??


ref2491's original code is valid, but doesn't have the intended meaning. 
`e => {foo(e);}` is the same as `(e) {return () {foo(e);};}`, i.e. a 
(unary) function that returns a (nullary) delegate. Calling it does not 
run foo. In contrast, calling this runs foo: `e => foo(e)`.


Re: DateTime.opBinary

2015-11-29 Thread anonymous via Digitalmars-d-learn

On 30.11.2015 00:25, bachmeier wrote:

I was just reading through the documentation for std.datetime.
DateTime.opBinary looks pretty interesting:

http://dlang.org/phobos/std_datetime.html#.DateTime.opBinary

Does anyone know how to use it? You certainly can't learn anything from
the documentation, because duration is a mystery. If someone knows, I
can submit a PR with that information added.


You can add a Duration to a DateTime, giving you a new DateTime. And you 
can subtract a DateTime from another, giving you the Duration between them.


Example:

import std.datetime, std.stdio;
void main()
{
DateTime oldYear = DateTime(2015, 12, 31, 23, 59, 59);
writeln(oldYear); /* 2015-Dec-31 23:59:59 */
DateTime newYear = oldYear + 1.seconds; /* adding Duration to 
DateTime */

writeln(newYear); /* 2016-Jan-01 00:00:00 */
Duration diff = newYear - oldYear; /* subtracting DateTime from 
DateTime */

writeln(diff); /* 1 sec */
}




Re: Can't understand how to do server response with vibed

2015-11-28 Thread anonymous via Digitalmars-d-learn

On 28.11.2015 19:51, Suliman wrote:

Eghm, sorry. Not req, but res, but again errr:

void action(HTTPServerRequest req, HTTPServerResponse res)
{
 writeln(req.writeJsonBody);
}

Error: no property 'writeJsonBody' for type
'vibe.http.server.HTTPServerRequest'

But this method are present in docs:

http://vibed.org/api/vibe.http.client/HTTPClientRequest


req is not an HTTPClientRequest, it's an HTTPServerRequest.

http://vibed.org/api/vibe.http.server/HTTPServerRequest


Re: Can't understand how to do server response with vibed

2015-11-28 Thread anonymous via Digitalmars-d-learn

On 28.11.2015 19:46, Suliman wrote:

And the second question. Why I am getting next error after attempt to
write to console JSON request:

Error: cannot resolve type for res.writeJsonBody(T)(T data int status =
HTTPStatus.OK, string content_type = "application/json; charset=UF-8",
bool allow_chunked = false)

void action(HTTPServerRequest req, HTTPServerResponse res)
{
 writeln(res.writeJsonBody);
}


That's because writeJsonBody's return type is void.

http://vibed.org/api/vibe.http.server/HTTPServerResponse.writeJsonBody


Re: EnumMemberNames

2015-11-27 Thread anonymous via Digitalmars-d-learn

On 27.11.2015 15:05, drug wrote:

I need to get names of enum members, is it possible? EnumMembers returns
the members itself, i.e.
```
enum Sqrts : real
 {
 one   = 1,
 two   = 1.41421,
 three = 1.73205,
 }

pragma(msg, [EnumMembers!Sqrts]);
```
returns

[1.0L, 1.41421L, 1.73205L]

but I need

[ "Sqrts.one", "Sqrts.two", "Sqrts.three" ] or [ "one", "two", "three" ]


You have a variety of options with subtle differences:

module test;

import std.algorithm: map;
import std.array: array;
import std.conv: to;
import std.meta: staticMap;
import std.range: only;
import std.traits: EnumMembers, fullyQualifiedName;

enum Sqrts : real
{
one   = 1,
two   = 1.41421,
three = 1.73205,
}

pragma(msg, only(EnumMembers!Sqrts).map!(to!string).array);
/* [['o', 'n', 'e'], ['t', 'w', 'o'], ['t', 'h', 'r', 'e', 'e']] */

enum toString(alias thing) = thing.to!string;
pragma(msg, staticMap!(toString, EnumMembers!Sqrts));
/* tuple(['o', 'n', 'e'], ['t', 'w', 'o'], ['t', 'h', 'r', 'e', 
'e']) */


pragma(msg, staticMap!(fullyQualifiedName, EnumMembers!Sqrts));
/* tuple("test.Sqrts.one", "test.Sqrts.two", "test.Sqrts.three") */

enum stringOf(alias thing) = thing.stringof;
pragma(msg, staticMap!(stringOf, EnumMembers!Sqrts));
/* tuple("one", "two", "three") */


std.conv.to is the first address for conversions between types. I'd say 
use that unless you have a reason not to.


If you're doing code generation, or otherwise need the fully qualified 
name, use std.traits.fullyQualifiedName.


I'm not sure if there would ever be a reason to use .stringof over the 
other ones, other than some quick debug printing.


There are probably more ways I didn't think of.


Re: switch with enum

2015-11-25 Thread anonymous via Digitalmars-d-learn

On 25.11.2015 21:06, Meta wrote:

...Which doesn't work because it won't compile without a default case.
Is this a recent change? I don't remember D doing this before.


Use `final switch`. Ordinary `switch`es need an explicit default case. 
`final switch`es have to cover all possibilities individually. Implicit 
default cases are not allowed.


Re: How to use D parallel functions/library

2015-11-24 Thread anonymous via Digitalmars-d-learn

On 24.11.2015 19:49, Bishop120 wrote:

I figured this would be a simple parallel foreach function with an iota
range of sizeX and just making int X declared inside the function so
that I didnt have to worry about shared variable but I cant get around
the alive++ reduction and I dont understand enough about D's
reduction/parallel library.

Any ideas?  Thanks in advance for yalls patience and assistance!


I'm not sure what you're asking. Are you maybe looking for 
core.atomic.atomicOp?


Example:

import core.atomic: atomicOp;
import std.parallelism: parallel;
import std.range: iota;
import std.stdio: writeln;

void main()
{
int x = 0;
shared int y = 0;
foreach(i; parallel(iota(100_000)))
{
++x;
y.atomicOp!"+="(1);
}
writeln(x); /* usually less than 100_000 */
writeln(y); /* 100_000 */
}



Re: RAII trouble

2015-11-20 Thread anonymous via Digitalmars-d-learn

On 20.11.2015 23:56, Spacen Jasset wrote:

The ideal would be to have a struct that can be placed inside a function
scope, or perhaps as a module global variable. Why does Ft_Init_FreeType
have to be read at compile time?


text.d(143,15): Error: static variable FT_Init_FreeType cannot be read
at compile time
text.d(174,43):called from here: initialise()

struct FreeType
{
 @disable this();

 static FreeType initialise()
 {
 return FreeType(0);
 }

 this(int)
 {
 int error = FT_Init_FreeType(); /// ERROR
 enforce(!error);
 }

 alias library this;

 ~this()
 {
 FT_Done_FreeType(library);
 }
 FT_Library library;
}

FreeType   freeType = FreeType.initialise();



FT_Init_FreeType must be read at compile time, because freeType is a 
module level variable, and initializers for module variables must be 
static values. The initializer is run through CTFE (Compile Time 
Function Evaluation).


Put the initialization/assignment in a function and it should work. That 
function can be a static constructor or the main function:


FreeType freeType = void; /* 'void' prevents default initialization */
static this() {freeType = FreeType.initialise();} /* should work */
void main() {freeType = FreeType.initialise();} /* too */



Re: char[] == null

2015-11-18 Thread anonymous via Digitalmars-d-learn

On 19.11.2015 06:18, Chris Wright wrote:

Just for fun, is an array ever not equal to itself?


Yes, when it contains an element that's not equal to itself, e.g. NaN.


Re: char[] == null

2015-11-18 Thread anonymous via Digitalmars-d-learn

On 18.11.2015 22:02, rsw0x wrote:

slices aren't arrays
http://dlang.org/d-array-article.html


The language reference/specification [1] uses the term "dynamic array" 
for T[] types. Let's not enforce a slang that's different from that.



[1] http://dlang.org/arrays.html


Re: Filtering a tuple of containers with indices

2015-11-17 Thread anonymous via Digitalmars-d-learn

On 17.11.2015 15:32, maik klein wrote:

template tupIndexToRange(alias Tup, Indices...){

[snip]

I don't quite understand how that code is supposed to work. Maybe 
there's just some detail missing, but it could also be that your 
approach can't work.



This is roughly what I want to achieve

   alias Integrals = AliasSeq!(Array!int, Array!float, Array!double);
   Integrals integrals;
   integrals[0].insertBack(1);
   integrals[1].insertBack(2);
   integrals[2].insertBack(3);

   auto range = zip(tuple(integrals[0][],integrals[1][]).expand);
   writeln(range);
   foreach(e;range){
 writeln("element: ",e);
   }
But instead of "auto range =
zip(tuple(integrals[0][],integrals[1][]).expand);" I want it to be
generic "auto range = zip(tupIndexToRange!(integrals, AliasSeq!(0,
1)).expand);"


I think the problem can be split up into two independent tasks:

1) Select fields of a tuple by indices (to drop `integrals[3]`).
2) A "map" function for tuples (to apply `[]` to the selected arrays).

Here are two quick implementations of those applied to your problem:


template selectFromTuple(indices ...)
{
auto selectFromTuple(Types...)(Types values)
{
import std.typecons: tuple, Tuple;
static if (indices.length == 0) return Tuple!()();
else
{
enum headIndex = indices[0];
auto tail = .selectFromTuple!(indices[1 .. $])(values);
return tuple(values[headIndex], tail.expand);
}
}
}

auto mapTuple(alias op, Types ...)(Types values)
{
import std.meta: staticMap;
import std.typecons: tuple;

alias ResultType(T) = typeof(op(T.init));
alias ResultTypes = staticMap!(ResultType, Types);

ResultTypes results;
foreach (i, v; values) results[i] = op(v);
return tuple(results);
}

void main()
{
  import std.container.array;
  import std.meta: AliasSeq;
  import std.range: zip;
  import std.stdio: writeln;

  alias Integrals = AliasSeq!(Array!int, Array!float, Array!double);
  Integrals integrals;
  integrals[0].insertBack(1);
  integrals[1].insertBack(2);
  integrals[2].insertBack(3);

  auto range = integrals
.selectFromTuple!(0, 1).expand
.mapTuple!(a => a[]).expand
.zip;

  writeln(range);
  foreach(e;range){
writeln("element: ",e);
  }
}


That looks a lot like range based programming, which makes me think that 
there could be a way to use actual range algorithms from std.algorithm 
for this. But I don't see how.


Re: Filtering a tuple of containers with indices

2015-11-17 Thread anonymous via Digitalmars-d-learn

On 17.11.2015 20:46, maik klein wrote:

.selectFromTuple!(0, 1).expand

Does this result in a copy? I avoided doing it like this because I was
worried that I would copy every array. But I also don't fully understand
when D will copy.


Yes and no. It copies the Array structs, but it does not copy the 
elements of the arrays. If I remember correctly, std.container.Array 
uses reference counting, and copying them should be cheap.


By the way, do you have a good reason to go with Array!int rather than 
int[]? They're similar, but the builtin int[] may be easier to handle.



Also doing

   foreach(e;range){
 e[0] = 10;
 e[1] = 10.0f;
 writeln("element: ",e);
   }
   foreach(e;range){
 writeln("element: ",e);
   }

doesn't mutate the range at all.


You need to mark the `e` as `ref`: `foreach(ref e; range)`. Otherwise, 
it's a copy of the element, and any changes to it are forgotten at the 
end of the iteration.


But even with `ref` it doesn't work. Seems to be a bug in or a 
limitation of `zip`. Works with `lockstep`:


  auto ranges = integrals
.selectFromTuple!(0, 1).expand
.mapTuple!(a => a[]).expand;
  auto range = ranges.zip;

  import std.range: lockstep;
  foreach(ref e0, ref e1; lockstep(ranges)){
e0 = 10;
e1 = 10.0f;
  }
  foreach(e;range){
writeln("element: ",e);
  }



Re: std.conv.to!string(array), strange compile error

2015-11-14 Thread anonymous via Digitalmars-d-learn

On 14.11.2015 15:17, Relja wrote:

- std.conv.to!string() works on a static array, when called directly on
the array object, but gives the compile error when called on the
returning object from a function.

[...]

void main() {
 getFloat3().to!string; // does not compile
 (new float[3]).to!string; // compiles
}


`new float[3]` is not a static array. Its type is not `float[3]`, it's 
`float[]`.


Re: std.conv.to!string(array), strange compile error

2015-11-14 Thread anonymous via Digitalmars-d-learn

On 14.11.2015 15:40, Relja wrote:

float[3] array;
array.to!string; // compiles


Alright, full test case:


import std.conv;

float[3] getFloat3() {
return [1, 2, 3];
}

void main() {
getFloat3().to!string; // does not compile
float[3] a;
a.to!string; // compiles
}


Yeah, that's odd.

Looking at std.conv, `to` is this [1]:


template to(T)
{
T to(A...)(A args)
if (!isRawStaticArray!A)
{
return toImpl!T(args);
}

// Fix issue 6175
T to(S)(ref S arg)
if (isRawStaticArray!S)
{
return toImpl!T(arg);
}
}


So static arrays are taken by reference. That explains why return values 
from functions are rejected: they're rvalues and can't be passed by 
reference.


Apparently, that oddity is a fix for issue 6175 [2] which seems to be 
about `to` returning a slice of a local variable (which is bad). I don't 
know the details of the issue or the fix, but I've got a feeling that 
there must be a better fix.


Taking the data by reference, but otherwise doing the same as before 
would mean that `to` simply slices a static array when asked to make a 
dynamic array of it, rather than copying the data. And indeed, that 
seems to be the case:



float[] f()
{
import std.conv;
float[3] a = [1, 2, 3];
return a.to!(float[]);
}
void main()
{
auto a = f();
import std.stdio;
writeln(a); /* prints garbage */
}


I don't know if that's considered acceptable. I'm not a fan.

[1] 
https://github.com/D-Programming-Language/phobos/blob/48d57e36e74379291a52087fcd1aa0dc19ff9a70/std/conv.d#L293-L307

[2] https://issues.dlang.org/show_bug.cgi?id=6175


Re: Am I using std.encoding correctly?

2015-11-14 Thread anonymous via Digitalmars-d-learn

On 14.11.2015 15:55, Charles wrote:

I know there's safeDecode, but I'm also fairly confident that all
strings can decode safely, already, and if it isn't I'd want an
exception thrown from it.


Documentation [1] says "The input to this function MUST be validly 
encoded." It says nothing about an Exception being thrown when the input 
is invalid. I'd interpret that "MUST" as "there is no defined behavior 
for bad input".


So if there's a chance that the input is invalid, don't use plain `decode`.


Is this correct usage? I guess I was a little surprised there was no
decodeString that basically did this.


I can't find a simpler way to decode a whole string either. Would be a 
useful addition. Make it a range. Or if we're both just missing it, then 
it should probably be documented more prominently.



[1] http://dlang.org/phobos/std_encoding.html#.EncodingScheme.decode


  1   2   3   4   5   6   >