extended characterset output

2022-04-07 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: 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.


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 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: 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 = &gallery[0];


Re: Ternary if and ~ does not work quite well

2015-10-11 Thread anonymous via Digitalmars-d-learn
On Monday 12 October 2015 07:23, Rikki Cattermole wrote:

> On 12/10/15 6:19 PM, Andre wrote:
[...]
>>  // assert("foo "~ true ? "bar" : "baz" == "foo bar"); does not 
compile
[...]
> I read it as:
> 
> assert("foo "~ (true ? ("bar") : ("baz" == "foo bar")));
> 
> Oh hey look:
> /d434/f138.d(6): Error: incompatible types for (("bar") : ("baz" == "foo 
> bar")): 'string' and 'bool'
> 
> Compiler agrees!

It's `assert(("foo "~ true) ? ("bar") : ("baz" == "foo bar"));` though.


Re: Class, constructor and inherance.

2015-10-11 Thread anonymous via Digitalmars-d-learn
On Monday 12 October 2015 07:28, Ali Çehreli wrote:

> For example, you cannot get current time at run time.

I think you mean compile time here.


Re: Ternary if and ~ does not work quite well

2015-10-12 Thread anonymous via Digitalmars-d-learn
On Monday 12 October 2015 17:39, TheFlyingFiddle wrote:

> "foo" ~ true
> 
> How does this compile? All i can see is a user trying to append a 
> boolean to a string which is obvously a type error. Or are they 
> converted to ints and then ~ would be a complement operator? In 
> that case.. horror.

char and bool are considered integral types. In `"foo " ~ true`, true is 
converted to a char with a value of 1, i.e. some control character.

I'm not a fan either.


Re: DMD Compiler 'switches'

2015-10-12 Thread anonymous via Digitalmars-d-learn
On Monday 12 October 2015 17:38, ric maicle wrote:

> I'm wondering if this small irregularity should be made consistent or 
> maybe I misunderstood something.

As far as I know, the difference just happened, and there is point to it. 
The style without "=" is older and wasn't followed when new switches were 
added.

Consistency between different switches has to be weighed against stability 
here. So far stability has won, I guess.

FWIW, dmd seems to be in good company as gcc is in a similar situation. For 
example, `gcc -std=c11 -ofoo foo.c` is a proper gcc command line, generating 
the file "foo".


Re: DMD Compiler 'switches'

2015-10-12 Thread anonymous via Digitalmars-d-learn
On Monday 12 October 2015 19:46, anonymous wrote:

> and there is point to it

Ugh, should have been: and there is *no* point to it.


Re: Regarding std.array.Appender

2015-10-13 Thread anonymous via Digitalmars-d-learn
On Tuesday 13 October 2015 15:42, Suliman wrote:

> map!(a=> a~=" +") work fine, but how to add before 
> at same time?

Use ~ instead of ~=, like so: map!(a => "+" ~ a ~ "+")


Re: Regarding std.array.Appender

2015-10-13 Thread anonymous via Digitalmars-d-learn
On Tuesday 13 October 2015 15:47, Suliman wrote:

> something like: auto content = file.byLine.map!("start " ~ a=>a ~ 
> " end");

That's not how it works at all. Maybe stick to the examples of whatever 
resource you're learning from, for now.


Re: Struct toString works but not std.conv.to!string

2015-10-13 Thread anonymous via Digitalmars-d-learn

On Tuesday, 13 October 2015 at 22:21:43 UTC, Ali Çehreli wrote:

Reduced with a workaround:

struct UTCOffset
{
import std.conv : to;// Move to module scope to compile


This introduces UTCOffset.to as an alias to std.conv.to.


string toString() const
{
return "hello";
}
}

void main() {
import std.conv : to;


This ends up being ignored, because UTCOffset has a member called 
`to`.



UTCOffset().to!string;


This does not do call std.conv.to through UFCS. Instead, it calls 
UTCOffset's static alias of std.conv.to without an argument.


That is: `UTCOffset().to!string;` = `UTCOffset.to!string;` = 
`std.conv.to!string;`



}




Re: Builtin array and AA efficiency questions

2015-10-15 Thread anonymous via Digitalmars-d-learn
On Thursday, October 15, 2015 11:48 PM, Random D user wrote:

> Should array have clear() as well?
> Basically wrap array.length = 0; array.assumeSafeAppend();
> At least it would then be symmetric (and more intuitive) with 
> built-in containers.

No. "clear" is too harmless a name for it to involve an unsafe operation 
like assumeSafeAppend. With containers there is always one container that 
owns the data. There is no such notion with dynamic arrays.


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

2015-10-16 Thread anonymous via Digitalmars-d-learn
On Friday, October 16, 2015 12:35 PM, Shriramana Sharma wrote:

> Why can't a function that takes an immutable argument be called with a
> mutable input at the call site?
> 
> IOW, why isn't mutable implicitly convertible to immutable?

immutable says that the data won't ever change. If references to mutable 
data would be implicitly convertible to immutable, then you could break the 
immutable guarantee by mutating through the mutable reference which would 
also be visible through the immutable reference.

Keep in mind that functions/methods may store references and reuse them on 
subsequent calls. If the parameter is immutable, then the function can 
assume that the data doesn't change in between calls. If you could pass 
mutable data, then you could change it between calls, and the function's 
immutability expectation would fail.

Also, multiple threads may work concurrently on the same data. But if you 
could have an immutable reference in one thread and a mutable one in 
another, then "immutable" data could change while the function runs.

An immutable parameter is as much a demand by the function from the caller 
as it is a guarantee to the caller. If you don't need the demand part, and 
only want to guarantee that the function does not alter the argument 
(through that reference), const does that.

> I just finished writing a string processing module which calls multiple
> subroutines, and all of them carrying arguments with type `string` viz.
> `immutable(char)[]` IIUC, and I tried to pass it something which came from
> File.byLine(), then got the error:
> 
> function textattr.applyTextAttr (string text) is not callable using
> argument types (char[])
> 
> I understand that const can refer to either mutable or immutable, so does
> this mean I should replace all occurrences of `string` in arguments and
> return values of functions by `const(char)[]`?

If the functions don't actually require immutable data, then yes, use const 
instead.


Re: Idiomatic adjacent_difference

2015-10-16 Thread anonymous via Digitalmars-d-learn
On Friday, October 16, 2015 02:03 PM, Per Nordlöw wrote:

> zip(r, r.dropOne).map!((t) => t[1]-t[0]);

You should r.save one or both of those. The dropOne may affect both 
instances if you don't .save.

By the way, what's the point of `dropOne` over `drop(1)`? It's not shorter. 
Does it do anything subtly different?


Re: what is wrong with this code??

2015-10-17 Thread anonymous via Digitalmars-d-learn
On Saturday, October 17, 2015 04:17 PM, steven kladitis wrote:

> // it thows a range exception

On which line?


Re: what is wrong with this code??

2015-10-17 Thread anonymous via Digitalmars-d-learn
On Saturday, October 17, 2015 04:50 PM, steven kladitis wrote:

> core.exception.RangeError@sokuban.d(84): Range violation

Line 84 being this:

sDataBuild ~= sMap[ch];


Where sMap is:

/*static*/ immutable sMap =
[' ':' ', '.':'.', '@':' ', '#':'#', '$':' '];


Apparently, ch is some char that's not a key in sMap. Try printing out ch to 
see what it is exactly. Then, assuming it's really not a key in sMap, figure 
out if sMap should have that key, or if ch should not end up with that 
value.


Re: Compiling a .d file both as library and executable

2015-10-17 Thread anonymous via Digitalmars-d-learn
On Saturday, October 17, 2015 05:36 PM, Shriramana Sharma wrote:

> In Python there is:
> 
> if __name__ == "__main__":
> 
> to allow the same source file to be treated as both an importable library
> and as an executable script. In D is there any such mechanism to make a
> main() compiled selectively, i.e. by some compile-time flag or such?
> 

http://stackoverflow.com/questions/18537761/hyrbid-modul-and-program-behaviour-for-a-d-source-file


Re: Enough introspection to report variable name of calling argument

2015-10-19 Thread anonymous via Digitalmars-d-learn
On Monday, October 19, 2015 04:14 PM, Handyman wrote:

> Is the following possible in D?  To call a (unary) function f
> with variable a, and let f print:
> 
>> Called with argument named 'a'.
> 
> I am of course asking for a generic solution, independent of the
> actual variable name (in this case, 'a').  I am aware that I am
> likely asking the impossible because of how the function call
> mechanism is implemented in most programming languages, hence in
> D.  Still, it might be possible given D's stong introspection
> capabilities / traits / pragma's / whathaveyou's.

I think the exact thing you're asking for is not possible.

With slightly different syntax you can do this:

module test;
void f(alias v)()
{
import std.stdio: writeln;
import std.traits: fullyQualifiedName;
writeln(v.stringof, " ", fullyQualifiedName!v);
}

void main()
{
int a;
f!a(); /* prints "a test.main.a" */
}



Re: Check Instance of Template for Parameter Type/Value

2015-10-19 Thread anonymous via Digitalmars-d-learn
On Monday, October 19, 2015 04:51 PM, Stewart Moth wrote:

> struct Vector(type, int dimension_){ ... }
> 
> Where type is going to be an int/float/etc and dimension_ is
> 2/3/4.
> 
> I could write a bunch of functions for each case, but I'd rather
> not... I'd like to use something like the following:
> 
> void foo(T)(Array!T array){
>  if(isInstanceOf!(Vector, T)){
>  //get type of T or check it
>  //test if dimension_ is 2 or 3 or 4
>  ...
>  } else {
>  //Non-vector stuff
>  ...
>  }
> }
> 
> But to do that I need to check that parameters of T as if it were
> an instantiated instance of Vector and I'm not sure how to
> accomplish that... Can anyone help me out with what I need to do?

You can use std.traits.TemplateArgsOf:

static if(isInstanceOf!(Vector, T)){ /* note: must be a static if */
enum dimensions = TemplateArgsOf!T[1];
static if(dimensions == 2) {...}
}



Re: Overloading an imported function

2015-10-21 Thread anonymous via Digitalmars-d-learn
On Wednesday, October 21, 2015 02:05 PM, Shriramana Sharma wrote:

> When I've imported std.math which contains round(real), why is the
> compiler complaining about not being able to call the overload function
> defined in *this* module?

The functions don't form an overload set. You need to bring them together 
explicitly using `alias`:


import std.math;
alias round = std.math.round;
real round(real val, int prec) {...}


This is so to avoid function hijacking. See .

> I don't see anything in http://dlang.org/module.html that says I cannot
> define an overload of an imported function. Did I miss something?

That page doesn't seem to mention overloads at all. 
 covers overload sets from 
different imports, but it doesn't mention this specific case where there is 
a local overload set, too.


Re: can't zip a char[5], string[5], real[5]

2015-10-21 Thread anonymous via Digitalmars-d-learn
On Wednesday, 21 October 2015 at 14:06:54 UTC, Shriramana Sharma 
wrote:

import std.stdio, std.range;
void mywrite(char [5] chars, real[5] vals)
{
static string [5] fmts = ["%9.4f, ", "%9.4f; ", "%3d, ", 
"%3d, ",

"%3d\n"];
foreach (e; zip(chars, fmts, vals)) write(e[0], " = ",
e[1].format(e[2]));
}

Compiling gives:

[...]
I would have thought there would be no problem in creating a 
zip of three arrays of equal length. What's the problem here?


Static arrays are not ranges. You can't popFront them. Try 
slicing them: chars[], fmts[], vals[]


Re: Implicit conversion rules

2015-10-21 Thread anonymous via Digitalmars-d-learn
On Wednesday, October 21, 2015 07:53 PM, Sigg wrote:

>  void func() {
>  int a = -10;
>  ulong b = 0;
>  ulong c = a + b;
>  writefln("%s", c);
>  }
> 
>  out: 18446744073709551574
> 
> But shouldn't declaring c as auto force compiler to go extra step
> and "properly" deduce result of the "a + b" expression, since its
> already as far as I understand doing magic in the background?
> Basically try to cast rvalues to narrowest type without losing
> precision before evaluating expression.

The problem is of course that int and ulong have no common super type, at 
least not in the primitive integer types. int supports negative values, 
ulong supports values greater than long.max.

As far as I understand, you'd like the compiler to see the values of `a` and 
`b` (-10, 0), figure out that the result is negative, and then make `c` 
signed based on that. That's not how D rolls. The same code must compile 
when the values in `a` and `b` come from run time input. So the type of the 
addition cannot depend on the values of the operands, only on their types.

Or maybe you'd expect an `auto` variable to be able to hold both negative 
and very large values? But `auto` is not a special type, it's just a 
shorthand for typeof(right-hand side). That means, `auto` variables still 
get one specific static type, like int or ulong.

std.bigint and core.checkedint may be of interest to you, if you prefer 
safer operations over faster ones.

http://dlang.org/phobos/std_bigint.html
http://dlang.org/phobos/core_checkedint.html



Re: Overloading an imported function

2015-10-21 Thread anonymous via Digitalmars-d-learn
On Wednesday, October 21, 2015 08:28 PM, Shriramana Sharma wrote:

> Kagamin wrote:
> 
>> http://dlang.org/hijack.html
> 
> Thanks people, but even as per the rules:
> 
> 1. Perform overload resolution independently on each overload set
> 2. If there is no match in any overload set, then error
> 3. If there is a match in exactly one overload set, then go with that
> 4. If there is a match in more than one overload set, then error
> 
> Here there is only one round(real, int) i.e. in the current module and
> only one round(real) i.e. in the imported module, so as per rule 3, there
> should be a clear resolution.
> 
> So why the conflict then?

Huh. I can't find any specification on this, but apparently the local 
overload set shadows any imported overload sets completely.

I don't know if there's a good reason for this. All I can think of is I 
don't want some local `write` function to conflict with std.stdio.write. But 
the local overload set wouldn't need to shadow the others completely for 
that. It would be enough if it took precedence on conflict.


Re: Converting Unicode Escape Sequences to UTF-8

2015-10-22 Thread anonymous via Digitalmars-d-learn
On Thursday, October 22, 2015 08:10 PM, Nordlöw wrote:

> How do I convert a `string` containing Unicode escape sequences
> such as "\u" into UTF-8?

Ali explained that "\u" is already UTF-8.

But if you actually want to interpret such escape sequences from user input 
or some such, then find all occurrences, and for each of them do:

* Drop the backslash and the 'u'.
* Parse  as a hexadecimal integer, and cast to dchar.
* Use std.utf.encode to convert to UTF-8. std.conv.to can probably do it 
too, and possibly simpler, but would allocate.

Also be aware of the longer variant with a capital U: \U (8 Xs)


Re: Converting Unicode Escape Sequences to UTF-8

2015-10-22 Thread anonymous via Digitalmars-d-learn

On 22.10.2015 21:13, Nordlöw wrote:

Hmm, why isn't this already in Phobos?


I think parsing only Unicode escape sequences is not a common task. You 
usually need to parse some larger language of which escape sequences are 
only a part. For example, parsing JSON or XML are common tasks, and we 
have modules for them.


When we don't have a module for the language in question, then it's 
still likely that you need to parse more than just Unicode escape 
sequences. Some parseUnicodeEscapeSequence function would then probably 
not buy you much on the convenience side but cost you some on the 
performance side.


Also, since escape sequences are defined as part of larger languages, 
they are not well-defined by themselves. We could have a function that 
parses D style sequences, but strictly that would only be good for 
parsing D code.


Re: Overloading an imported function

2015-10-22 Thread anonymous via Digitalmars-d-learn

On 22.10.2015 06:14, Shriramana Sharma wrote:

anonymous wrote:


Huh. I can't find any specification on this, but apparently the local
overload set shadows any imported overload sets completely.


Should I file a bug on this then?


I'm not sure. Maybe make a thread on the main group first. It's not 
clear to me if the compiler is wrong, or if the spec needs to be made 
more precise. Or maybe I just failed to find the relevant part of the spec.


Re: `clear`ing a dynamic array

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

On 24.10.2015 15:18, Shriramana Sharma wrote:

   int a[] = [1,2,3,4,5];


Aside: `int[] a;` is the preferred style for array declarations.


How to make it so that after clearing `a`, `b` will also point to the same
empty array? IOW the desired output is:

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

... and any further items added to `a` should also reflect in `b`.



You can't do that with built-in arrays. The length of a dynamic array is 
a value member of the array structure. So to update `b`'s length you 
need access to the actual `b`.




Re: `clear`ing a dynamic array

2015-10-25 Thread anonymous via Digitalmars-d-learn
On Sunday, 25 October 2015 at 11:45:53 UTC, Shriramana Sharma 
wrote:
http://dlang.org/arrays.html#resize says: """Also, you may wish 
to utilize the phobos reserve function to pre-allocate array 
data to use with the append operator."""


I presume this means 
http://dlang.org/phobos/std_array.html#.Appender.reserve but 
how `append` is considered an operator is beyond me.


That sentence doesn't refer to std.array.Appender. `reserve` 
means . The append 
operator is `~=`.




Re: Merging two named Tuples

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

On 29.10.2015 19:59, Edwin van Leeuwen wrote:

On Saturday, 24 October 2015 at 11:04:14 UTC, Edwin van Leeuwen wrote:

I am trying to write a function to merge two named structs, but am
completely stuck on how to do that and was wondering if anyone good
provide any help. I know I can access the different names with
tup.fieldNames, but basically can't work out how to use that to build
the new return type. Below is an outline of what I am trying to do
(with unittest). Any pointers would be greatly appreciated.


I tried the following, but get a compile error:
source/ggplotd/aes.d(633): Error: variable tup cannot be read at compile
time
source/ggplotd/aes.d(633): Error: argument to mixin must be a string,
not (__error)
source/ggplotd/aes.d(646): Error: template instance
ggplotd.aes.merge!(Tuple!(string[], "x", string[], "y", string[],
"label"), Tuple!(double[], "x", double[], "y")) error instantiating

import std.typecons : Tuple;
template merge(T, U)
{
 auto merge( T base, U other )
 {
 string typing = "Tuple!(";
 string variables = "(";
 foreach( i, t; other.fieldNames )
 {
 typing ~= other.Types[i].stringof ~ ",\"" ~ t ~ "\",";
 variables ~= "other." ~ t ~ ",";
 }

 foreach( i, t; base.fieldNames )
 {
 bool contains = false;
 foreach( _, t2; other.fieldNames )
 {
 if (t==t2)
 contains = true;
 }
 if (!contains)
 {
 typing ~= base.Types[i].stringof ~ ",\"" ~ t ~ "\",";
 variables ~= "base." ~ t ~ ",";
 }
 }
 string tup = typing[0..$-1] ~ ")" ~ variables[0..$-1] ~ ");";
 // Do some clever CTFE
 return mixin(tup);
 }
}

///
unittest
{
 auto xs = ["a","b"];
 auto ys = ["c","d"];
 auto labels = ["e","f"];
 auto aes = Tuple!(string[], "x", string[], "y", string[], "label")(
 xs, ys, labels );

 auto nlAes = merge( aes, Tuple!(double[], "x",
 double[], "y" )(
 [0,1], [3,4] ) );

 assertEqual( nlAes.x[0], 0 );
 assertEqual( nlAes.label.front, "e" );
}

I guess fieldNames does not exist at compile time? Can I get the
fieldNames etc at compile time?

Cheers, Edwin


`tup` is an ordinary (run time, dynamic) string to the type system. You 
can't mixin those. You can only mixin static values (enum, static 
immutable, CTFE results).


The code you're generating doesn't depend on `base` and `other`. All it 
needs are `T` and `U`. So, you can generate the code from the types and 
mix it into a function that takes `T base, U other`:



template merge(T, U)
{
auto generateCode()
{
string typing = "Tuple!(";
string variables = "(";
foreach( i, t; U.fieldNames )
{
typing ~= U.Types[i].stringof ~ ",\"" ~ t ~ "\",";
variables ~= "other." ~ t ~ ",";
}

foreach( i, t; T.fieldNames )
{
bool contains = false;
foreach( _, t2; U.fieldNames )
{
if (t==t2)
contains = true;
}
if (!contains)
{
typing ~= T.Types[i].stringof ~ ",\"" ~ t ~ "\",";
variables ~= "base." ~ t ~ ",";
}
}
return "return " ~ typing[0..$-1] ~ ")" ~ variables[0..$-1] ~ ");";
}

auto merge(T base, U other)
{
mixin(generateCode());
}
}



Re: Static constructors in structs.

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

On 30.10.2015 21:23, TheFlyingFiddle wrote:

Is this intended to work?

struct A
{
__gshared static this()
{
   //Add some reflection info to some global stuff.
   addReflectionInfo!(typeof(this));
}
}

I just noticed this works in 2.069, is this intended?


static constructors are supposed to work, yes.

The description is on the class page: 
http://dlang.org/class.html#static-constructor


__gshared doesn't do anything there, though. Use `shared static this` 
instead, if you want the constructor to run only once per process, and 
not once per thread.


Re: Capturing __FILE__ and __LINE in a variadic templated function

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

On 01.11.2015 23:49, Adam D. Ruppe wrote:

Yeah, just make the other args normal runtime instead of template:


Or make it two nested templates:

template show(T ...)
{
void show(string file = __FILE__, uint line = __LINE__,
string fun = __FUNCTION__)()
{
...
}
}


Re: parallel

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

On 05.11.2015 21:30, Handyman wrote:

Seems that 4 cores go all out on first 4 dishes, then 1 core deals with
the last dish.  With 4 cores I expect diner is ready after 5/4 = 1.25
secs though.  What did I do wrong?


You describe the situation correctly. The unit of work is a dish. That 
is, the work for a single dish is not split between cores. So one of 
your four cores has to make two dishes. That takes two seconds.


Re: parallel

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

On 05.11.2015 21:43, Handyman wrote:

foreach (i; 0..50)
Thread.sleep(20.msecs);

But then my program still says: '2 secs'.   Please enlighten me.


Let's look at the line that does the `parallel` call:

foreach (dish; parallel(dishes, 1)) dish.prepare();

This means that `dishes` is processed in parallel. Multiple threads are 
started to execute `prepare()` on multiple elements of `dishes` at the 
same time.


Each of those `dish.prepare()` calls is done on only one thread, though. 
There is not attempt to split the `prepare` action up and run parts of 
it in parallel.


Re: parallel

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

On 05.11.2015 21:52, Handyman wrote:

On Thursday, 5 November 2015 at 20:45:25 UTC, Ali Çehreli wrote:

That's still 1 second per task. The function prepare() cannot be
executed by more than one core.


Thanks.  OK.  So 'prepare' is atomic?  Then let's turn it around: how
can I make the cores prepare a meal of 5 dishes in 1.25 secs?   Should I
rewrite, or split, 'prepare'?




You'd have to split `prepare` further into parallelizable parts. In a 
real world scenario that may or may not be possible.


When the goal is just sleeping we can do it, of course. Just do another 
`parallel` loop in `prepare`:


import std.range: iota;
foreach (i; parallel(iota(50))) Thread.sleep(20.msecs);

This won't get you down to exactly 1.25 seconds, because the 
start/finish print outs still take some time, and because of 
parallelization overhead.


Re: struct constructor co nfusion

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

On 06.11.2015 20:05, Spacen Jasset wrote:

Also, I had to add a dummy private constructor to make my structs
'createable', or is there another way?

e.g.

struct Texture
{
 @disable this();
 static Texture create()
 {
 return Texture(0);
 }

...

private:
 this(int)
 {
 glGenTextures(1, &textureId_);
 enforce(0 != textureId_);
 }

 GLuint textureId_;
}


You can use Texture.init to initialize a variable:

struct Texture
{
@disable this();
static Texture create()
{
Texture t = Texture.init;
glGenTextures(1, &t.textureId_);
enforce(0 != t.textureId_);
return t;
}
private:
GLuint textureId_;
}




Re: opCmp with structs

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

On 07.11.2015 15:36, Mike Parker wrote:

It's actually possible to use move one instance
into another, though:

void main() {
 import std.algorithm : move;
 ku k1 = ku(1);
 ku k2 = ku(2);
 k2.move(k1);
 assert(k1.id == 2);
}


Wat. It even compiles with @safe. That's not good.


Re: Error not callable with argument types but types matches

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

On 08.11.2015 08:17, Sliya wrote:

I am on Mac OS, but I still don't get it. If the import was not
case-sensitive, I would not have any error since the good file would
have been loaded... Here I have no error saying file not found yet the
file is not loaded. I'd love to know what really happens.


The file system is case insensitive. That means when dmd opens noise.d 
or Noise.d it gets the same contents both times. So both `import noise;` 
and `import Noise;` succeed.


But the module name is case sensitive. `import noise;` results in a 
module `noise`, while `import Noise;` results in a module `Noise`. And 
they're not the same. They're different modules.


So when cell.d does `import Noise;` and perlin.d does `import noise;`, 
then they're using two different, incompatible Noise interfaces.


Re: opCmp with structs

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

On 07.11.2015 16:59, anonymous wrote:

Wat. It even compiles with @safe. That's not good.


Filed an issue:
https://issues.dlang.org/show_bug.cgi?id=15315


Re: Compiler doesn't complain with multiple definitions

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

On 12.11.2015 06:27, ric maicle wrote:

I was playing with __traits and tried the code below.
Shouldn't the compiler emit a warning that I'm defining isPOD
multiple times and/or I'm defining something that is built-in
like isPOD?

// DMD64 D Compiler v2.069
import std.stdio;

struct isPOD {
bool status = false;
}

int main()
{
 byte isPOD = 0;
 writeln(isPOD);
 writeln(__traits(isPOD, typeof(isPOD)));
 return 0;
}


__traits has special syntax. The first "argument" must be from a list of 
special keywords that only have special meaning in that place. You can't 
put the name of a struct there, and you can't put the special keyword 
anywhere else. So there's no ambiguity, and you're not redefining 
anything. Everything's fine.


Re: A new instance of a variable?

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

On 13.11.2015 18:44, Ish wrote:

immutable int* j = new immutable int(i);
gives error:
locks1.d:27: error: no constructor for immutable(int);


Looks like your D version is rather old. I had to go back to dmd 2.065 
to see that error. 2.065 is from February 2014. We're at 2.069 now. I'd 
recommend updating the compiler.


If that's not an option, here are two variants that work with 2.065.

Allocate mutable, assign value, cast to immutable:

int* jm = new int;
*jm = i;
immutable int* j = cast(immutable) jm;
jm = null; /* So that you don't accidentally alter the data through jm. */

Pretty straight-forward, but verbose and not fool-proof at all.


Array literal:

immutable int imm = i; /* or declare i immutable to begin with */
immutable int* j = [imm].ptr;

Looks nicer, but allocates more space than necessary.



Bug? Bad file name?

2015-11-13 Thread Anonymous via Digitalmars-d-learn
I was playing with some code someone posted on the forum that 
involved opDispatch and compile time parameters. I pasted it in a 
file named templOpDispatch.d, ran it, and got an error. Then I 
noticed if I renamed the file it worked.


The source didn't matter; same thing happens with an empty main.

Ex: templOpDispatch.d contains just

void main() {}

Then running 'rdmd templOpDispatch.d' produces:

std.process.ProcessException@std\process.d(568): Failed to spawn 
new process (The requested operation requires elevation.)


0x004396F0
0x0042AC3A
0x00403F66
0x00403FDF
0x00433043
0x00432F57
0x00426B70
0x7577337A in BaseThreadInitThunk
0x77969882 in RtlInitializeExceptionChain
0x77969855 in RtlInitializeExceptionChain

Windows 7
rdmd build 20150923
DMD32 D Compiler v2.068.2

But I can rename the file to rdmd templOpDispatc.d (remove h) and 
all is good. Strange. Can anyone else reproduce this?


Re: I can't believe this !!

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

On 14.11.2015 07:30, MesmerizedInTheMorning wrote:

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

but it's true !

There's **nothing** to check the availability of a Key. At least I would
expect opIndex[string key] to return a JSONValue with .type ==
JSON_TYPE.NULL, but no...

Also If it was returning a JSONValue* it would be easyer to check if a
key is present.

God damn it, how could you miss this design flaw when std.json was
reviewed ?!


JSONValue supports `in`, though:

import std.stdio;
import std.json;
void main()
{
foreach (jsonStr; ["{}", "{\"foo\": 42}"])
{
JSONValue jsonObj = parseJSON(jsonStr);
const JSONValue* p = "foo" in jsonObj;
if (p is null) writeln("not found");
else writeln(*p);
}
}


Looks like documentation has been neglected.


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


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: 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: 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: 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(&library); /// 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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:

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-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&lang=gpp&id=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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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 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: 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: 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: [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(&foo.bar);
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: 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: 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: 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.


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




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(&r). 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.


  1   2   3   4   5   6   >