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: 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: 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: 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-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: 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, _);
 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, _);
enforce(0 != t.textureId_);
return t;
}
private:
GLuint textureId_;
}




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: 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: 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: 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: `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: `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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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 19:46, anonymous wrote:

> and there is point to it

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


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-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: Comparing arrays of floats?

2015-10-09 Thread anonymous via Digitalmars-d-learn
On Saturday 10 October 2015 00:14, Straivers wrote:

> Is it a bit-by-bit comparison,

no

> is the std.math.approxEqual function get called for 
> each element,

no

> or is it byte-by-byte across the entire array?

no

After comparing the lengths, the elements are checked for equality one by 
one, using the usual `==` operator.

`==` is different from bitwise comparison. For example, -0f and +0f are `==` 
equal but have different bits, and NaNs are equal no nothing, not even 
themselves.


Re: Varargs and default arguments

2015-10-07 Thread anonymous via Digitalmars-d-learn
On Wednesday 07 October 2015 02:22, Steven Schveighoffer wrote:

> On 10/6/15 4:27 PM, anonymous wrote:
[...]
>> void foo(T...)(string str=null, T args = T.init) {
[...]
> I find it quite fascinating that in anonymous' solution, the T.init 
> doesn't ever actually get used!

It's not used with IFTI, but if you instantiate the template explicitly, the 
defaults arguments come up.

Or rather, they should come up. It doesn't seem to work:


void foo(T ...)(T args = T.init) {}
void main()
{
foo!(int, float)(); /* Error: foo (int _param_0, float _param_1) is not 
callable using argument types () */
}


I filed an issue: https://issues.dlang.org/show_bug.cgi?id=15170


Re: What is the postfix for min long value?

2015-10-06 Thread anonymous via Digitalmars-d-learn
On Tuesday 06 October 2015 17:39, Ali Çehreli wrote:

> I would expect the following to work:
> 
>  writeln( -9_223_372_036_854_775_808L);
> 
> But it doesn't compile:
> 
>Error: signed integer overflow
> 
> It looks like a compiler bug to me. If so, a very embarrassing one. :)

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


Re: Bug? 0 is less than -10

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

On Tuesday, 6 October 2015 at 14:46:56 UTC, tcak wrote:

Maybe I am just too stressed out to see the problem.

[code]
import std.stdio;

void main(){
size_t dec = 0;

	writeln( dec, " ", (dec <= -10), " ", (dec >= 10), " ", ((dec 
<= -10) || (dec >= 10)) );

}
[/code]

[output]
0 true false true
[/output]

How is it generating "true" for (dec <= -10) ? Is there a 
special casting or something?


DMD 2.068.2, Ubuntu 64-bit


dec is a size_t. size_t is unsigned. -10 is cast to unsigned for 
the comparison, resulting in some huge value.


Re: Varargs and default arguments

2015-10-06 Thread anonymous via Digitalmars-d-learn
On Tuesday 06 October 2015 22:01, Nick Sabalausky wrote:

> Ok, D-style varargs can accept a parameter length of zero:
> 
> ---
> void foo(T...)(T args) {
>  //...
> }
> foo();
> foo(t1, t2);
> ---

Terminology fun:

The spec uses the term "D-style variadic function" for something else yet: 
`int abc(char c, ...);` -- http://dlang.org/function.html#variadic

Yours is technically a "variadic function template", I guess, i.e., a 
function template that's variadic, not a template of a variadic function.

> Is there any way to stick a param with a default value before that?
> 
> ---
> void foo(T...)(string str=null, T args=/+what goes here???+/) {
>  //...
> }
> foo();
> foo(str);
> foo(str, t1, t2);
> ---
> 
> Obviously this can be worked around easily enough by splitting it into 
> two overloads ("foo(string str=null)" and "foo(string str, T args)"), 
> but is there a way to do it in one?

You can put an expression tuple ("expression AliasSeq"??) there. T.init is 
one that always fits T's types. But you could generate one with different 
values, too.


void foo(T...)(string str=null, T args = T.init) {
//...
}
void main()
{
foo();
foo("");
foo("", 1, 2);
}



Re: Range of variables

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

On Wednesday, 30 September 2015 at 20:11:56 UTC, Freddy wrote:

Is there a way to make a range of a variables lazily?
---
int var1;
int var2;
void func()
{
int var3;
auto range = /*range of var1,var2,var3*/ ;
}
---


There's std.range.only which gives you a range over the arguments 
you pass without allocating an array for them. Not sure what you 
mean by "lazily".


http://dlang.org/phobos/std_range.html#only


Re: Interval Arithmetic

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

On Tuesday, 29 September 2015 at 21:04:06 UTC, Wulfrick wrote:
Is there an interval arithmetic library in D? I couldn’t find 
one.

None I am aware of.


In case I had to write my own, I understand that the IEEE 
standard floating point arithmetic provides operations for 
rounding up or down certain operations like summing, 
subtracting, etc. (thus overriding the default behavior of 
rounding to nearest representable).


How do I access this functionality in D? At first I thought 
that std.math.nextDown and nextUp is what I needed, but not so. 
Apparently these functions return the previous or next 
representable *after* the calculation has been done.


For example, I would like the value of x+y rounded in the 
arithmetic towards -\infty, which may or may not be 
nextDown(x+y).


Any luck?
Thanks for reading!


fencv.h  [1] + a few extern(C) declarations could work - changes 
the rounding mode.

Maybe there is an inline ASM solution, too.

I have never tried to use that from D. The FENV_ACCESS pragma 
could cause problems - don't know how to pass that info to a D 
compiler (never tried to figure it out).


It may be easier to generate an binding for an existing C/C++ 
lib, e.g. [2] (page is in German, but the downloadable tar.gz 
("komprimierte (gzipped) tar-Datei") contains an English readme. 
Boost also contains an interval arithmetic lib [3], but the use 
of C++ templates will most likely force you to write some glue 
code in C++...



[1] http://www.cplusplus.com/reference/cfenv/
[2] http://www.ti3.tuhh.de/keil/profil/ (GPL)
[3] 
http://www.boost.org/doc/libs/1_58_0/libs/numeric/interval/doc/interval.htm




Re: Move Semantics

2015-09-29 Thread anonymous via Digitalmars-d-learn
On Tuesday 29 September 2015 16:38, Alex wrote:

> Another question on move semantics from the cheap seats...
> 
> See my code here: http://dpaste.dzfl.pl/995c5af59dd6
[...]
> The first (minor) question is:
> I have to initialize some dummy inner objects, before I can apply 
> the move action. Is this really necessary? It won't be that 
> problem I think, if it is so, but it would be nicer, if I could 
> just perform the move operation.

Accessing an non-existing element of an associative array doesn't initialize 
it. You have to assign to it. I've been slightly annoyed by this, too. I'm 
not sure what the reasons for the current behavior are. I guess it would 
slow down accesses (a bit? a lot?).

> The second question is:
> Following my code, the inner object I moved does not disappear 
> from the array in the source outer object. Why? I tried it 
> without, with an empty and with a non empty destructor, the 
> result was the same.

`move` doesn't know what greater structure you're moving from. It just takes 
two locations. There's no way for it to figure out that the source location 
is an element of an associative array or whatever.

> And the third, main, question is:
> After I moved the inner object to the new outer object, the 
> pointer to the outer object remains in the old state, to the 
> source outer object. This is not what I expected! Well, yes this 
> is some subjective expectation, but shouldn't an implicit pointer 
> update itself to not break the logic of what it points to?

Your view on the relations of the objects is that the Inner objects in an 
Outer's _innerarr field are owned by that Outer object. The compiler and 
`move` have no such notion. Objects of nested classes are not restricted to 
exist in fields of their .outer objects.

All in all, I think you expected more from nested classes and `move` than 
they provide.

An object of a (non-static) nested class just has a pointer to an object of 
the outer class. All this allows is some shorter syntax. The bond between 
the two objects isn't any tighter than other pointers.

`move` does little more than copying. It avoids postblits and destroys the 
source if necessary (i.e. reset to .init). It doesn't have any notion of 
ownership transfer.


Re: Server side command execution.

2015-09-28 Thread anonymous via Digitalmars-d-learn
On Monday 28 September 2015 12:40, anonymous wrote:

> The client probably sends a newline; i.e. buffer[0 .. received] is
> "exit\n".

Or more likely it's "exit\r\n".


Re: Server side command execution.

2015-09-28 Thread anonymous via Digitalmars-d-learn
On Monday 28 September 2015 11:59, holo wrote:

> I changed my condition to:
> 
> if(to!string(buffer[0..received]) == "exit")
>   {
>   
>   break;
>   }
> 
> 
> But it still dint help.

The client probably sends a newline; i.e. buffer[0 .. received] is "exit\n".


Re: Parallel processing and further use of output

2015-09-26 Thread anonymous via Digitalmars-d-learn
On Saturday 26 September 2015 14:18, Zoidberg wrote:

> I've run into an issue, which I guess could be resolved easily, 
> if I knew how...
> 
> [CODE]
>  ulong i = 0;
>  foreach (f; parallel(iota(1, 100+1)))
>  {
>  i += f;
>  }
>  thread_joinAll();
>  i.writeln;
> [/CODE]
> 
> It's basically an example which adds all the numbers from 1 to 
> 100 and should therefore give 5050. Running the above 
> code gives 205579930677, leaving out "thread_joinAll()" the 
> output is 210161213519.
> 
> I suspect there's some sort of data race. Any hint how to get 
> this straight?

Definitely a race, yeah. You need to prevent two += operations happening 
concurrently.

You can use core.atomic.atomicOp!"+=" instead of plain +=:

shared ulong i = 0;
foreach (f; parallel(iota(1, 100+1)))
{
import core.atomic: atomicOp;
i.atomicOp!"+="(f);
}

i is shared because atomicOp requires a shared variable. I'm not sure what 
the implications of that are, if any.

Alternatively, you could use `synchronized`:

ulong i = 0;
foreach (f; parallel(iota(1, 100+1)))
{
synchronized i += f;
}

I'm pretty sure atomicOp is faster, though.


Re: Parallel processing and further use of output

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

On Saturday, 26 September 2015 at 13:09:54 UTC, Meta wrote:

On Saturday, 26 September 2015 at 12:33:45 UTC, anonymous wrote:

foreach (f; parallel(iota(1, 100+1)))
{
synchronized i += f;
}


Is this valid syntax? I've never seen synchronized used like 
this before.


I'm sure it's valid.

A mutex is created for that instance of synchronized. I.e., only 
one thread can execute that piece of code at a time.


If you're missing the braces, they're optional for single 
statements, as usual.


http://dlang.org/statement.html#SynchronizedStatement


Re: Why are static arrays not ranges?

2015-09-21 Thread anonymous via Digitalmars-d-learn
On Monday 21 September 2015 22:33, Jack Stouffer wrote:

> import std.range;
> 
> void main() {
>  int[6] a = [1, 2, 3, 4, 5, 6];
> 
>  pragma(msg, isInputRange!(typeof(a)));
>  pragma(msg, isForwardRange!(typeof(a)));
>  pragma(msg, isRandomAccessRange!(typeof(a)));
> }
> 
> $ dmd -run test.d
> false
> false
> false
> 
> That's ridiculous. Do I have to wrap my static arrays in structs 
> to get range primitives?

You can just slice them: `a[]` is an `int[]` which is a range.

> Is there an actual reason for this?

How would popFront work on an `int[6]`? popFront can't change the type, but 
it must remove an element.


Re: OS minimum version

2015-09-21 Thread anonymous via Digitalmars-d-learn
On Monday 21 September 2015 14:47, ponce wrote:

> 1. What is the minimum Windows version required by programs 
> created with DMD?

http://dlang.org/dmd-windows.html says: "Windows XP or later, 32 or 64 bit".


Re: Question about Object.destroy

2015-09-20 Thread anonymous via Digitalmars-d-learn
On Sunday 20 September 2015 20:34, Lambert Duijst wrote:

> On Sunday, 20 September 2015 at 18:21:52 UTC, Adam D. Ruppe wrote:
[...]
>> So after calling destroy(s), s is null, so it segfaults when 
>> you try to use it.
[...]
> Also when I print the address of s it gives me some hex number, 
> but not 0 (null).
> I use writeln("Address of s ", ) to print the address, not sure 
> if that is correct though.
> Before and after the explicit destroy I get the same address, 
> which is 7FFF549108D8.

 is the address of the variable. We're not interested that but in the 
reference that's stored in s. You can print that by casting to void*:

writeln(cast(void*) s);

But that doesn't change either. I think Adam is mistaken here.


Re: Simple template constraint question

2015-09-19 Thread anonymous via Digitalmars-d-learn
On Saturday 19 September 2015 19:09, WhatMeWorry wrote:

> And a more open ended question.  Is there a more elegant solution 
> for the
> below function?  Maybe a one-liner?  I have a knack for making 
> simple solutions
> complex :)
> 
> 
> 
> // Calculate the number of components for openGL generic
> // vertex attribute. Must be 1, 2, 3, 4.
> 
> // isAggregateType constraint accepts class, union, struct, and 
> interface
> 
> int getNumberComponents(T)(T someStruct) if (isAggregateType!(T))
> {
>  int members = 0;
>  foreach (i, member; someStruct.tupleof)
>  {
>  //writefln("Member %s:", i);
>  //writefln("  type : %s", typeof(member).stringof);
>  //writefln("  value: %s", member);
>  members++;
>  }
>  return members;
> }

If the whole goal is to get how many members T has:

template getNumberComponents(T) if (is(T == struct))
{
enum getNumberComponents = T.tupleof.length;
}


Or you can write `T.tupleof.length` directly, of course.


Re: Tried release build got ICE, does anyone have a clue what might cause this?

2015-09-19 Thread anonymous via Digitalmars-d-learn
On Sunday 20 September 2015 00:09, Random D user wrote:

> class Gui
> {
>  enum MouseButton { Left = 0, Right };
> 
> private:
> 
>  struct ClickPair
>  {
>   MouseButton button = MouseButton.Left;
>  };
> 
>  struct ClickPair  // Second struct ClickPair with the enum 
> above --> Assertion failure: 'type->ty != Tstruct || 
> ((TypeStruct*)type)->sym == this' on line 957 in file 'struct.c'
>  {
>   MouseButton button = MouseButton.Left;
>  };
> };

Off topic: You don't need semicolons after struct/class declarations in D.


Re: Passing Arguments on in Variadic Functions

2015-09-17 Thread anonymous via Digitalmars-d-learn
On Thursday 17 September 2015 23:27, jmh530 wrote:

> I think I could figure out how to look through the arguments for 
> a bool, but wouldn't that make me give up the default value for 
> the bool?

If you don't find a bool, you use the default value.


Re: Final templated interface method not found

2015-09-15 Thread anonymous via Digitalmars-d-learn
On Wednesday 16 September 2015 06:14, Andre wrote:

> Hi,
> 
> following coding shoud work, or?
> It doesn't compile with v2.068.0.
> 
> Kind regards
> André
> 
> interface IfStatement
> {
>   void execute();
>   
>   final void execute(T...)(T t)
>   {
>   execute();
>   }
> }
> 
> class Statement: IfStatement
> {
>   void execute(){}
> }
> 
> void main()
> {
>   new Statement().execute(1,"Hello World");
> }

You need to add IfStatement.execute to the overload set like so:

class Statement: IfStatement
{
alias execute = IfStatement.execute;
void execute(){}
}



Re: Initalizing complex array types or some other problem ;/

2015-09-15 Thread anonymous via Digitalmars-d-learn
On Wednesday 16 September 2015 03:46, Prudence wrote:

> In any case, Maybe you are not as smart as you think you are if 
> you can't understand it?

kthxbye


Re: Initalizing complex array types or some other problem ;/

2015-09-15 Thread anonymous via Digitalmars-d-learn
On Tuesday 15 September 2015 22:09, Prudence wrote:

> The code below doesn't work.

Please be more specific in how it doesn't work. Mention the error message if 
there is one, or say how the code behaves differently from what you'd 
expect.

Trying to compile the code (after kicking getch out), I get this error:
core.exception.RangeError@test.d(103): Range violation

Line 103 is: writeln(MyStore.Store[k].length);

I can't find where you set Store[k]. Maybe you forgot that or deleted it 
accidentally?

I made a guess and added this line in SingleStore.New:
o.Store[k] ~= tuple(v, o);

It still throws a range error with this. That's because associative arrays 
are a little weird, unfortunately.

An AA is effectively initialized on the first assignment. So (with my 
addition) the first SingleStore.New call initializes the AA. But it only 
initializes o.Store, not the original variable s (i.e. ObjectStore.Store). s 
is left empty.

Possible solutions/workarounds:
* Append to s[k], then assign s to o.Store.
* Initialize ObjectStore.Store in a static constructor:

static this()
{
Store[TKey.init] = [];
Store.remove(TKey.init);
}


Aside: I have no idea what you're doing there, but it looks pretty 
complicated, to the point that I'd guess that it's more complicated than 
necessary.


Re: chaining chain Result and underlying object of chain

2015-09-14 Thread anonymous via Digitalmars-d-learn
On Monday 14 September 2015 16:17, Laeeth Isharc wrote:

> chain doesn't seem to compile if I try and chain a chain of two 
> strings and another string.
> 
> what should I use instead?

Please show code, always.

A simple test works for me:


import std.algorithm: equal;
import std.range: chain;
void main()
{
auto chain1 = chain("foo", "bar");
auto chain2 = chain(chain1, "baz");
assert(equal(chain2, "foobarbaz"));
}



Re: chaining chain Result and underlying object of chain

2015-09-14 Thread anonymous via Digitalmars-d-learn
On Monday 14 September 2015 17:01, Laeeth Isharc wrote:

>auto chain1 = chain("foo", "bar");
>chain1 = chain(chain1, "baz");
> 
> Realized that in this case it was much simpler just to use the 
> delegate version of toString and sink (which I had forgotten 
> about).  But I wondered what to do in other cases.  It may be 
> that the type of chain1 and chain2 don't mix.

Yes, the types don't match. The result types of most range functions depend 
on the argument types.

Let's say chain("foo", "bar") has the type ChainResult!(string, string). 
Then chain(chain("foo", "bar"), "baz") has the type ChainResult!
(ChainResult!(string, string), string). Those are different and not 
compatible.

You can get the same type by:

a) being eager:

import std.array: array;
auto chain1 = chain("foo", "bar").array;
chain1 = chain(chain1, "baz").array;


(At that point you could of course just work with the strings directly, 
using ~ and ~=.)

b) being classy:

import std.range.interfaces;
InputRange!dchar chain1 = inputRangeObject(chain("foo", "bar"));
chain1 = inputRangeObject(chain(chain1, "baz"));


Those have performance implications, of course. Being eager means allocating 
the whole thing, and possibly intermediate results. Being classy means 
allocating objects for the ranges (could possibly put them on the stack), 
and it means indirections.


Re: Passing Arguments on in Variadic Functions

2015-09-14 Thread anonymous via Digitalmars-d-learn
On Monday 14 September 2015 21:59, jmh530 wrote:

> This approach gives the correct result, but dmd won't deduce the 
> type of the template. So for instance, the second to the last 
> line of the unit test requires explicitly stating the types. I 
> may as well use the alternate version that doesn't use the 
> variadic function (which is simple for this trivial example, but 
> maybe not more generally).

You can use a variadic template instead:


import std.algorithm : sum;

auto test(R, E ...)(R r, E e)
{
return sum(r, e);
}

unittest
{
int[] x = [10, 5, 15, 20, 30];
assert(test(x) == 80);
assert(test(x, 0f) == 80f);
assert(test(x, 0f) == 80f);
}



Re: [D Cookbook]about "Communicating with external processes" part.

2015-09-13 Thread anonymous via Digitalmars-d-learn
On Sunday 13 September 2015 15:32, xky wrote:

> [ pipe.d ]:
> ==
> import std.process;
> import std.stdio;
> 
> void main(){
>   auto info = pipeProcess("child.exe");
>   scope(exit) wait(info.pid);
> 
>   info.stdin.writeln("data to send to the process");
>   info.stdin.close();
> 
>   foreach(line; stdout.byLine){

I think it should be `info.stdout.byLine` here.

>   writeln("Received ", line, " from child.");
>   }
> }
> ==



Re: alias for regular expressions

2015-09-13 Thread anonymous via Digitalmars-d-learn
On Sunday 13 September 2015 21:47, Thunderbird wrote:

> Some special interest thingamabob:
> 
> I've tried to redefine "else if" as "elif" using "alias elif = 
> else if;". No matter what to no avail.
> 
> I know this is probably useless fancy stuff, but is there any way 
> to get this done without much ado?

no


Re: I guess this is a bug?

2015-09-12 Thread anonymous via Digitalmars-d-learn
On Saturday 12 September 2015 20:28, Random D user wrote:

> prints (with option B):
> bar: 0.00, 0.00   // BUG??
> baz: 1.00, 2.00

Looks like a bug to me. Please file an issue at https://issues.dlang.org/


Re: Mixin templates accessing mixed out scope

2015-09-12 Thread anonymous via Digitalmars-d-learn
On Saturday 12 September 2015 16:30, Ali Çehreli wrote:

> Reduced:
[...]
> Error: type SingleStore is not an expression

Reduced further:


class MyStore
{
class SingleStore
{
static void New() // Removing 'static' compiles
{
new SingleStore();
}
}
}


And now the problem can be spotted:

SingleStore is a nested class. That means, instances of it are bound to 
MyStore instances. But New is static, so it doesn't have a MyStore to which 
it could attach the `new SingleStore`.

That error message is pretty awful. I filed an issue:
https://issues.dlang.org/show_bug.cgi?id=15049

As for a fix: I guess SingleStore isn't supposed to be a nested class. Mark 
it static then.


Re: Mixin templates accessing mixed out scope

2015-09-12 Thread anonymous via Digitalmars-d-learn
On Saturday 12 September 2015 19:36, Prudence wrote:

> On Saturday, 12 September 2015 at 17:11:04 UTC, anonymous wrote:
[...]
>> class MyStore
>> {
>> class SingleStore
>> {
>> static void New() // Removing 'static' compiles
>> {
>> new SingleStore();
>> }
>> }
>> }
[...]
>> As for a fix: I guess SingleStore isn't supposed to be a nested 
>> class. Mark it static then.
> 
> NO! That is the whole point!

So New is supposed to create a SingleStore that's associated with a MyStore?

That static can't work like that then. It doesn't escape just the first 
level (SingleStore), but all levels (SingleStore and MyStore). That is, a 
static method isn't bound to any object. But you need a MyStore to construct 
a (nested) SingleStore. You have to pass a MyStore somehow.

It can come via `this.outer`:

class MyStore
{
class SingleStore
{
SingleStore New()
{
return new SingleStore;
}
}
}
void main()
{
auto ms = new MyStore;
auto ss1 = ms.new SingleStore;
auto ss2 = ss1.New();
}

But here you need a SingleStore object to call New on. Not what you want, I 
think.

Or the MyStore can come via parameter:

class MyStore
{
class SingleStore
{
static SingleStore New(MyStore ms)
{
return ms.new SingleStore;
}
}
}
void main()
{
auto ms = new MyStore;
auto ss = MyStore.SingleStore.New(ms);
}


Or you can move New a level up, into MyStore, and then plain `this` is the 
needed MyStore:

class MyStore
{
class SingleStore
{
}
SingleStore NewSingleStore()
{
return new SingleStore;
}
}
void main()
{
auto ms = new MyStore;
auto ss = ms.NewSingleStore();
}




Re: Is this a bug?

2015-09-11 Thread anonymous via Digitalmars-d-learn
On Friday 11 September 2015 12:33, Rene Zwanenburg wrote:

> The following fails to compile with an 'cannot deduce function 
> from argument types' error. When using an array of something 
> other than TypeInfo_Class everything works as expected.
> 
> void main()
> {
>   import std.algorithm.mutation : remove;
>   
>   TypeInfo_Class[] arr;
>   TypeInfo_Class c;
>   arr = arr.remove!(a => a is c);
> }

Yes, it's a bug. It should work.

The problem is that TypeInfo_Class has a method called "init" which shadows 
the built-in type property of the same name. This confuses ElementType.

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


Re: Sum and other algorithm functions

2015-09-10 Thread anonymous via Digitalmars-d-learn
On Thursday 10 September 2015 15:48, Namal wrote:

> Hello,
> 
> how can I define the range for the sum function which I want to 
> sum up? For instance how do I sum up the first 3 elements of an 
> array
> 
> int[] a = [1,2,3,4,5,6,7,8,9];
> 
> or the last 3?

First you slice the first/last 3, then you sum them.

first 3: a[0 .. 3].sum
last 3: a[$ - 3 .. $].sum


Re: ref parameter qualifier and static arrays

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

On Wednesday, 9 September 2015 at 20:18:57 UTC, Paul wrote:


Is it possible to call a function like this...

void foo(ref int[] anArray)

...with slices of static arrays? I thought I might be able to 
use [0..$-1] but to no avail - I get an error like this (which 
is confusing!):
Note that the upper bound of the slice is exclusive - [0..$-1] is 
not the whole array but everthing except the last entry. To slice 
the whole array, you can use [0..$] or just write

int[42] a;
auto b = a[];



(ref int[] anArray) is not callable using argument types (int[])

I've modified the function declaration and used .ptr when 
calling it but it seems like a retrograde step for a modern 
language - although I suppose ref is pretty much the same thing.


In practice I'm using arrays of structs (which are of various 
fixed sizes and known at compile time) that are currently 
global in scope - something that I'd like to avoid.


I suppose I could just ask, what is the 'best' way to give 
access to variously sized static arrays between different 
modules?


It is impossible to pass a rvalue as a reference (intended 
behaviour, afaik it is causes problems if the reference escapes 
from foo and outlasts the rvalue). There is a bug report about 
the strange error message somewhere in the bug tracker.
Some time ago someone announced to implement passing rvalue as 
reference but it seems the PR was not merged for dmd 2.068.


Workaround:
use a temporary variable.
instead of

int[42] a;
foo(a[]);

write

int[42] a;
auto tmp = a[];
foo(tmp);


Re: ref parameter qualifier and static arrays

2015-09-09 Thread anonymous via Digitalmars-d-learn
On Wednesday 09 September 2015 22:18, Paul wrote:

> 
> Is it possible to call a function like this...
> 
> void foo(ref int[] anArray)
> 
> ...with slices of static arrays? I thought I might be able to use 
> [0..$-1] but to no avail - I get an error like this (which is 
> confusing!):
> 
> (ref int[] anArray) is not callable using argument types (int[])

Slice expressions are not lvalues (can't take their addresses), so you can't 
pass them in ref parameters. You can store the slice in a variable and pass 
that:


void f(ref int[] x) {}
int[3] a;
version(none) f(a[]); /* Nope, a[] is not an lvalue. */
int[] s = a[];
f(s); /* Ok, s is an lvalue. */


But if you want to pass slice expressions, then you probably don't need that 
ref.

When you pass a slice (without ref), what's actually passed is a pointer and 
length. The contents are not copied. That means, when you alter an array 
element, the change will be done the original, even without ref:


void f(int[] x) {x[0] = 1;}
int[3] a = [0, 0, 0];
f(a[]);
assert(a[0] == 1); /* passes */


ref would allow you to resize the original dynamic array:


void f(ref int[] x) {x ~= 4;}
int[] a = [1, 2, 3];
f(a);
assert(a.length == 4); /* passes */


But there's no point in doing that to temporaries like slice expressions.


Re: What are (dis)advantages of using pure and immutable by default?

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 13:12, Bahman Movaqar wrote:

> I was under the impression that when a variable, that is declared 
> as `immutable`, is passed to a function, a copy of the value is 
> passed.
>
> However based on "marks" I can imagine that since the data is 
> marked as `immutable` only a reference is passed; and the 
> compiler guarantees that what is referenced to never changes.  Am 
> I right?

Generally immutable doesn't affect how things are passed around. An 
immutable type is passed the same as a mutable version of it.

Compilers may optimize based on immutability. This may mean that a reference 
is passed instead of a copy, or the other way around. I don't know if 
compilers do such things currently, or how much potential is in that. Also, 
I don't think the language has a stance on that; it's purely an 
optimization.

immutable does affect how you can pass things around, though. An example:


void f(int a) {}
void g(int* a) {}

void main()
{
int xm;
immutable int xi;
f(xm); /* ok, obviously */
f(xi); /* ok */

int* ym = 
immutable int* yi = 
g(ym); /* ok, obviously */
g(yi); /* doesn't compile */
}


f(xi) is ok because when passing an int or an immutable(int), it's copied 
completely. So the f cannot possibly mutate the original immutable variable 
xi.

g(yi) is not ok, because when passing an int* or an immutable(int*), only 
the pointer is copied. So g could dereference yi and mutate the referenced 
immutable variable xi.

The same applies to other forms of references: classes, ref parameters, 
arrays.


Re: Better unittest failure output

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 13:57, Bahman Movaqar wrote:

> I am working on a simple project created with DUB[1].
> When unit tests the output reads really cryptic to me; for 
> example:
> 
>  $ dub test
[...]
>  core.exception.AssertError@source/e002.d(111): unittest 
> failure
[...]
> 
> It is almost impossible for me to comprehend anything useful out 
> of this, except that, well, the tests have failed :-)

>From that one line I left intact above, you should also be able to figure 
out that it's the test in source/e002.d, line 111 that failed.

> Is there any compiler switch, argument to `assert` or trick to 
> make `unittest` output more helpful messages when failing?

You can pass a custom message as a second argument to assert:
assert(condition, "message goes here");

I think there are testing libraries/frameworks around that mean to provide 
more than the basic built-in things. But I haven't tried any, so I can't 
recommend anything. Try searching for "test" here: http://code.dlang.org/


Re: What are (dis)advantages of using pure and immutable by default?

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 12:40, Bahman Movaqar wrote:

> It seems to me a good practice to mark all functions that I write 
> as `pure` and define all the variables as `immutable`, unless 
> there is a reason not to.

I agree.

> I can see some serious advantages of this, most notable of which 
> is minimum side-effect and predictability of the code.  However I 
> suppose it's going to impact the performance and memory footprint 
> as well, though I have no idea how deep the impact will be.

I don't see how merely marking things immutable/pure would affect 
performance negatively. They're just marks on the type. If anything, you 
could get a performance boost from the stricter guarantees. But 
realistically, there won't be a difference.

If you change your algorithms to avoid mutable/impure, then you may see 
worse performance than if you made use of them. But I suppose that would be 
"a reason not to" mark everything immutable/pure.


Re: function argument restrictions for templated struct

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 17:51, Laeeth Isharc wrote:

> Is there a more elegant way to write the template arg 
> restrictions for display?
[...]
> void display(T)(T a)
> if (__traits(isSame, TemplateOf!(T), Bar))
> {
>   writefln("%s",a);
> }

if (isInstanceOf!(Bar, T))


Re: Better unittest failure output

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 14:12, Bahman Movaqar wrote:

> Thanks.  This is indeed helpful.  OT but where can I view the 
> documentation for `unittest` and `assert`?

unittest: http://dlang.org/unittest.html
assert: http://dlang.org/expression.html#AssertExpression (I don't know why 
it's considered an expression and not a statement.)


Re: Windows Header consts

2015-09-07 Thread anonymous via Digitalmars-d-learn
On Monday 07 September 2015 21:06, Prudence wrote:

> If you think mentally changing a . to a _ is a hassle then your 
> in trouble! An apple a day simply won't help!
[...]
> Oh well, some people 
> just don't like progress! Do you want to go back to using wooden 
> wheels too?
[...]
> Get out of the dark ages!

This is uncalled for. Please stay friendly.


Re: reading file byLine

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

On Sunday, 6 September 2015 at 15:41:34 UTC, Namal wrote:
is there any function that removes double elements in a sorted 
array?


std.algorithm.iteration.uniq

http://dlang.org/phobos/std_algorithm_iteration.html#uniq


Re: reading file byLine

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

On Sunday, 6 September 2015 at 16:17:29 UTC, Namal wrote:
Error: module comparison is in file 
'std/algorithm/comparison.d' which cannot be read

import path[0] = /usr/include/dmd/phobos
import path[1] = /usr/include/dmd/druntime/import

when I try to load the headers like in the example


Are you on 2.066 or older? Back then std.algorithm hasn't been 
split into submodules yet. Just import std.algorithm then instead 
of std.algorithm.comparison, std.algorithm.iteration, etc.


Re: Abstractioning away main/winMain

2015-09-05 Thread anonymous via Digitalmars-d-learn
On Saturday 05 September 2015 07:52, anonymous wrote:

> This doesn't work because delegates and static initialization don't go
> together. You can use a static constructor:
> 
> 
> const Application MyApp;
> static this()
> {
> Application.New({import std.stdio; std.stdio.writeln("MY APP IS
> COOL");

Should be: MyApp = Application.New({...});

> });
> }
> 



Re: Superfluous code in switch statement

2015-09-04 Thread anonymous via Digitalmars-d-learn
On Friday 04 September 2015 23:04, Timon Gehr wrote:

> DMD never warns about dead code.

It warns here:


import std.stdio;
void main()
{
return;
writeln("hi"); /* Warning: statement is not reachable */
}



Re: Abstractioning away main/winMain

2015-09-04 Thread anonymous via Digitalmars-d-learn
On Saturday 05 September 2015 03:43, Prudence wrote:

> Standard and Win32 apps are so old school!
> 
> I'd like to hide WinMain by wrapping it in an application
> class(more or less).
> 
> Essentially I have an Application class
> 
> class Application
> {
> public static Application New(void delegate() entry)
> {
> 
> }
> }
> 
> 
>  Another module
> 
> extern (Windows) int WinMain(...)
> {
> 
> 
> }
> 
>  User Module:
> 
> 
> const MyApp = Application.New({ std.stdio.writeln("MY APP IS
> COOL"); });
> 
> 
> But the lamba runs into a problem because of the static nature of
> the program... much less figuring out how to hook WinMain up into
> it.

Please provide self-contained code. Without key details it's hard to 
understand where things are going wrong.

I'm guessing your actual code essentially tries to do this:


class Application
{
void delegate() entry;
public static Application New(void delegate() entry)
{
auto a = new Application;
a.entry = entry;
return a;
}
}

const MyApp = Application.New({import std.stdio; std.stdio.writeln("MY APP 
IS COOL"); });
/* Error: non-constant nested delegate literal expression __lambda6 */

void main() /* or WinMain */
{
MyApp.entry();
}


This doesn't work because delegates and static initialization don't go 
together. You can use a static constructor:


const Application MyApp;
static this()
{
Application.New({import std.stdio; std.stdio.writeln("MY APP IS COOL"); 
});
}


Or you can make `entry` a function instead of a delegate:


class Application
{
void function() entry;
public static Application New(void function() entry)
{
...
}
}


> Essentially I don't want the user ever to have to know how there
> entry point came into being but there is this funkyness about it
> because Application never gets any control to call the user's
> Entry function. Whats worse is that D tries to evaluate the
> lambda at compile time. It's as if D only allows non-static data
> inside functions.
> 
> 
> The idea is to have WinMain actually call the Entry lamba
> function once it gets ran(transfer control)... but this seems to
> be difficult or impossible with D and I'm not sure why or, if
> not, how to get it to work without having to make the user jump
> through hoops.
> 
> I suppose I could create the Application(Using New instead of
> new) inside of WinMain, but the issue still remains on how to get
> the user entry point(I suppose some compile time reflection could
> be used?).
> 
> Any ideas?

I'm probably being naive and the following falls short somehow, but how 
about this:


/* your module */
void function() userMain;

void main() /* or WinMain */
{
/* ... stuff ... */
userMain();
/* ... stuff ... */
}

/* user module: */
/* import your module; */
static this()
{
userMain = {import std.stdio; std.stdio.writeln("MY APP IS COOL"); };
}



Re: Problem with using struct ranges with @disabled this(this) with some range functions

2015-09-02 Thread anonymous via Digitalmars-d-learn
On Wednesday 02 September 2015 09:52, Uranuz wrote:

> I want to understand if we have *save* method in Forward Range
> then why or in which cases we should use plain struct copying
> instead. Should we assume that these two ways are equal or not?

No, don't assume that they're the same.

> Also as far as I understand behaviour for Input Ranges vs Forward
> Ranges would be different, because you could not store cursor on
> object like network data stream, because as soon as you read from
> it you cannot save some range that will point on previous bytes
> in network stream, because they are gone if you read them.
> 
> So for Input Range copy will always point on current state, but
> not previois state, that was saved before in another range
> pointing to the same source.

A copy of an input range may reflect the original, but it may also become 
invalid when the original is touched. Any operation on the original 
(especially popFront) may leave the copy in an invalid state, and vice 
versa.

That means, when you make a copy of an input range, you should not use the 
original anymore.

> For Forward Range we have ability to save cursor position and
> return to it later. In this case would copying via postblit would
> be equal to *save* method or would be similar as for Input Range.

Can go either way. Copying a forward range may work like a call to `save`, 
but it's not guaranteed/required to.

When you need the behavior of `save`, call `save`. Do not assume that 
copying works like `save`.

Do also not assume that a copy and the original of a range update each other 
correctly. When you pass an input range to some function and you want the 
operation to affect the original, use std.range.refRange to pass a 
reference.


Re: new static array

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

On Wednesday, 2 September 2015 at 06:04:40 UTC, Ali Çehreli wrote:

> with int[4] it compiles and runs. int[][4] fails. Is this a
bug?

I think so.


https://issues.dlang.org/show_bug.cgi?id=15004
may related to
https://issues.dlang.org/show_bug.cgi?id=10740



new static array

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

Hello,

I tried to send a string[4] with std.concurrency:

import std.concurrency;
import std.stdio;
void fun() {
receive((string[4] data) { writeln(data);});
}

void main() {
string[4] data;
auto tid = spawn();
send(tid, data);
}

I got (dmd 2.068)
/usr/include/dmd/phobos/std/variant.d(633): Error: new can only 
create structs, dynamic arrays or class objects, not string[4]'s

[...]

with int[4] it compiles and runs. int[][4] fails. Is this a bug?

Simple workaround: send a slice.


Re: observation: D getting a bit complex

2015-08-30 Thread anonymous via Digitalmars-d-learn
On Sunday 30 August 2015 04:42, Spacen Jasset wrote:

 immutable(ElementEncodingType!(ElementType!Range))[]
 buildPath(Range)(Range segments) if (isInputRange!Range 
 isSomeString!(ElementType!Range));
 pure nothrow @safe immutable(C)[] buildPath(C)(const(C)[][]
 paths...) if (isSomeChar!C);
 
 http://dlang.org/phobos/std_path.html

It's less horrible in the /library/ docs:


immutable(ElementEncodingType!(ElementType!Range))[] buildPath(Range)(
  Range segments
)
if (isInputRange!Range  isSomeString!(ElementType!Range));

immutable(C)[] buildPath(C)(
  const(C)[][] paths
) pure nothrow @safe
if (isSomeChar!C);


http://dlang.org/library/std/path/build_path.html

The /library/ docs are supposed to replace the current /phobos/ ones, but I 
don't know what's the latest on that.


Re: Reading and converting binary file 2 bits at a time

2015-08-29 Thread anonymous via Digitalmars-d-learn
On Saturday, 29 August 2015 at 23:34:47 UTC, Gary Willoughby 
wrote:
But it might not be safe: 
http://forum.dlang.org/thread/ztefzijqhwrouzlag...@forum.dlang.org


That link just takes me to this thread here again.


Re: Arrays of structs

2015-08-27 Thread anonymous via Digitalmars-d-learn
On Thursday 27 August 2015 14:35, BBasile wrote:

 Anyway. I cheat a bit with attributes but as long as it's only
 for me...I know this kinds of functions are not phobos-level.

Sure, as long as you're cautious and regard those functions as unsafe, you 
may be fine. You still risk accidentally writing unsafe code that's marked 
@safe, but that's up to you.

But when you show such code in the learn group, I think it's important to 
point out that this usage of @trusted is wrong. If only to warn newbies 
about it.


Re: What is this function call operator?

2015-08-27 Thread anonymous via Digitalmars-d-learn
On Thursday 27 August 2015 17:18, Gary Willoughby wrote:

 What is this function call operator? (...) Where can i learn more
 about it?

http://dlang.org/operatoroverloading.html#function-call
http://ddili.org/ders/d.en/operator_overloading.html#ix_operator_overloading.opCall



Re: Arrays of structs

2015-08-27 Thread anonymous via Digitalmars-d-learn
On Thursday 27 August 2015 13:15, BBasile wrote:

 https://github.com/BBasile/iz/blob/master/import/iz/types.d#L125
 https://github.com/BBasile/iz/blob/master/import/iz/types.d#L150
 https://github.com/BBasile/iz/blob/master/import/iz/types.d#L191

Your use of @trusted is wrong and dangerous. @trusted functions are supposed 
to be memory-safe, but you're marking unsafe functions with it.

Things like a @trusted `free` [1] are just plain wrong. `free` isn't memory-
safe.

The problems with @trusted templates can be more subtle. Even if the 
template body itself doesn't do anything unsafe, the template arguments are 
being trusted, too. So if the template ever calls any code from the 
arguments (including constructors, destructors, postblits, ...), then it 
cannot be marked @trusted.


[1] https://github.com/BBasile/iz/blob/master/import/iz/types.d#L112


Re: multiline string literal with CRLF

2015-08-26 Thread anonymous via Digitalmars-d-learn
On Wednesday 26 August 2015 20:28, Marek Janukowicz wrote:

 Is there any way to input such a literal? Both `...` and qEOS...EOS do
 not allow escape sequences. I'm on Linux, but I need precisely CRLF, not
 just \n.

I'm probably missing the point, but:

Hello\r\nworld

Or if you want to include the \n verbatim:

Hello\r
world



Re: Casting pointers

2015-08-26 Thread anonymous via Digitalmars-d-learn
On Wednesday 26 August 2015 14:14, John Burton wrote:

 This would be undefined behavior in c++ due to aliasing rules on
 pointers. It appears to work reliably in D when I try it, but
 that's obviously no guarantee that it's correct or will continue
 to do so.
 
 Is this correct code in D? And if not, what should I do instead
 to cleanly and efficiently extract structured data from a
 sequence of bytes?
 
 import std.stdio;
 
 struct data
 {
  int a;
  int b;
 }
 
 void main()
 {
  byte[] x = [1, 2, 3, 4, 5, 6, 7, 8];
 
  data* ptr = cast(data*)(x);
  printf(%x %x\n, ptr.a, ptr.b);
 
 }

There's an open issue about it:
https://issues.dlang.org/show_bug.cgi?id=10750

I don't know where we stand exactly, but by the looks of it, strict aliasing 
has never been added to the spec. So compilers should not assume it.

As David Nadlinger points out: There is already quite a lot of D code out 
there that violates the C-style strict aliasing rules.

I think that code should be fine for now. If it isn't, we have a problem, 
because with a silent spec we have no way of knowing what alternatives 
should work.


Re: NYT data article based on work of EMSI, who I think are a D shop

2015-08-25 Thread anonymous via Digitalmars-d-learn
On Tuesday 25 August 2015 06:55, Laeeth Isharc wrote:

 http://www.nytimes.com/2015/08/23/magazine/the-creative-apocalypse-that-wasnt.html
 
 Interesting article as it corrects misconceptions of a few years
 back by looking at the data.  This is based on tools from EMSI,
 who are a D shop.
 
 Congratulations to EMSI, and it would be great to hear more from
 them sometime about how they use D (I know they spoke at dconf
 once)

This isn't really relevant to learning D. Did you mean to post to the 
general group?


Re: C++/STL interop

2015-08-25 Thread anonymous via Digitalmars-d-learn
On Monday 24 August 2015 17:37, anonymous wrote:

 I saw https://issues.dlang.org/show_bug.cgi?id=14956 .
 
 
 questions:
 - is std.basic_string released into the wild?
 - where do I find std.basic_string?
 - does std.vector exist? That would allow me to get rid of some
 C++ clue code (build an C-like interface, copy data etc)...

basic_string and char_traits are C++ things. If you're looking for D 
bindings for them, I don't know if they exist or where to find them. You 
could try asking in the bugzilla issue you linked.


Re: NYT data article based on work of EMSI, who I think are a D shop

2015-08-25 Thread anonymous via Digitalmars-d-learn
On Wednesday 26 August 2015 00:22, Laeeth Isharc wrote:

 I'm open to being corrected about where the right place should
 be, but it wasn't an accidental decision to post here.

I think you might find more interest over in General. Learn tends to be a 
question/answer kind of thing. So people probably don't come here to find 
articles.

But I don't mean to play content police. I just thought you might have 
misclicked.


C++/STL interop

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

I saw https://issues.dlang.org/show_bug.cgi?id=14956 .


questions:
- is std.basic_string released into the wild?
- where do I find std.basic_string?
- does std.vector exist? That would allow me to get rid of some 
C++ clue code (build an C-like interface, copy data etc)...


Putting

extern(C++)
{
  void foo14a(std.basic_string!(char) *p);
  void foo14b(std.basic_string!(int) *p);
  void foo14f(std.char_traits!char* x, std.basic_string!char* p, 
std.basic_string!char* q);

}

into a file results in  Error: undefined identifier (dmd 2.068).


Re: How to use ranges?

2015-08-23 Thread anonymous via Digitalmars-d-learn
On Sunday 23 August 2015 19:58, Doolan wrote:

 You can use typeof to get the type of a range expression when
 typing it out is impractical/impossible.
 What if I want to save a range in a struct? Or is a range more of
 a verb than a noun..?

Can still use typeof then:

struct S
{
import std.range: tee;
import std.stdio: writeln;

typeof((int[]).init.tee!writeln) teeing;

this(int[] a)
{
teeing = a.tee!writeln;
}
}

void main()
{
auto s = S([1, 2, 3, 4]);
foreach(x; s.teeing) {}
}


Alternatively you can get classy and use std.range.interfaces:


struct S
{
import std.range: tee;
import std.range.interfaces: InputRange, inputRangeObject;
import std.stdio: writeln;

InputRange!int teeing;

this(int[] a)
{
teeing = inputRangeObject(a.tee!writeln);
}
}

void main()
{
auto s = S([1, 2, 3, 4]);
foreach(x; s.teeing) {}
}


 I need to compress some data, and luckily it's very suited for
 Running Length Encoding, so I've gone with doing that.
 Occasionally changes need to be made to this data and so rather
 than extracting the data, changing it, and then recompressing it,
 I can just do the equivalent of leaving a post-it note reminding
 the decompression function to sprinkle these changes in after
 decompression. Occasionally, I also need to grab some values out
 of this data without decompressing it, but for every additional
 value I look for I have to search the post-it notes and it gets a
 little fiddly.

Here's a quick implementation of a run-length decoder range, and some 
example usage.

I'm not sure how to go about the post-it note concept, or how practical it 
is. The decoder is not a random-access range, so when you want to edit the 
data and access individual items, then decode-edit-encode may work better. 
You don't have to shoehorn something into ranges just because ranges are 
cool.

But if you want to apply a bunch of transformations to the whole thing, then 
ranges shine.


import std.range: empty, front, popFront, save;
import std.stdio;

struct RunLengthItem(T)
{
T value;
size_t length;
}

struct RunLengthDecoder(T)
{
RunLengthItem!T[] items;
size_t currentRun = 0;

@property bool empty() const {return items.empty;}
@property T front() {return items.front.value;}
void popFront()
{
++currentRun;
if(currentRun = items.front.length)
{
items.popFront();
currentRun = 0;
}
}
@property RunLengthDecoder save() {return this;}
}

void main()
{
/* two 'f's, three 'o's, five 'b's, seven 'a's, eleven 'r's */
RunLengthItem!dchar[] data = [
RunLengthItem!dchar('f', 2),
RunLengthItem!dchar('o', 3),
RunLengthItem!dchar('b', 5),
RunLengthItem!dchar('a', 7),
RunLengthItem!dchar('r', 11)
];

auto decoder = RunLengthDecoder!dchar(data);

/* Just print the elements (writeln is aware of ranges): */
writeln(decoder.save); /* ffooobaaarrr */

/* Uppercase when printing: */
import std.uni: asUpperCase;
writeln(decoder.save.asUpperCase); /* FFOOOBAAARRR */

/* Filter out the 'b's, uppercase, and put an underscore every five 
characters: */
import std.algorithm: filter, joiner;
import std.range: chunks;
auto r = decoder.save
.filter!(c = c != 'b')
.asUpperCase
.chunks(5).joiner(_);
writeln(r); /* FFOOO_A_AARRR_R_RRR */
}



 So, I vaguely know what ranges are, and I've heard you can chain
 them together, and my code would be much more readable if I could
 cut up access to the data and splice in changes... but I don't
 even know how to define a range of the right type...

Sounds like you may have some specific code you could use help with. If so, 
don't be afraid to post that code and ask how it can be range-ified.

 So slices are random-access ranges... I understand the
 random-access part... but are they inheriting from Range, do they
 just include a Range?

There's no inheritance going on. Inheritance is a class thing. Arrays/slices 
are not classes.

std.range defines the necessary range operations for slices: empty, front, 
popFront, etc. That's how slices are ranges.

 Why is int[] an array when I declare, but
 variable[] a Range?? Or isn't it a Range?

Every int[] is a dynamic array, a slice, and a range. Doesn't matter where 
that int[] comes from.



Re: Trying to compile weather program

2015-08-23 Thread anonymous via Digitalmars-d-learn
On Sunday 23 August 2015 11:54, Tony wrote:

 weather_report.d(32): Error: undefined identifier centerJustifier

`centerJustifier` is new in 2.068. You're probably using an older version of 
D. You can replace `centerJustifier` with `center` here.


Re: How to use ranges?

2015-08-23 Thread anonymous via Digitalmars-d-learn
On Sunday 23 August 2015 12:17, Doolan wrote:

 And the use of auto everywhere makes it really hard to tell what
 types I should be using for anything. My compiler talks about
 RangeT!(whatever) but you try to use RangeT!(whatever) and you
 find out RangeT is private...

You can use typeof to get the type of a range expression when typing it out 
is impractical/impossible.

 Can someone give me a short summary of how to use ranges?

I'm not sure what exactly you're looking for. The documentation for tee has 
some example code. How about you show something you're having trouble with?

 And how do they relate to slices? That line is really blurry...

Slice is a synonym for what the spec calls a dynamic array, i.e. a 
structure containing a pointer and a length.

Slicing a dynamic array, static array, or pointer produces a dynamic 
array, referencing (not copying) the sliced elements:


int[] d = [1, 2, 3, 4]; /* dynamic array */
int[] slice = d[1 .. 3];
assert(slice == [2, 3]);

d[1] = 20;
assert(slice[0] == 20);

int[4] s = [1, 2, 3, 4]; /* static array */
slice = s[];
assert(slice == [1, 2, 3, 4]);

int* p = [1, 2, 3, 4].ptr; /* pointer */
slice = p[1 .. 3];
assert(slice == [2, 3]);


Note that the source types are different, but slicing them yields the same 
type every time: int[].

Generally, dynamic arrays / slices are random-access ranges. Narrow strings 
(string/wstring/char[]/wchar[]/...) are a notable exception to this. They 
are dynamic arrays of UTF-8/UTF-16 code units. But they're not random-access 
ranges of Unicode code units. Instead, they're _forward_ ranges of Unicode 
code _points_ (dchar). They have special range primitives that to the 
decoding.



Re: Why does not my program is not running?

2015-08-20 Thread anonymous via Digitalmars-d-learn
On Thursday 20 August 2015 22:31, Unknow wrote:

 I'm writed a program for calculating the e number. I can compile
 the source code but when i try run the program, system gives
 'program stopped working' error.
 
 Source code;
 
 // main.d
 
 module main;
 
 import std.file;
 import std.conv;
 
 long factorial(long i){
 if (i == 0){
 return 1;
 }else{
 return(i * factorial(i-1));
 }
 }
 
 void main(string[] args){
 real *e; e = new real; *e = 0; long *integer; integer = new
 long; *integer = 1;
 for(; *integer = 100; *integer++){
 *e = (*e) + (*integer / factorial(*integer));
 }
 if(exists(e) != 0)
 {
 std.file.write(e, to!string(*e));
 }else{
 //...
 }
 delete(e); delete(integer);
 }
 

This has a couple issues.

1) The factorial gets huge quickly. For example, factorial(100) definitely 
won't fit in a long. It'll wrap around and give wrong results.

2) *integer++ doesn't do what you think it does. The increment is done 
before the dereference. You could fix this, but:

3) Don't use pointers like that. You really don't need to new reals and 
longs like that.

4) `*integer / factorial(*integer)` does integer division, which you don't 
want there. You can multiply with `1.0` (a floating point number) to force 
floating point division: `*integer * 1.0 / factorial(*integer)`.

5) I'm not sure what you want the `exists` condition to do. The way it is, 
the file e is only (over)written when it exists already. This may not be 
what you want. Better write it like this:

if(exists(e))
{
/* Do what you want when the file exists. */
}
else
{
/* Do what you want when the file doesn't exist. */
}


6) Don't use delete unless you know exactly what you're doing (which you 
don't yet).

Here's a cleaned up version of your code:

module main;

import std.stdio: writeln;

long factorial(long i){
if (i == 0){
return 1;
}else{
return(i * factorial(i-1));
}
}

void main(string[] args){
real e = 0;
long integer = 1;
for(; integer = 10; integer++){
e = e + integer * 1.0 / factorial(integer);
}
writeln(e); /* 2.71828 */
}


I severely limited the range of integer. I don't know off the top of my head 
how large you can make it without hitting overflow.

I removed the file writing, because I'm not sure if you want to write it 
only when it doesn't exist, or only overwrite when it does exist.


<    1   2   3   4   5   6   >