Re: D vs perl6

2018-11-22 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 19 November 2018 at 06:46:55 UTC, dangbinghoo wrote:
So, can you experts give a more comprehensive compare with 
perl6 and D?


Sure!

1). You can actually read and understand D code.


Re: How do I install a library?

2018-11-09 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 9 November 2018 at 00:18:28 UTC, H. S. Teoh wrote:
It's not true that you're stuck with dub.  And I'm not among 
the people who think dub is the way to go (though it's true 
that that's a minority opinion around here).  Where I have a 
choice, my own D projects do not use dub.


Me neither, I think it's a lot of work for little benefit and 
doesn't seem all that easy to use either. I rather use rdmd using 
-I flags.


Re: Which Docker to use?

2018-10-17 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 17 October 2018 at 03:37:21 UTC, Ky-Anh Huynh wrote:

Hi,

I need to build some static binaries with LDC. I also need to 
execute builds on both platform 32-bit and 64-bit.



From Docker Hub there are two image groups:

* language/ldc (last update 5 months ago)
* dlang2/ldc-ubuntu (updated recently)


Which one do you suggest?

Thanks a lot.


To be honest, you don't need docker for this. You can just 
download LDC in a self-contained folder and use it as is.


https://github.com/ldc-developers/ldc/releases

That's what I do on Linux.


Re: Converting a character to upper case in string

2018-09-21 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 21 September 2018 at 12:15:52 UTC, NX wrote:
How can I properly convert a character, say, first one to upper 
case in a unicode correct manner?
In which code level I should be working on? Grapheme? Or maybe 
code point is sufficient?


There are few phobos functions like asCapitalized() none of 
which are what I want.


Use `asCapitalized` to capitalize the first letter or use 
something like this:



import std.conv;
import std.range;
import std.stdio;
import std.uni;

void main(string[] args)
{
string input = "noe\u0308l";
int index= 2;

auto graphemes= input.byGrapheme.array;
string upperCased = [graphemes[index]].byCodePoint.text.toUpper;

graphemes[index] = upperCased.decodeGrapheme;
string output= graphemes.byCodePoint.text;

writeln(output);
}



Why do some attributes have an @ symbol and others don't?

2018-09-15 Thread Gary Willoughby via Digitalmars-d-learn

Why do some attributes have an @ symbol and others don't?

I thought it might be because some are used as keywords for other 
things but then 'pure' doesn't follow that rule. Any ideas? Is it 
just a legacy thing?


Re: Is there a way to anonymously execute some sh script contents?

2018-08-01 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 1 August 2018 at 14:58:56 UTC, Ky-Anh Huynh wrote:
This works well with user interaction. However I don't really 
like the idea of using temporary files. Is there any better way?


Maybe take a look at:

https://dlang.org/library/std/process/pipe_shell.html


Re: Check whether a range is empty

2018-07-17 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 13 July 2018 at 18:37:35 UTC, vino.B wrote:

Hi All,

  How do i check whether a range is empty. eg. 
(!PFResutl.toRange).empty. I tired the below, but it is no 
printing Empty if the range is empty it just prints blank line.


if (!(!PFResutl.toRange).empty) { writeln("Empty"); }


From,
Vino.B


I thought every range at the lowest level has an `empty` 
property. So, in this case, it would be:


if (PFResutl.toRange.empty)
{
writeln("Empty");
}


Re: Garbage collected pointers?

2018-03-02 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 2 March 2018 at 08:44:53 UTC, Gary Willoughby wrote:
It would be interesting to test whether those methods handle 
these scenarios.


Yeah, it doesn't work.

https://dpaste.dzfl.pl/55116efd0c9c


Re: Garbage collected pointers?

2018-03-02 Thread Gary Willoughby via Digitalmars-d-learn
On Thursday, 1 March 2018 at 12:20:08 UTC, Steven Schveighoffer 
wrote:

On 3/1/18 7:05 AM, Gary Willoughby wrote:

On Thursday, 1 March 2018 at 10:10:27 UTC, John Burton wrote:
My question is how do I tell if a pointer is "garbage 
collected" or not?


You could try `GC.addrOf()` or `GC.query()` in core.memory.


I was going to say this, but then I realized, it's not that the 
pointer points at GC-allocated memory, but that the pointer 
itself is stored in a location that is scanned by the GC. 
That's not as easy to figure out, as you have to look at 
stacks, added ranges, etc.


-Steve


It would be interesting to test whether those methods handle 
these scenarios.




Re: Garbage collected pointers?

2018-03-01 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 1 March 2018 at 10:10:27 UTC, John Burton wrote:
My question is how do I tell if a pointer is "garbage 
collected" or not?


You could try `GC.addrOf()` or `GC.query()` in core.memory.


Re: Does dmd not always compile all of the source code?

2017-12-06 Thread Gary Willoughby via Digitalmars-d-learn
On Wednesday, 6 December 2017 at 16:47:17 UTC, A Guy With a 
Question wrote:

abstract class Test(T)
{
private:
T thing;

public:
this(T theThing)
{
thing = theThing;
thisdoesnotexist(); // expect compiler error right here
}
}

...but this compiles just fine.


It's because it's not being used in your program. How can the 
compiler compile it without knowing what T would be?


When you do this:


class Test2
   : Test!int
{
this(int thing)
{
super(thing);
}
}


You are suppling T and now it is compiled and an error raised.


Re: What does ! mean?

2017-09-27 Thread Gary Willoughby via Digitalmars-d-learn
On Wednesday, 27 September 2017 at 14:23:01 UTC, Ky-Anh Huynh 
wrote:
Can you please explain and give any link where I can learn more 
about these things?


Thanks a lot.


http://nomad.so/2013/07/templates-in-d-explained/


Re: C style 'static' functions

2017-07-19 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 19 July 2017 at 07:22:48 UTC, John Burton wrote:
In C++ I could use static or an anonymous namespace for 
implementation functions, but there doesn't seem to be anything 
similar in D.
Is there any way to achieve what I want in D (Private 
implementation functions)


Try the package keyword: 
https://dlang.org/spec/attribute.html#visibility_attributes


Re: Generic operator overloading for immutable types?

2017-06-13 Thread Gary Willoughby via Digitalmars-d-learn
On Tuesday, 13 June 2017 at 11:36:45 UTC, Steven Schveighoffer 
wrote:


Nope, const works just fine. A clue is in your return type -- 
it's not inout!


This should work:

public Rational opBinary(string op)(Rational rhs) const

If Rational had any indirections, then inout would be required, 
and your signature wouldn't work (because you can't convert an 
inout(SomethingWithPointers) to SomethingWithPointers).


Why do I need to make the member function const, but not the 
parameter? Because the parameter is taken by value, 'this' is a 
reference.


-Steve


Is it possible for the `result` variable in the following code to 
be returned as an immutable type if it's created by adding two 
immutable types?


import std.stdio;

struct Rational
{
public long numerator;
public long denominator;

	public inout Rational opBinary(string op)(inout(Rational) other) 
const

{
static if (op == "+")
{
return inout(Rational)(0, 0);
}
else
{
static assert(0, "Operator '" ~ op ~ "' not 
implemented");
}
}
}

unittest
{
auto baz= immutable(Rational)(1, 3);
auto qux= immutable(Rational)(1, 6);
auto result = baz + qux;

writeln(typeof(result).stringof); // Result is not immutable!
}



Re: Generic operator overloading for immutable types?

2017-06-13 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 12 June 2017 at 20:10:17 UTC, H. S. Teoh wrote:
Therefore, nowadays I always recommend writing parenthesis with 
type modifiers, so that the intent it unambiguous, i.e., always 
write `inout(Rational)` rather than `inout Rational`, unless 
you intend for `inout` to apply to the function rather than the 
return value. (And I apologize for the slip-up in my code 
example above, where I failed to do this for the function 
parameter.)



T


Ok, thanks.


Re: Generic operator overloading for immutable types?

2017-06-12 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 12 June 2017 at 19:36:52 UTC, H. S. Teoh wrote:
On Mon, Jun 12, 2017 at 07:38:44PM +, Gary Willoughby via 
Digitalmars-d-learn wrote:
In the following code is there any way to make the `opBinary` 
method generic to be able to accept immutable as well as a 
standard type? The code currently passes the unit test but I 
wonder if I could get rid of the duplication to overload the 
operator? I'm failing badly.


This is what inout was designed for:

public inout Rational opBinary(string op)(inout Rational rhs)
{
static if (op == "+")
{
return inout(Rational)(0, 0);
}
else
{
static assert(0, "Operator '" ~ op ~ "' not 
implemented");
}
}

That should do the trick.


T


Quick question about the signature, if I change it to (note the 
parens):


   public inout(Rational) opBinary(string op)(inout(Rational) rhs)

It no longer works, why is that?


Re: Generic operator overloading for immutable types?

2017-06-12 Thread Gary Willoughby via Digitalmars-d-learn
I don't know how H. S. Teoh managed to answer 'before' I posted 
but thanks guys! :)


Generic operator overloading for immutable types?

2017-06-12 Thread Gary Willoughby via Digitalmars-d-learn
In the following code is there any way to make the `opBinary` 
method generic to be able to accept immutable as well as a 
standard type? The code currently passes the unit test but I 
wonder if I could get rid of the duplication to overload the 
operator? I'm failing badly.



import std.stdio;

struct Rational
{
public long numerator;
public long denominator;

	public immutable Rational opBinary(string op)(immutable Rational 
rhs)

{
static if (op == "+")
{
return Rational(0, 0);
}
else
{
static assert(0, "Operator '" ~ op ~ "' not 
implemented");
}
}

public Rational opBinary(string op)(Rational rhs)
{
static if (op == "+")
{
return Rational(0, 0);
}
else
{
static assert(0, "Operator '" ~ op ~ "' not 
implemented");
}
}
}

unittest
{
auto foo = Rational(1, 3);
auto bar = Rational(1, 6);
writefln("%s", foo + bar);

auto baz = immutable Rational(1, 3);
auto qux = immutable Rational(1, 6);
writefln("%s", baz + qux);
}



Re: The syntax of sort and templates

2017-05-26 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 26 May 2017 at 09:59:26 UTC, zakk wrote:
1) Why is D making using of the binary ! operator, which as far 
as I understand introduces a template?


The exclamation mark here is not a binary operator, it's used in 
D templates to define where compile-time parameters are.



2) Why is a template needed here?


It's a template so you can use differently typed ranges. Remember 
a range is an interface and very different types can implement it.


3) It seems to me like the argument passed to the template is a 
lambda expression. I only know about templates taking types as 
argument. What's going on?


The function parameter is defined as an alias which is also valid 
at compile-time.


https://dlang.org/phobos/std_algorithm_sorting.html#sort


Re: Why would an initialised struct pointer field be null in the struct's destructor?

2017-05-20 Thread Gary Willoughby via Digitalmars-d-learn

On Saturday, 20 May 2017 at 12:25:39 UTC, Stanislav Blinov wrote:

Oof. Dangerous stuff.


:)

Thanks for the heads up but I think I'm covering all cases in my 
main code.


Re: Why would an initialised struct pointer field be null in the struct's destructor?

2017-05-20 Thread Gary Willoughby via Digitalmars-d-learn

On Saturday, 20 May 2017 at 11:15:57 UTC, Moritz Maxeiner wrote:
Because `element = tmp` destroys `element`, which you allocated 
filled with zeroes.

The destructor will run for each `element`.


Right, I get it because the destructors running on the struct 
that is being replaced. Doh!


Why would an initialised struct pointer field be null in the struct's destructor?

2017-05-20 Thread Gary Willoughby via Digitalmars-d-learn
In the following code, the `_foo` pointer (of the Foo struct) is 
null in the first call to the destructor. Why is this? I think 
it's got something to do with the foreach loop but I'm not sure. 
Any ideas?



import std.stdio;
import core.stdc.stdlib : malloc, calloc, free;

struct Foo
{
public int* _foo;

public this(int n)
{
this._foo  = cast(int*) malloc(int.sizeof);
writefln("ctor: %x", this._foo);
}

public this(this)
{
writefln("post blit: %x", this._foo);
}

public ~this()
{
// Why is this._foo null here???
writefln("dtor: %x", this._foo);
}
}

struct Bar
{
private Foo[] _data;

public this(int n)
{
this._data = (cast(Foo*) calloc(n, Foo.sizeof))[0 .. n];

foreach(ref element; this._data)
{
auto tmp = Foo(1);
element = tmp;
}
}
}

void main(string[] args)
{
auto bar = Bar(1);
}



Re: How to check a struct exists at a particular memory address?

2017-05-18 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 18 May 2017 at 21:09:06 UTC, Igor wrote:

On Thursday, 18 May 2017 at 20:20:47 UTC, Gary Willoughby wrote:

This might be a really silly question but:

I've allocated some memory like this (Foo is a struct):

this._data = cast(Foo*) calloc(n, Foo.sizeof);

How can I then later check that there is a valid Foo at 
`this._data` or `this._data + n`?


Well... I think the right answer is that everything you do with 
memory should be very deterministic so you should just know 
where is what and not have a need to check :).


Agreed. I think I'll re-visit the design.




How to check a struct exists at a particular memory address?

2017-05-18 Thread Gary Willoughby via Digitalmars-d-learn

This might be a really silly question but:

I've allocated some memory like this (Foo is a struct):

this._data = cast(Foo*) calloc(n, Foo.sizeof);

How can I then later check that there is a valid Foo at 
`this._data` or `this._data + n`?


Re: is char[] faster than string?

2017-04-06 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 5 April 2017 at 21:58:16 UTC, Inquie wrote:

What I am looking for is something like StringBuilder in C#.


std.array.appender


Re: Memory Allocation

2017-03-30 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 29 March 2017 at 19:19:48 UTC, Enigma wrote:
I have a memory buffer allocated using different methods. It is 
simply a pointer and a size.


I would like to be able to manage this buffer by treating it as 
a memory pool or heap. I think I can use allocators to do this 
but not sure how.


You can re-task the GC to use an arena if that's suitable:

https://bitbucket.org/infognition/dstuff/src/1dca752af1021ed5998bb041004465674695113f/gcarena.d?fileviewer=file-view-default


Re: how to define my own traits

2017-03-27 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 26 March 2017 at 23:25:49 UTC, XavierAP wrote:
I've looked into Phobos to emulate it when defining my own 
trait template, and when I see this:


module std.range.primitives;
// ...
template isInputRange(R)
{
enum bool isInputRange = is(typeof(
(inout int = 0)
{
R r = R.init; // can define a range object
if (r.empty) {}   // can test for empty
r.popFront;   // can invoke popFront()
auto h = r.front; // can get the front of the range
}));

I wonder, why that unused parameter (inout int = 0)?
In my project () { /* ... */ } works the same for a custom 
trait.


Even Andrei was baffled:

http://forum.dlang.org/thread/nepm2k$311l$1...@digitalmars.com


Re: constraint on variadic template

2016-12-07 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 7 December 2016 at 16:35:52 UTC, Alex wrote:

mixin template S(T...)
{
void run()
{
foreach(s; T)
{
static assert(__traits(hasMember, s, "run"));
}
}
}

How to formulate the check inside the foreach as a template 
constraint with

mixin template S(T...) if(???)


Will some like this work?

import std.range.primitives;

mixin template S(T...) if(__traits(hasMember, 
ElementType!(T), "run"))

{
...
}

https://dlang.org/phobos/std_range_primitives.html#ElementType


What is the simplest way of doing @nogc string concatenation?

2016-11-03 Thread Gary Willoughby via Digitalmars-d-learn

What is the simplest way of doing @nogc string concatenation?


Re: Can someone please explain why the following assertion fails?

2016-11-01 Thread Gary Willoughby via Digitalmars-d-learn
On Tuesday, 1 November 2016 at 14:06:08 UTC, Steven Schveighoffer 
wrote:

On 10/31/16 3:08 PM, Gary Willoughby wrote:

Can someone please explain why the following assertion fails?

import std.stdio;
import std.conv;

void main(string[] args)
{
auto x = 1;

assert(hashOf(x.to!(string)) == hashOf(x.to!(string)));
}

Thanks.


IMO, it shouldn't. A string's "value" has nothing to do with 
it's location.


-Steve


It definitely is surprising. I'll raise an issue and see what 
others think.


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


Re: Can someone please explain why the following assertion fails?

2016-11-01 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 31 October 2016 at 22:10:30 UTC, Ali Çehreli wrote:

On 10/31/2016 12:08 PM, Gary Willoughby wrote:

Can someone please explain why the following assertion fails?

import std.stdio;
import std.conv;

void main(string[] args)
{
auto x = 1;

assert(hashOf(x.to!(string)) == hashOf(x.to!(string)));
}

Thanks.


I think you need TypeInfo.getHash.

  https://dlang.org/phobos/object.html#.TypeInfo.getHash

import std.conv;

auto myHashOf(T)(auto ref T value) {
return typeid(T).getHash();
}

void main() {
auto x = 1;
auto s = "1";
assert(myHashOf(x.to!string) == myHashOf(x.to!string));
assert(myHashOf(s) == myHashOf(s));
assert(myHashOf(s) == myHashOf(x.to!string));
}

Ali


Thanks but `TypeInfo.getHash` is not @nogc. Looks like I'll have 
to roll my own.


Re: Can someone please explain why the following assertion fails?

2016-10-31 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 31 October 2016 at 19:24:13 UTC, Ali Çehreli wrote:

On 10/31/2016 12:08 PM, Gary Willoughby wrote:

[...]


Because it considers the .ptr property of arrays as well:


https://github.com/dlang/druntime/blob/master/src/core/internal/hash.d#L61

[...]


Ah right.

Is there an alternative built-in, generic, nogc hash function 
that would return the same values for Strings?


Re: Can someone please explain why the following assertion fails?

2016-10-31 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 31 October 2016 at 19:08:50 UTC, Gary Willoughby wrote:

Can someone please explain why the following assertion fails?

import std.stdio;
import std.conv;

void main(string[] args)
{
auto x = 1;

assert(hashOf(x.to!(string)) == hashOf(x.to!(string)));
}

Thanks.


DMD64 D Compiler v2.072.0
Copyright (c) 1999-2016 by Digital Mars written by Walter Bright

Ubuntu 16.04


Can someone please explain why the following assertion fails?

2016-10-31 Thread Gary Willoughby via Digitalmars-d-learn

Can someone please explain why the following assertion fails?

import std.stdio;
import std.conv;

void main(string[] args)
{
auto x = 1;

assert(hashOf(x.to!(string)) == hashOf(x.to!(string)));
}

Thanks.


Re: What exactly does the compiler switch -betterC do?

2016-09-26 Thread Gary Willoughby via Digitalmars-d-learn
On Tuesday, 20 September 2016 at 13:23:35 UTC, Jacob Carlborg 
wrote:

On 2016-09-19 23:09, Gary Willoughby wrote:

$ rdmd --build-only --force -betterC -de -O -inline -release 
-w test.d

$ nm test


Indeed. I just noticed now that there's a difference between 
2.070.0 and 2.071.0. I get 4 symbols with 2.070.0 and 2428 with 
2.071.0. I would say it's a bug.


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


Re: What exactly does the compiler switch -betterC do?

2016-09-19 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 20 June 2016 at 06:35:32 UTC, Jacob Carlborg wrote:

On 2016-06-19 21:53, Gary Willoughby wrote:
When compiling, what exactly does the -betterC flag do? The 
command help
says "omit generating some runtime information and helper 
functions" but

what does this really mean? Is there any specifics somewhere?


It is intended to allow you to link an application without 
druntime. A Hello World using "extern(C) main" and printing 
using "printf" contains the following symbols on OS X:


00a8 S _D4main12__ModuleInfoZ
0068 T _D4main15__unittest_failFiZv
0018 T _D4main7__arrayZ
0040 T _D4main8__assertFiZv
00b5 s _TMP1
 U __d_arraybounds
 U __d_assert
 U __d_unittest
 T _main
 U _printf

If compiled with -betterC, it contains these:

 T _main
 U _printf


I get significantly more symbols than that when compiling the 
following program any idea why?


import core.stdc.stdio;

extern(C) void main()
{
printf("Hello World!\n");
}


$ rdmd --build-only --force -betterC -de -O -inline -release -w 
test.d

$ nm test



Re: Metaprogramming with traits

2016-09-16 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 15 September 2016 at 22:05:55 UTC, Ram_B wrote:

test.d(33): Error: variable f cannot be read at compile time
test.d(33): Error: string expected as second argument of 
__traits hasMember instead of __error
test.d(46): Error: template instance test.A.t!(B) error 
instantiating


Maybe Array!(string) can't be use in compile-time code?


Re: Metaprogramming with traits

2016-09-15 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 15 September 2016 at 15:07:09 UTC, Ram_B wrote:
How i can get fields of derived classes in runtime? This not 
works


What about something like this:

import std.traits;
import std.stdio;

class A {
int a,b;
this(){}
void fields(this T)(){
writeln(FieldNameTuple!(T));
foreach(Class; TransitiveBaseTypeTuple!(T)) {
writeln(FieldNameTuple!(Class));
}
}
}

class B : A{
int c;
this(){}
}

class C : B{
int d;
this(){}
}
void main(){
C c = new C();
c.fields();
}


Re: How to add nogc to delegate

2016-08-11 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 11 August 2016 at 05:12:39 UTC, ag0aep6g wrote:

On 08/11/2016 06:15 AM, Engine Machine wrote:

void foo(@nogc void delegate())

doesn't work.


Put it after the parameter list, like so:

void foo(void delegate() @nogc)


You may also need to add the scope keyword too.

Reference:
http://forum.dlang.org/thread/zaxaqgeeenwypmijr...@forum.dlang.org


Re: I need a @nogc version of hashOf(). What are the options?

2016-08-07 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 7 August 2016 at 18:37:19 UTC, ag0aep6g wrote:

On 08/07/2016 07:10 PM, ag0aep6g wrote:

https://github.com/dlang/druntime/pull/1624


Has been merged. Is going to be part of 2.072.


Very cool!

MurmurHash3 is a great addition too. Thanks guys.


I need a @nogc version of hashOf(). What are the options?

2016-08-07 Thread Gary Willoughby via Digitalmars-d-learn
I need a @nogc version of hashOf(). Here's one i'm currently 
using but it's not marked as @nogc.


https://github.com/dlang/druntime/blob/master/src/object.d#L3170

What are the options now?

Is there anything D offers that I could use? I need a function 
that takes a variable of any type and returns a numeric hash.


Re: Endiannes & Splitting Values

2016-07-07 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 7 July 2016 at 10:48:56 UTC, Lodovico Giaretta wrote:

On Thursday, 7 July 2016 at 10:45:12 UTC, Gary Willoughby wrote:
On Thursday, 7 July 2016 at 08:21:53 UTC, Lodovico Giaretta 
wrote:
Are you sure that this works in both big-endian and 
little-endian systems?


It shouldn't matter. You're just interested in the high and 
low 4 byte chunks (which are to be interpreted as an int) 
which will return in the relevant endianess of your machine.


But are the high 4 bytes the first 4 or the second 4? It 
depends on endianness. So your high and low variables may be 
switched, if I understand correctly.


Ah, I see. You could modify it like this:

union Value
{
ulong full;

static struct Bits
{
version (BigEndian)
{
uint high;
uint low;
}
else
{
uint low;
uint high;
}

}

Bits bits;
alias bits this;

this(ulong value)
{
this.full = value;
}
}


Re: Endiannes & Splitting Values

2016-07-07 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 7 July 2016 at 08:21:53 UTC, Lodovico Giaretta wrote:
Are you sure that this works in both big-endian and 
little-endian systems?


It shouldn't matter. You're just interested in the high and low 4 
byte chunks (which are to be interpreted as an int) which will 
return in the relevant endianess of your machine.


Re: Endiannes & Splitting Values

2016-07-07 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 6 July 2016 at 21:44:37 UTC, BitGuy wrote:
I'm trying to implement a feistel cipher that'll give the same 
results regardless of the endianness of the machine it runs on. 
To make the cipher I need to split a 64bit value into two 32bit 
values, mess with them, and then put them back together. I can 
think of a few ways to split a 64bit value with versions or the 
endianness functions in bitmanip but it all seems pretty messy 
for just wanting to split a value... I'm thinking maybe I can 
just cast and bitshift so I can forget about the endianness but 
I'm not really sure about the casting down rules and if that'd 
work?


What about something like:

import std.stdio;

union Value
{
ulong full;

static struct Bits
{
uint high;
uint low;
}

Bits bits;
alias bits this;

this(ulong value)
{
this.full = value;
}
}

void main(string[] args)
{
auto value = Value(77309411348);

writefln("%s, (%b)", value.high, value.high);
writefln("%s, (%b)", value.low, value.low);
writefln("%s, (%b)", value.full, value.full);
}


Re: Is there anyway to make opApply @nogc?

2016-06-22 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 22 June 2016 at 13:36:54 UTC, Marc Schütz wrote:

On Tuesday, 21 June 2016 at 19:21:01 UTC, Gary Willoughby wrote:
Right ok, thanks! It doesn't seem to help though as the 
compiler complains about it being not @nogc.


You probably need to declare the delegate and opApply() itself 
as @nogc, too:


int opApply(scope int delegate(int) @nogc dg) @nogc { }


That fixed it, thanks all for your help. :)


Re: Is there anyway to make opApply @nogc?

2016-06-21 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 21 June 2016 at 12:53:11 UTC, Adam D. Ruppe wrote:

On Tuesday, 21 June 2016 at 12:48:04 UTC, Gary Willoughby wrote:
I have no idea what that means. Can anyone shed more light on 
this, please?


So when you use local variables in a delegate, the compiler 
usually makes a copy of them just in case the delegate gets 
saved for later.


When you mark it scope, you promise that you won't save it for 
later, so the compiler skips making the copy.


Right ok, thanks! It doesn't seem to help though as the compiler 
complains about it being not @nogc.


Re: Is there anyway to make opApply @nogc?

2016-06-21 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 20 June 2016 at 15:27:32 UTC, Adam D. Ruppe wrote:

On Monday, 20 June 2016 at 15:13:53 UTC, Gary Willoughby wrote:
I think the problem is that the delegate which is required by 
opApply is allocated using the GC.


make the delegate in opApply scope

int opApply(scope int delegate(whatever) dg)


I'm still not sure what this achieves. The description on the 
stackoverflow question reads: "And when the compiler sees this on 
delegates, it will avoid allocating a closure when taking the 
address of a local function. This is essential in opApply loops."


I have no idea what that means. Can anyone shed more light on 
this, please?


Re: Is there anyway to make opApply @nogc?

2016-06-20 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 20 June 2016 at 15:47:44 UTC, Gary Willoughby wrote:

On Monday, 20 June 2016 at 15:27:32 UTC, Adam D. Ruppe wrote:

On Monday, 20 June 2016 at 15:13:53 UTC, Gary Willoughby wrote:
I think the problem is that the delegate which is required by 
opApply is allocated using the GC.


make the delegate in opApply scope

int opApply(scope int delegate(whatever) dg)


What effect does this have? and how does it beat the GC?


Found the explanation here:

http://stackoverflow.com/questions/4711309/meaning-of-scope-in-d-for-a-parameter

I give it a go. Thanks.


Re: Is there anyway to make opApply @nogc?

2016-06-20 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 20 June 2016 at 15:27:32 UTC, Adam D. Ruppe wrote:

On Monday, 20 June 2016 at 15:13:53 UTC, Gary Willoughby wrote:
I think the problem is that the delegate which is required by 
opApply is allocated using the GC.


make the delegate in opApply scope

int opApply(scope int delegate(whatever) dg)


What effect does this have? and how does it beat the GC?


Re: Is there anyway to make opApply @nogc?

2016-06-20 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 20 June 2016 at 14:34:33 UTC, Mathias Lang wrote:
Can't `opApply` with `auto` return type works since it infers 
attributes ?


I think the problem is that the delegate which is required by 
opApply is allocated using the GC.


Is there anyway to make opApply @nogc?

2016-06-20 Thread Gary Willoughby via Digitalmars-d-learn
Is there any way to make opApply @nogc? or provide the same 
foreach functionality without implementing a range interface?


I want to iterate over a piece of memory using a pointer. I 
thought about using opSlice but that doesn't provide information 
for an index in a foreach loop.


auto opSlice()
{
return this._pointer[0 .. size];
}

Anyone got any ideas?


What exactly does the compiler switch -betterC do?

2016-06-19 Thread Gary Willoughby via Digitalmars-d-learn
When compiling, what exactly does the -betterC flag do? The 
command help says "omit generating some runtime information and 
helper functions" but what does this really mean? Is there any 
specifics somewhere?


Re: Why do I get this error when casting to an immutable or shared byRef return type?

2016-06-19 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 19 June 2016 at 10:35:59 UTC, Gary Willoughby wrote:

...


A more correct example:

import core.stdc.stdlib;
import std.traits;

ref T foo(T)()
{
alias Type = Unqual!(T);

Type* foo = cast(Type*) malloc(Type.sizeof * 8);

return *foo;
}

void main(string[] args)
{
// Works!
auto bar = foo!(int)();

// Works!
auto bar = foo!(const(int))();

// Error: cast(immutable(int))*foo is not an lvalue
auto bar = foo!(immutable(int))();

// Error: cast(shared(int))*foo is not an lvalue
auto bar = foo!(shared(int))();
}


Why do I get this error when casting to an immutable or shared byRef return type?

2016-06-19 Thread Gary Willoughby via Digitalmars-d-learn
In the following code, the `foo` function doesn't work when 
casting to an immutable or shared type. Can anyone please explain 
what is happening here? Is there any way of returning such 
variables byRef from a malloc'd chunk of memory?


import core.stdc.stdlib;

ref T foo(T)()
{
int* foo = cast(int*) malloc(int.sizeof * 8);

return *foo;
}

void main(string[] args)
{
// Works!
auto bar = foo!(int)();

// Works!
auto bar = foo!(const(int))();

// Error: cast(immutable(int))*foo is not an lvalue
auto bar = foo!(immutable(int))();

// Error: cast(shared(int))*foo is not an lvalue
auto bar = foo!(shared(int))();
}


Is it possible to create a static factory method on a templated struct?

2016-06-18 Thread Gary Willoughby via Digitalmars-d-learn

I've tried the following code and I get the error:

Error: template Foo(A) does not have property 'of'


struct Foo(A)
{
private int _foo;

@disable this();

public this(int foo)
{
this._foo = foo;
}

public static auto of(B)()
{
return Foo!(B)(8);
}
}

void main(string[] args)
{
auto foo = Foo.of!(string);
}


Is it possible to even have static methods on structs like this? 
What am I doing wrong?


Is there a more elegant way of testing T for multiple types?

2016-06-18 Thread Gary Willoughby via Digitalmars-d-learn

Here I'm testing T is either a class or interface:

void foo(T)(T bar) if (is(T == class) || is(T == interface))
{
...
}

Is there a more elegant way of testing T for multiple types? 
Because it doesn't scale well if I need to add more.


I would love to use something like this:

void foo(T)(T bar) if (T in [class, interface])
{
...
}

Is something like this currently possible using type tuples?


Re: Default initialization of structs?

2016-06-17 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 17 June 2016 at 10:53:40 UTC, Lodovico Giaretta wrote:

struct Foo(T)
{
private int _bar = 1;

this(int bar)
{
this._bar = bar;
}
}

auto foo = Foo!(string)();

This should do the trick.


Thanks, I forgot to mention I'm also doing lots of other stuff in 
the constructor to private fields too.


struct Foo(T)
{
private int _bar;
private void* _baz;

this(int bar = 8)
{
this._bar = bar;
this._baz = malloc(this._bar);
}
}

So I have to at least run a constructor.



Default initialization of structs?

2016-06-17 Thread Gary Willoughby via Digitalmars-d-learn
I have a struct where I need to perform default initialization of 
some members but the compiler doesn't allow to define a default 
constructor which allow optional arguments.


struct Foo(T)
{
private int _bar;

this(int bar = 1)
{
this._bar = bar;
}
}

auto foo = Foo!(string) // error

Are there any patterns or idioms I could use to get the desired 
result? Or is it just the case if I use a constructor I have to 
pass values to it?


Re: Creating a reference counted type?

2016-06-12 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 12 June 2016 at 15:05:53 UTC, ketmar wrote:
this is basically how refcounted structs are done. note that i 
just typed the code into reply box, so it may not compile or 
contain some small bugs, but i think you got the idea.


Thanks for the replies guys.


Re: Creating a reference counted type?

2016-06-12 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 12 June 2016 at 14:45:12 UTC, ketmar wrote:
ahem... wut?! we have one copy of our struct freed half the 
way, and another copy has refcount of 2, so it won't be freed 
at all. it doesn't so innocent as it looks: we may try to use 
`f` in `main`... just to find out that resources was 
mysteriously freed, and refcount is total garbage.


Hmmm. I thought it looked *too* simple. Have you any idea if 
there is a simple solution to this?


Re: Creating a reference counted type?

2016-06-12 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 12 June 2016 at 14:29:19 UTC, Gary Willoughby wrote:
Another thing that is puzzling me is that when creating an 
instance of the above struct and passing as an argument to a 
function, the copy constructor is called and the reference 
count is incremented. This is expected. However, when the 
function returns, the destructor is called (on the copy) and 
the reference count lowered. How does the original instance 
know of the updated reference count from the copy?


Actually, this doesn't puzzle me at all! I think I must be tired. 
Ignore this paragraph, it doesn't make sense. lol.


Creating a reference counted type?

2016-06-12 Thread Gary Willoughby via Digitalmars-d-learn
I'm wondering if it's this easy to create a reference counted 
type:


struct Foo
{
int _refCount = 1;

this(...)
{
// allocate resources, etc.
}

this(this)
{
this._refCount++;
}

~this()
{
this._refCount--;

if (this._refCount == 0)
{
// free resources.
}
}
}

Are there any other considerations I need to handle?

Another thing that is puzzling me is that when creating an 
instance of the above struct and passing as an argument to a 
function, the copy constructor is called and the reference count 
is incremented. This is expected. However, when the function 
returns, the destructor is called (on the copy) and the reference 
count lowered. How does the original instance know of the updated 
reference count from the copy?


Re: D, GTK, Qt, wx,…

2016-06-04 Thread Gary Willoughby via Digitalmars-d-learn

On Saturday, 4 June 2016 at 08:27:53 UTC, Russel Winder wrote:
On Sun, 2016-05-29 at 14:01 +0200, Jordi Sayol via 
Digitalmars-d-learn wrote:



[…]

https://github.com/nomad-software/tkd



I am not a great fan of tk even in Python. It is true that Tk 
is everywhere and so meets the portability requirement, but I 
would still go with Qt (well QML anyway) in preference.


I'm the author of Tkd and I would always try and choose another 
framework before Tkd. ;) Simply because others give you much more 
control over your UI. That said, Tkd is invaluable for quick and 
dirty GUI apps or prototypes. Choose the right tool for the job, 
etc.


Re: Is there any overhead iterating over a pointer using a slice?

2016-06-01 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 31 May 2016 at 20:52:20 UTC, Johan Engelen wrote:

On Tuesday, 31 May 2016 at 18:55:18 UTC, Gary Willoughby wrote:


If I have a pointer and iterate over it using a slice, like 
this:


T* foo = 

foreach (element; foo[0 .. length])
{
...
}

Is there any overhead compared with pointer arithmetic in a 
for loop?


Use the assembly output of your compiler to check! :-)  It's 
fun to look at.

For example, with GDC:
http://goo.gl/Ur9Srv

No difference.

cheers,
  Johan


That's pretty nice.


Is there any overhead iterating over a pointer using a slice?

2016-05-31 Thread Gary Willoughby via Digitalmars-d-learn

In relation to this thread:

http://forum.dlang.org/thread/ddckhvcxlyuvuiyaz...@forum.dlang.org

Where I asked about slicing a pointer, I have another question:

If I have a pointer and iterate over it using a slice, like this:

T* foo = 

foreach (element; foo[0 .. length])
{
...
}

Is there any overhead compared with pointer arithmetic in a for 
loop?


Re: How to hash any type to an integer?

2016-05-30 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 29 May 2016 at 16:26:58 UTC, Seb wrote:

On Sunday, 29 May 2016 at 11:05:21 UTC, Gary Willoughby wrote:
I'm currently implementing a hash map as an exercise and 
wondered if there is a built-in function I could use to hash 
keys effectively? What I'm looking for is a function that 
hashes any variable (of any type) to an integer.


I've been looking at the `getHash` function of the `TypeInfo` 
class but that only seems to return the passed pointer. Any 
ideas?


How about hashOf?
https://dlang.org/phobos/object.html#.hashOf


Awesome, thanks. Can't believe I missed that.


How to hash any type to an integer?

2016-05-29 Thread Gary Willoughby via Digitalmars-d-learn
I'm currently implementing a hash map as an exercise and wondered 
if there is a built-in function I could use to hash keys 
effectively? What I'm looking for is a function that hashes any 
variable (of any type) to an integer.


I've been looking at the `getHash` function of the `TypeInfo` 
class but that only seems to return the passed pointer. Any ideas?


Re: Is there a way to clear an OutBuffer?

2016-05-25 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 23 May 2016 at 03:03:12 UTC, Jon Degenhardt wrote:

Currently not possible. Enhancement request perhaps?

Looking at the implementation, setting its 'offset' member 
seems to work. Based on example from documentation:


import std.outbuffer;

void main() {
OutBuffer b = new OutBuffer();
b.writefln("a%sb", 16);
assert(b.toString() == "a16b\n");

b.offset = 0;
b.writefln("a%sb", 16);
assert(b.toString() == "a16b\n");
}

Bug report perhaps? :)

Ali


Thanks. Enhancement request: 
https://issues.dlang.org/show_bug.cgi?id=16062


Is there a consensus on this? Does this really need a clear 
method seeing as though you can reset the offset directly?


Re: Is there an easy way to convert a pointer to malloc'd memory to an array?

2016-05-24 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 24 May 2016 at 18:43:22 UTC, Adam D. Ruppe wrote:

On Tuesday, 24 May 2016 at 18:42:41 UTC, Gary Willoughby wrote:
I have a T* pointer to the start of a malloc'd chunk of 
memory, the type T and the number of T's stored in the chunk.


Is there an efficient way of converting this information to a 
D array of type T[] or even T[n]?


Slice it:

T[] = t[0 .. n];


That! ...is amazing!


Is there an easy way to convert a pointer to malloc'd memory to an array?

2016-05-24 Thread Gary Willoughby via Digitalmars-d-learn
I have a T* pointer to the start of a malloc'd chunk of memory, 
the type T and the number of T's stored in the chunk.


Is there an efficient way of converting this information to a D 
array of type T[] or even T[n]?


Re: D equivalent of C++ bind ?

2016-05-10 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 10 May 2016 at 09:39:53 UTC, chmike wrote:

Is there an equivalent in D of the C++11 std.bind template class


See http://dlang.org/phobos/std_functional.html#partial


Re: Accepting function or delegate as function argument

2016-05-06 Thread Gary Willoughby via Digitalmars-d-learn

On Wednesday, 4 May 2016 at 15:23:20 UTC, Rene Zwanenburg wrote:

On Wednesday, 4 May 2016 at 14:54:39 UTC, chmike wrote:
Two constructors, one accepting a function and the other one 
accepting a delegate would do the job for the API. Is there a 
simple method to convert a function pointer into a delegate 
pointer that is also efficient ?


http://dlang.org/phobos/std_functional.html#.toDelegate

You can also make your constructor a template, constrain it on 
isCallable if you wish, and then use toDelegate. If the 
argument is already a delegate toDelegate will avoid doing 
extra work.


import std.functional;
import std.stdio;
import std.traits;

class Foo(K,T)
{
private T delegate(K) m_factory;

public this(T)(T factory) if (isCallable!(T))
{
this.m_factory = toDelegate(factory);
}

public T bar(K key)
{
return this.m_factory(key);
}
}

string dummyFactory(string key)
{
return "Hello " ~ key;
}

void main()
{
auto foo = new Foo!(string, string)();

writeln(foo.bar("world"));
}


Re: D GUI Toolkit Comparison

2016-04-29 Thread Gary Willoughby via Digitalmars-d-learn

On Friday, 29 April 2016 at 13:52:59 UTC, Nordlöw wrote:
Could somebody briefly outline the different GUI toolkits 
available in D and how they differ especially in terms of 
cleverly the make use of all idioms available in the language 
aswell as in Phobos.


For instance: DlangUI and Adams D Ruppe's `simpledisplay`


https://wiki.dlang.org/GUI_Libraries

I'm the author of Tkd[1] and wrote it to learn D in more depth 
and really enjoyed the flexibility of generic 
classes/functions/interfaces and mixins. Because Tkd is based on 
Tcl/Tk it was really hard to map the Tcl language and Tk toolkit 
to a sensible type hierarchy using inheritance. Using D gave me 
the opportunity to think a bit differently and compose types more 
simply while modeling the problem in a more intelligent way. I'm 
bias, but I love the simplicity of the finished code.


A pattern I used throughout was this:

class Foo : Bar
{
public auto baz(this T)(...)
{
...
return cast(T) this;
}
}

Which allows chaining of methods with those of parent and child 
types, i.e:



import tkd.tkdapplication;

class Application : TkdApplication
{
private void exitCommand(CommandArgs args)
{
this.exit();
}

override protected void initInterface()
{
auto frame = new Frame(2, ReliefStyle.groove)
.pack(10);

auto label = new Label(frame, "Hello World!")
.pack(10);

auto exitButton = new Button(frame, "Exit")
.setCommand()
.pack(10);
}
}

void main(string[] args)
{
auto app = new Application();
app.run();
}


[1]: https://github.com/nomad-software/tkd


Re: Three Cool Things about D?

2016-03-02 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 1 March 2016 at 20:26:36 UTC, Ali Çehreli wrote:

On 03/01/2016 12:17 PM, Wulfrick wrote:

On Tuesday, 1 March 2016 at 20:15:00 UTC, Wulfrick wrote:
It looks like the link in wiki.dlang.org/Videos to Andrei's 
"Three

Cool Things about D" is dead.

Do you know of another link?


Maybe this?

https://www.youtube.com/watch?v=3NihZVcZqto


Yes, that should be it. Although, I think he made small 
improvements to the presentation over time.


Ali


Here's one from 2010:

https://www.youtube.com/watch?v=RlVpPstLPEc=PLummIahGJZ1T5wOzRKO32pm7z0Th9_YYe=3


Re: Printing a C "string" with write(f)ln

2016-02-09 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 9 February 2016 at 12:50:27 UTC, Jakob Ovrum wrote:
writefln et al sensibly does *not* assume that a pointer to 
char is a C string, for memory safety purposes.


Print the result of std.string.fromStringz[1] instead:

writeln(fromStringz(pString));
writefln("%s", fromStringz(pString));

[1] http://dlang.org/phobos/std_string#fromStringz


Or use `to` like this:

import std.conv;
writefln("%s", pString.to!(string));


Re: Printing a C "string" with write(f)ln

2016-02-09 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 9 February 2016 at 16:58:03 UTC, Daniel Kozak wrote:

Or use `to` like this:

import std.conv;
writefln("%s", pString.to!(string));


this will allocate new string which can be performance problem.


Which is good in most cases. It's better to have the GC take care 
of the D string instead of worrying about the lifetime of pString.


Re: Printing a C "string" with write(f)ln

2016-02-09 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 9 February 2016 at 17:02:28 UTC, Jakob Ovrum wrote:
to!string behaving like that was a poor design choice[1]. 
Please use fromStringz.


[1] https://github.com/D-Programming-Language/phobos/pull/1607


It's not a poor design choice. It ensures the string is handled 
by the D GC instead of the C side freeing it. `fromStringz` and 
`to!(String)` are for different cases.


Re: How do you check if object o has base type B?

2016-02-04 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 4 February 2016 at 05:51:22 UTC, Enjoys Math wrote:

Consider:

class C {

}

class B : C {

}

class A : B {

}

class D : C {

}

C[] objList;

how do we test if objLis[k] is of base type "B"?

Ie for [new A(), new B(), new D(), new C()] would give output 
[true, true, false, false].


?

Thank you! :D


if (cast(B)objLis[k])
{
// It's an instance.
}


Re: Call D from TCL

2016-02-03 Thread Gary Willoughby via Digitalmars-d-learn
On Wednesday, 3 February 2016 at 12:20:42 UTC, Vasileios 
Anagnostopoulos wrote:
Is there any example,framework or tutorial on how to call D 
from Tcl (write new commands in D for Tcl)?


I am on Windows 10 x86_64.

thank you.


I've created a wrapper around Tcl/Tk to create GUI's here:

https://github.com/nomad-software/tkd

It uses the library found here:

https://github.com/nomad-software/tcltk

In the project, I've created a simple interpreter which handles 
communicating to Tcl here:


https://github.com/nomad-software/tkd/blob/master/source/tkd/interpreter/tcl.d

There is a method on that class for creating commands for use in 
Tcl.


Re: Call D from TCL

2016-02-03 Thread Gary Willoughby via Digitalmars-d-learn
On Wednesday, 3 February 2016 at 14:19:32 UTC, Vasileios 
Anagnostopoulos wrote:

Thank you very much. I investigate

Tcl_CmdProc

more closely.

On Wed, Feb 3, 2016 at 3:50 PM, Gary Willoughby via 
Digitalmars-d-learn < digitalmars-d-learn@puremagic.com> wrote:


On Wednesday, 3 February 2016 at 12:20:42 UTC, Vasileios 
Anagnostopoulos wrote:



[...]


I've created a wrapper around Tcl/Tk to create GUI's here:

https://github.com/nomad-software/tkd

It uses the library found here:

https://github.com/nomad-software/tcltk

In the project, I've created a simple interpreter which 
handles communicating to Tcl here:



https://github.com/nomad-software/tkd/blob/master/source/tkd/interpreter/tcl.d

There is a method on that class for creating commands for use 
in Tcl.


Here's the reference to the C interface:

https://www.tcl.tk/man/tcl/TclLib/contents.htm


Re: What is the best declaration type for a string like parameter?

2016-01-28 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 28 January 2016 at 15:10:38 UTC, Adam D. Ruppe wrote:

On Thursday, 28 January 2016 at 13:36:46 UTC, Puming wrote:
I searched the forum and found that people use `const(char)[]` 
or `in char[]` to accept both string and char[] arguments.


There's also the hyper-generic signatures Phobos uses like

void foo(S)(S s) if(isSomeString!S)


Yep, this is your answer.

void foo(S)(S s) if(isSomeString!S)
{
//use s
}

Call normally as it can implicitly determine the type of S:

foo("bar");


Re: How can i track the GC when it's runing?

2016-01-25 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 25 January 2016 at 09:33:15 UTC, Dsby wrote:

I want to know How can i track the GC when it's runing?
And Which algorithm is  D's GC used,only Scan-Mark?


There is a good resource here:

https://dlang.org/spec/garbage.html

It details compiler flags to use to profile and log the GC usage.


Re: [Dlang] Delegate Syntax Question

2016-01-10 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 10 January 2016 at 14:32:02 UTC, Jack wrote:

...


Just to make your code a little more clear, try using aliases 
when defining delegate parameters. Like this:


alias Action = void delegate();

Then in your code you use the alias, like this:

class Bar()
{
private Action _action;

void setAction(Action d)
{
this._action = d;
}
}

IMHO it makes everything more readable and you only have one 
definition of the delegate signature.


Re: GC greediness

2016-01-05 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 5 January 2016 at 17:20:07 UTC, Justin Whear wrote:

On Tue, 05 Jan 2016 16:07:36 +, Jack Applegame wrote:

On a server with 4GB of RAM our D application consumes about 
1GB.
Today we have increased server memory to 6 Gb and the same 
application

under the same conditions began to consume about 3Gb of memory.
Does GC greediness depend on available RAM?


My understanding is that the GC won't return collected memory 
to the OS unless a threshold relative the system total is 
crossed.  You can use GC.minimize() from core.memory to 
decrease this.  This could result in degraded performance.


Also see: https://dlang.org/spec/garbage.html


Re: A few range questions

2016-01-05 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 5 January 2016 at 18:47:30 UTC, Charles Smith wrote:
1. `arr[].sort` is changing arr in place. Any way to not do 
that?


Use this instead:

auto result = sort(arr[].dup);

.dup duplicates the array and sort(...) uses the std.algorithm 
sort and not the built-in array sort method.


2. I noticed that result within `countingSort` is an array of 
arrays. I thought `chain` would concat them... did I miss 
something obvious?


No idea yet.



Re: Call C function - Access violation

2016-01-03 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 3 January 2016 at 19:24:46 UTC, TheDGuy wrote:
On Sunday, 3 January 2016 at 13:25:04 UTC, Gary Willoughby 
wrote:
On Sunday, 3 January 2016 at 13:23:25 UTC, Gary Willoughby 
wrote:
I think I've noticed one problem with the code above. You are 
using `text.ptr`. You shouldn't do that because you are 
passing a pointer not an array. Just use `text`.


Forget this line, my mistake. Use `toStringz` and pass a 
pointer instead of an array.


Hi and thanks for your answer. My code looks now like this:

void main(string[] args){
const(char)* val = "Hello World".std.string.toStringz;
char* result = write(val);
const(char)[] s = cstr2dstr(result);
writeln(s);
readln(); //keep the window open
}

But now i get the error: "function expected before(), not 
package std of type void" (refering to line 2).


And if i define the variable 'value' as 'const(char)*' i also 
have to rewrite my C-function to accept const(char)*...


Use an import.

import std.string;
import std.conv;

void main(string[] args) {
auto value  = toStringz("Hello World");
auto result = write(value);
auto s  = to!(string)(result);
writeln(s);
}

Also all string literals in D are zero terminated so you could 
write the call like this:


auto result = write("Hello World");




Re: Call C function - Access violation

2016-01-03 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 3 January 2016 at 12:30:34 UTC, TheDGuy wrote:

I get an access violation with this code:

...


There are a few things you can do to improve your code to make it 
easier to debug.


1. When converting a D string to a char pointer for use with C, 
use `std.string.toStringz`:


http://dlang.org/phobos/std_string.html#.toStringz

2. When converting a char pointer to a D string use 
`std.conv.to!(string)`:


http://dlang.org/phobos/std_conv.html#.to

3. Define C-style char pointers in D as `const(char)*`.
4. Don't use the variable name `text` as it conflicts with 
`std.conv.text`.



I think I've noticed one problem with the code above. You are 
using `text.ptr`. You shouldn't do that because you are passing a 
pointer not an array. Just use `text`.


Re: Call C function - Access violation

2016-01-03 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 3 January 2016 at 13:23:25 UTC, Gary Willoughby wrote:
I think I've noticed one problem with the code above. You are 
using `text.ptr`. You shouldn't do that because you are passing 
a pointer not an array. Just use `text`.


Forget this line, my mistake. Use `toStringz` and pass a pointer 
instead of an array.


Re: Is it possible to elegantly create a range over a binary heap?

2015-12-28 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 27 December 2015 at 22:42:21 UTC, Ivan Kazmenko wrote:
If you implement a struct with range primitives over it, you 
can use it as a range.


See the second code example in std.container.binaryheap's docs 
at

http://dlang.org/phobos/std_container_binaryheap.html#.BinaryHeap.

Or do you mean you want to print variables in order without 
modifying the array?  Sounds like this would require at least N 
log N time and N additional memory for an N-element heap anyway 
(or quadratic time and constant memory).  So, you can just copy 
the array and exhaust the copied binary heap, getting the same 
asymptotic complexity: N log N time and N additional memory.


Ivan Kazmenko.


Thanks. I wanted to iterate through the range without modifying 
the original array but like you said the only way to do that is 
by copying the data which is not ideal.


std.container.binaryheap looks like it implements the range 
interface and consumes the original during iteration. I'll 
probably do that too.


Re: Is it possible to elegantly create a range over a binary heap?

2015-12-28 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 28 December 2015 at 14:05:42 UTC, Ivan Kazmenko wrote:
1. You can find maximum, then second maximum, then third 
maximum and so on - each in constant memory and linear time.  
So, if performance is somehow not an issue, there is a way to 
do it @nogc but in N^2 operations.


That's perhaps too much of a performance hit.

2. If you output the whole array anyway, you may sort the array 
in place.  A sorted array obeys the heap property, so 
subsequent heap operations will still work.


That's actually a good idea. Sort it first, and it should still 
be balanced and correct. Then iteration is easy!


3. The tricky part is when we want to support parallel 
iteration over the same heap.  If we look closely at one 
iteration of heapsort algorithm, it will perhaps become clear 
how to output values so that the array is a heap between any 
two consecutive output operations.  At the very least, our heap 
struct over the array can just track which part of the array is 
already sorted, and work with it separately.


4. Reading and modifying the heap in parallel at the same time 
does not look possible anyway, so this is as far as we can get.


I'll have to test parallel iteration.




Is it possible to elegantly create a range over a binary heap?

2015-12-27 Thread Gary Willoughby via Digitalmars-d-learn
I have a binary tree storing ints implemented using an array. The 
internal state looks like this:


8,7,6,4,1,3,5,2

When extracting this data, it is returned as 8,7,6,5,4,3,2,1.

Is it possible to elegantly add a range on top of the internal 
state to return the correct value order I would expect when 
extracting? Is there an algorithm documented somewhere for doing 
this?


Is this an rvalue reference problem?

2015-12-27 Thread Gary Willoughby via Digitalmars-d-learn

See the following code:

import std.stdio;

void foo(ref int x)
{
writefln("%s", x);
}

void main(string[] args)
{
int y = 0;
foo(y++);
}

When compiled it produces this error:

test.d(11): Error: function test.foo (ref int x) is not callable 
using argument types (int)


If I remove the post-increment of the y variable if works. Is 
this an rvalue reference issue? Would you expect this to work? 
Should the error message be a little more helpful?


Re: Is it possible to elegantly create a range over a binary heap?

2015-12-27 Thread Gary Willoughby via Digitalmars-d-learn
On Sunday, 27 December 2015 at 17:23:35 UTC, Gary Willoughby 
wrote:
I have a binary tree storing ints implemented using an array. 
The internal state looks like this:


8,7,6,4,1,3,5,2

When extracting this data, it is returned as 8,7,6,5,4,3,2,1.

Is it possible to elegantly add a range on top of the internal 
state to return the correct value order I would expect when 
extracting? Is there an algorithm documented somewhere for 
doing this?


Some explanatory reference:

https://en.wikipedia.org/wiki/Binary_tree#Arrays


Re: Is this an rvalue reference problem?

2015-12-27 Thread Gary Willoughby via Digitalmars-d-learn

On Sunday, 27 December 2015 at 18:54:25 UTC, Adam D. Ruppe wrote:
On Sunday, 27 December 2015 at 16:05:39 UTC, Gary Willoughby 
wrote:

[...]


Yes, but more than that, what, exactly, would you expect from 
that? The order of operations with the postfix ++ operator and 
ref would probably lead to confusing results anyway, so better 
to disallow it and force you to be a bit more clear with the 
code.


[...]


Thanks guys, I thought as much.


Re: TreeViews in tkd

2015-12-17 Thread Gary Willoughby via Digitalmars-d-learn

On Thursday, 17 December 2015 at 09:47:42 UTC, TheGag96 wrote:
I've been trying to get into tkd to make some GUI apps, since 
it looked like the simplest/intuitive library out there so far. 
I've been attempting to use their TreeViews to make 
interactable lists of things, but it almost looks like there's 
some missing functionality.


I made an issue on GitHub but I'm not sure I'll get anything 
back, it's been 9 months since the last commit.


Has anyone worked with this before and could give me some tips? 
Thanks!


Calm down, lol. There have been no commits for 9 months because 
as far as i'm aware it's finished and stable. I got your issue 
this morning and will take a look tonight after work.


Re: How to use readText to read utf16 file?

2015-11-17 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 17 November 2015 at 02:40:14 UTC, Domain wrote:

How to use readText to read utf16 file? Or other encoding file.


Here's a helpful resource when working with text files in D.

http://nomad.so/2015/09/working-with-files-in-the-d-programming-language/


Re: @property

2015-11-10 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 9 November 2015 at 22:42:16 UTC, Fyodor Ustinov wrote:
If this feature will be removed, it will be very lacking code, 
like:


writeln = "Hello, world!";

:)
WBR,
Fyodor.


The feature is not being removed. Only the @property attribute 
and compiler check is being removed.


Re: When a variable is passed into a function, is its name kept somewhere for the function to acceess

2015-11-10 Thread Gary Willoughby via Digitalmars-d-learn

On Tuesday, 10 November 2015 at 14:14:33 UTC, DlangLearner wrote:

Please enlighten me if this can be done, thanks.


If i understand you, you could use a templated function:

import std.stdio;

void foo(alias a)()
{
writefln("%s was passed in.", a.stringof);
}

void main(string[] args)
{
auto bar = "bar";
foo!(bar);
}


Re: Associative array with duplicated keys?

2015-11-05 Thread Gary Willoughby via Digitalmars-d-learn
On Thursday, 5 November 2015 at 10:04:02 UTC, Andrea Fontana 
wrote:

Anyway: are duplicated keys on declaration allowed?


IMHO This should at least be a warning.


Re: Capturing __FILE__ and __LINE in a variadic templated function

2015-11-02 Thread Gary Willoughby via Digitalmars-d-learn

On Monday, 2 November 2015 at 08:23:16 UTC, Nordlöw wrote:

I need `T` to be an alias in order for .stringof to work.


typeof(T).stringof


  1   2   3   4   5   6   >