Re: Treat memory as a file with a name.

2014-02-21 Thread Vladimir Panteleev

On Saturday, 22 February 2014 at 07:26:26 UTC, Steve Teale wrote:

This is probably not exactly a D question.

The library librsvg expects to get an SVG file filename. I have 
the data of such a file in memory.


If it's the same librsvg as below, then it looks like it has an 
API function which can also load a SVG from memory:


https://developer.gnome.org/rsvg/2.40/RsvgHandle.html#rsvg-handle-new-from-data

To answer your original question, I think the best way to do this 
is to create a pipe on the filesystem. Once created, you can feed 
data through it without touching the disk.


Treat memory as a file with a name.

2014-02-21 Thread Steve Teale

This is probably not exactly a D question.

The library librsvg expects to get an SVG file filename. I have 
the data of such a file in memory.


How do I dress up that memory as a file with a name so that I can 
pass the name to the librsvg open function.


I've looked at std.mmfile, and played with it, giving a name to 
the constructor, along with the address and size of my memory 
block.


import std.mmfile;
import std.stdio;
import std.stream;

void main()
{
   char[] ca;
   ca.length = 10;
   ca[] = 'X';
   MmFile mmf = new MmFile("glob", 0, 10UL, ca.ptr);
   std.stream.File sf = new std.stream.File("glob", FileMode.In);
   char[] b;
   b.length = 20;
   sf.readExact(b.ptr, 20);
   writefln("%s", b);
}

But then I just get 'No such file or directory', which is what 
I'd expect after I'd taken the trouble to read mmfile.d.


I had expected it to create a stub entry in the file system or 
something, and the somehow use fmemopen(), but it just looks for 
an existing file.


At the moment I'm having to write the data to a temporary file, 
and then pass the name of the temp to rsvg.


There must be some elegant way to do this!


Re: Cannot implicitly convert derived type

2014-02-21 Thread Eric Suen
Generic?

"Frustrated"  ...
> interface iGui
> {
> @property iButton button(ref iButton button);
> }
>
> class WindowsGui : iGui
> {
> WindowsButton _button;
>
> @property WindowsButton button(ref WindowsButton button)
> //@property iButton button(ref iButton button)
> {
> _button = button;
> return button;
> }
> }
>
> interface iButton { }
> class WindowsButton : iButton { }
>
>
> Should this not work?
>
> Error: class main.WindowsGui interface function 'iButton
> button(ref iButton
> button) @property' is not implemented
> Or by using the commented line:
>
> Error: cannot implicitly convert expression (button) of type
> main.iButton to main.WindowsButton
>
> 1. In the first case I override a property using a more derived
> type. This should work but doesn't. Seems D doens't support
> covariance properly?
>
> 2. In the second case, I can cast to make everything work. This
> seems wrong. Hence goto 1. WindowsGui is designed to only work
> with WindowsButton, say, and I should never have to use iButton
> in the WindowsGui class unless, maybe, I want to support
> non-windows buttons in the WindowsGui for some reason.
>
> Basically, because of the covariance issue I end up having to use
> a lot of casts. Hopefully theres some simple trick that won't
> pollute the code to make this work. I guess I could use a
> templated property with a generic type that is derivable from
> iButton to make it work?
>
> In some sense I can understand the error. If I'm using iGui then
> I have the option to use any button(since it is generic) but if
> iGui is a WindowsGui I'm not allowing this. The issue is, that I
> will have some type of dependency restrictions on the types.
>
> e.g.,
>
> iGui g = new WindowsGui;
>
> g.button = new LinuxButton; // ok but not ok!! (should result in
> an error in some way)
>
> Obviously I can cast and check the type and do all that. Just
> feels like the wrong way to go about it because it requires a lot
> of casting and polluting the code with checks that in general,
> should be unnecessary. Again: In the WindowsGui I want to use
> WindowsButton, not iButton because WindowsGui will never need any
> other type of button. iButton is too general to use in WindowsGui.
>
> (it would be cool if one could do something like
>
> class WindowsGui : iGui
> iButton <= WindowsButton // constrains iButton to always be a
> WindowsButton. Checks/casts are automatically added by compiler
> when necessary
> {
> // use WindowsButton here with proper covariance relations and
> checks/casts
> }
>
> Anyways, hopefully there is some single trick to get what I'm
> asking? 




Re: Container templates

2014-02-21 Thread Meta

On Thursday, 20 February 2014 at 18:55:06 UTC, Frustrated wrote:

This should work. Just have to add the overrides and call the
base function(e.g., "override" insert and then call x's insert).

This at least gets the job done... I wonder if there is a better
way?


If you want a.Add() (insert() in the case of std.container.Array) 
to work correctly and be overloaded for both ints and floats, I 
don't think you have any choice beside implementing it yourself. 
This is exactly the kind of problem that multiple alias this 
could solve, but that's not implemented, so I guess you're out of 
luck. Like you said earlier, however, you can just create a 
template mixin that mixes in the Array functionality for any type 
you want, which is about as succint as you're going to get.


Re: Cannot implicitly convert derived type

2014-02-21 Thread Steven Schveighoffer

On Fri, 21 Feb 2014 17:54:06 -0500, Frustrated  wrote:


interface iGui
{
@property iButton button(ref iButton button);
}

class WindowsGui : iGui
{
WindowsButton _button;

@property WindowsButton button(ref WindowsButton button)
//@property iButton button(ref iButton button)
{
_button = button;
return button;
}
}

interface iButton { }
class WindowsButton : iButton { }


Should this not work?


What you are trying to do is not legal.

e.g.:

class RogueButton : iButton { }

iGui gui = new WindowsGui;
gui.button = new RogueButton;

Note that setting gui.button to any iButton is legal, but the derived type  
REQUIRES a WindowsButton. This would have to be rejected at runtime,  
because the compile-time type is implicitly convertible.


There are two types of variance that are logical, contravariance and  
covariance. covariance allows you to *return* a more derived type than the  
base. In other words, this would be legal (assume same  
iButton/WindowsButton structure):


interface iGui
{
@property iButton button();
}

class WindowsGui : iGui
{
@property WindowsButton button() {...};
}

This works, because whenever you return a WindowsButton, you ALSO are  
returning an iButton. In fact, D supports this.


The opposite is contravariance, and that's used on *input* parameters. In  
this case, the derived method can accept a base of the parameter that the  
base class defines:


interface iGui
{
   void button(WindowsButton); // please humor me, I know you don't want  
to do this :)

}

class WindowsGui : iGui
{
   void button(iButton);
}

This is logically sound, because the actual implementation only requires  
an iButton. Therefore, passing a WindowsButton into the iGui interface  
still satisfies that requirement.


However, D does NOT support contravariance.


2. In the second case, I can cast to make everything work. This
seems wrong. Hence goto 1. WindowsGui is designed to only work
with WindowsButton, say, and I should never have to use iButton
in the WindowsGui class unless, maybe, I want to support
non-windows buttons in the WindowsGui for some reason.


This is actually the correct mechanism if you want to use polymorphism.  
However, in some cases, a templated system may be more advantageous than  
an interface system.


One other possibility is to use overloading -- i.e.:

class WindowsGui
{
   @property WindowsButton button(WindowsButton b) { return _button = b;}

   @property WindowsButton button(iButton b)
   {
   if(auto wb = cast(WindowsButton)b)
   button = wb;
   else
   throw new ButtonException;
   }
}

This is not really an attractive solution, but it could be easily  
generated as a mixed-in solution.


-Steve


Re: signatures

2014-02-21 Thread voyager

thanks. works nice



Re: Cannot implicitly convert derived type

2014-02-21 Thread Frustrated

On Friday, 21 February 2014 at 23:19:19 UTC, Ali Çehreli wrote:

On 02/21/2014 02:54 PM, Frustrated wrote:

interface iGui
{
@property iButton button(ref iButton button);
}

class WindowsGui : iGui
{
WindowsButton _button;

@property WindowsButton button(ref WindowsButton button)
//@property iButton button(ref iButton button)
{
_button = button;
return button;
}
}

interface iButton { }
class WindowsButton : iButton { }


Should this not work?

Error: class main.WindowsGui interface function 'iButton
button(ref iButton
button) @property' is not implemented

Or by using the commented line:

Error: cannot implicitly convert expression (button) of type
main.iButton to main.WindowsButton


1. In the first case I override a property using a more derived
type. This should work but doesn't. Seems D doens't support
covariance properly?

2. In the second case, I can cast to make everything work. This
seems wrong. Hence goto 1. WindowsGui is designed to only work
with WindowsButton, say, and I should never have to use iButton
in the WindowsGui class unless, maybe, I want to support
non-windows buttons in the WindowsGui for some reason.

Basically, because of the covariance issue I end up having to 
use

a lot of casts. Hopefully theres some simple trick that won't
pollute the code to make this work. I guess I could use a
templated property with a generic type that is derivable from
iButton to make it work?

In some sense I can understand the error. If I'm using iGui 
then

I have the option to use any button(since it is generic) but if
iGui is a WindowsGui I'm not allowing this. The issue is, that 
I

will have some type of dependency restrictions on the types.

e.g.,

iGui g = new WindowsGui;

g.button = new LinuxButton; // ok but not ok!! (should result 
in

an error in some way)

Obviously I can cast and check the type and do all that. Just
feels like the wrong way to go about it because it requires a 
lot

of casting and polluting the code with checks that in general,
should be unnecessary. Again: In the WindowsGui I want to use
WindowsButton, not iButton because WindowsGui will never need 
any
other type of button. iButton is too general to use in 
WindowsGui.


(it would be cool if one could do something like

class WindowsGui : iGui
iButton <= WindowsButton // constrains iButton to always 
be a

WindowsButton. Checks/casts are automatically added by compiler
when necessary
{
// use WindowsButton here with proper covariance relations 
and

checks/casts
}

Anyways, hopefully there is some single trick to get what I'm
asking?


It should not work because the derived type is requiring more 
than the interface. iGui requires that the parameter to 
button() is iButton:


@property iButton button(ref iButton button);

However, WindowsGui is bringing an extra requirement by asking 
a more specific iButton:


@property WindowsButton button(ref WindowsButton button)

Note that there is no problem with the return type because this 
time the derived type is still returning an iButton because 
WindowsButton "is an" iButton.


I don't know whether this works for you but I made the actual 
button a constructor parameter:


interface iGui
{
@property iButton button();
}

class WindowsGui : iGui
{
WindowsButton _button;

// The constructor gets the button
this(WindowsButton button)
{
this._button = button;
}

@property WindowsButton button()
{
return _button;
}
}

interface iButton { }
class WindowsButton : iButton { }

void main()
{
auto w = new WindowsGui(new WindowsButton());
w.button;
}

Ali


But what about a setter? Using DI isn't the way to go here.

The point that in the windows class, it will only ever use a
windows button. This is fine, but because I'm using
iGui(programming to interfaces), it causes a problem inside the
windows class, which it shouldn't.

e.g., if I only had one gui and used one class, then there would
never be a problem.

Also, it is not a problem of construct, I already have a solution
by casting. But casting hides the fact that windowsgui is meant
to use only a windows button... which is obvious in the design.


Again

iGui uses an iButton
WindowsGui uses a WindowsButton

But when iGui is an actual WindowsGui, it forces WindowsGui to be
more generic than it is meant to be.

The key piece of information here is that I will only ever use
WindowsButtons with WindowsGui... this fact is not general and
the reason the compiler throws the error BUT it is always the
case in my code(except in errors).

I need to inform the compiler that it is always the case and then
I can do what I want.




Re: signatures

2014-02-21 Thread Brad Anderson

On Friday, 21 February 2014 at 23:46:10 UTC, voyager wrote:

is there some thing like typedef?

alias int XXX;
alias int YYY;

void a1(XXX a, YYY b) {int c = a+b;}
void a1(int a, YYY b) {int c = a+b;}


gives an error:
Building Debug\bgitest.exe...
bgitest.obj : fatal error LNK1179: invalid or corrupt file: 
duplicate COMDAT '_D4main2a1FiiZv (void main.a1(int, int))'

Building Debug\bgitest.exe failed!
Details saved as 
"file://G:\PROGRAMMING\DPROG\bgitest\bgitest\Debug\bgitest.buildlog.html"
== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 
skipped ==


http://dlang.org/phobos/std_typecons.html#Typedef


signatures

2014-02-21 Thread voyager

is there some thing like typedef?

alias int XXX;
alias int YYY;

void a1(XXX a, YYY b) {int c = a+b;}
void a1(int a, YYY b) {int c = a+b;}


gives an error:
Building Debug\bgitest.exe...
bgitest.obj : fatal error LNK1179: invalid or corrupt file: 
duplicate COMDAT '_D4main2a1FiiZv (void main.a1(int, int))'

Building Debug\bgitest.exe failed!
Details saved as 
"file://G:\PROGRAMMING\DPROG\bgitest\bgitest\Debug\bgitest.buildlog.html"
== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped 
==


Re: Cannot implicitly convert derived type

2014-02-21 Thread Ali Çehreli

On 02/21/2014 02:54 PM, Frustrated wrote:

interface iGui
{
 @property iButton button(ref iButton button);
}

class WindowsGui : iGui
{
 WindowsButton _button;

 @property WindowsButton button(ref WindowsButton button)
 //@property iButton button(ref iButton button)
 {
 _button = button;
 return button;
 }
}

interface iButton { }
class WindowsButton : iButton { }


Should this not work?

Error: class main.WindowsGui interface function 'iButton
button(ref iButton
button) @property' is not implemented

Or by using the commented line:

Error: cannot implicitly convert expression (button) of type
main.iButton to main.WindowsButton


1. In the first case I override a property using a more derived
type. This should work but doesn't. Seems D doens't support
covariance properly?

2. In the second case, I can cast to make everything work. This
seems wrong. Hence goto 1. WindowsGui is designed to only work
with WindowsButton, say, and I should never have to use iButton
in the WindowsGui class unless, maybe, I want to support
non-windows buttons in the WindowsGui for some reason.

Basically, because of the covariance issue I end up having to use
a lot of casts. Hopefully theres some simple trick that won't
pollute the code to make this work. I guess I could use a
templated property with a generic type that is derivable from
iButton to make it work?

In some sense I can understand the error. If I'm using iGui then
I have the option to use any button(since it is generic) but if
iGui is a WindowsGui I'm not allowing this. The issue is, that I
will have some type of dependency restrictions on the types.

e.g.,

iGui g = new WindowsGui;

g.button = new LinuxButton; // ok but not ok!! (should result in
an error in some way)

Obviously I can cast and check the type and do all that. Just
feels like the wrong way to go about it because it requires a lot
of casting and polluting the code with checks that in general,
should be unnecessary. Again: In the WindowsGui I want to use
WindowsButton, not iButton because WindowsGui will never need any
other type of button. iButton is too general to use in WindowsGui.

(it would be cool if one could do something like

class WindowsGui : iGui
 iButton <= WindowsButton // constrains iButton to always be a
WindowsButton. Checks/casts are automatically added by compiler
when necessary
{
 // use WindowsButton here with proper covariance relations and
checks/casts
}

Anyways, hopefully there is some single trick to get what I'm
asking?


It should not work because the derived type is requiring more than the 
interface. iGui requires that the parameter to button() is iButton:


@property iButton button(ref iButton button);

However, WindowsGui is bringing an extra requirement by asking a more 
specific iButton:


@property WindowsButton button(ref WindowsButton button)

Note that there is no problem with the return type because this time the 
derived type is still returning an iButton because WindowsButton "is an" 
iButton.


I don't know whether this works for you but I made the actual button a 
constructor parameter:


interface iGui
{
@property iButton button();
}

class WindowsGui : iGui
{
WindowsButton _button;

// The constructor gets the button
this(WindowsButton button)
{
this._button = button;
}

@property WindowsButton button()
{
return _button;
}
}

interface iButton { }
class WindowsButton : iButton { }

void main()
{
auto w = new WindowsGui(new WindowsButton());
w.button;
}

Ali



Re: Optimization ???

2014-02-21 Thread rumbu

D version of to!string(uint):

size_t index = 12;
char[12] buffer = void;
uint div = void;
uint mod = void;
char baseChar = 'A';
do {
   div = cast(uint)(mValue / 10);
   mod = mValue % 10 + '0';
   buffer[--index] = cast(char)mod;
   mValue = div;
} while (mValue);
return cast(string)buffer[index .. $].dup;

C# version of uint.ToString() (in fact Int32ToDecChars written in 
C++):


//p is a reusable buffer;
wchar_t* COMNumber::Int32ToDecChars(wchar_t* p, unsigned int 
value, int digits)

{
while (--digits >= 0 || value != 0) {
*--p = value % 10 + '0';
value /= 10;
}
return p;
}
//COMString::NewString(p,...) is called afterwards to obtain a c# 
string.




Cannot implicitly convert derived type

2014-02-21 Thread Frustrated

interface iGui
{
@property iButton button(ref iButton button);
}

class WindowsGui : iGui
{
WindowsButton _button;

@property WindowsButton button(ref WindowsButton button)
//@property iButton button(ref iButton button)
{
_button = button;
return button;
}
}

interface iButton { }
class WindowsButton : iButton { }


Should this not work?

Error: class main.WindowsGui interface function 'iButton
button(ref iButton
button) @property' is not implemented   

Or by using the commented line:

Error: cannot implicitly convert expression (button) of type
main.iButton to main.WindowsButton  


1. In the first case I override a property using a more derived
type. This should work but doesn't. Seems D doens't support
covariance properly?

2. In the second case, I can cast to make everything work. This
seems wrong. Hence goto 1. WindowsGui is designed to only work
with WindowsButton, say, and I should never have to use iButton
in the WindowsGui class unless, maybe, I want to support
non-windows buttons in the WindowsGui for some reason.

Basically, because of the covariance issue I end up having to use
a lot of casts. Hopefully theres some simple trick that won't
pollute the code to make this work. I guess I could use a
templated property with a generic type that is derivable from
iButton to make it work?

In some sense I can understand the error. If I'm using iGui then
I have the option to use any button(since it is generic) but if
iGui is a WindowsGui I'm not allowing this. The issue is, that I
will have some type of dependency restrictions on the types.

e.g.,

iGui g = new WindowsGui;

g.button = new LinuxButton; // ok but not ok!! (should result in
an error in some way)

Obviously I can cast and check the type and do all that. Just
feels like the wrong way to go about it because it requires a lot
of casting and polluting the code with checks that in general,
should be unnecessary. Again: In the WindowsGui I want to use
WindowsButton, not iButton because WindowsGui will never need any
other type of button. iButton is too general to use in WindowsGui.

(it would be cool if one could do something like

class WindowsGui : iGui
iButton <= WindowsButton // constrains iButton to always be a
WindowsButton. Checks/casts are automatically added by compiler
when necessary
{
// use WindowsButton here with proper covariance relations and
checks/casts
}

Anyways, hopefully there is some single trick to get what I'm
asking?


Re: Is there kind of "associative tuple" - like syntax in D?

2014-02-21 Thread Philippe Sigaud
Justin:
> alias MyFoo = Foo!(opt1(23), opt2("foo"));

That's also my preferred solution. I find it easy to read and it's quite
typesafe (also, it allows for more complex possibilities like n-params
options).

Another solution could be to use an associative array literal for each
option (you have to use one AA for each option, because they can have
different types for keys and values):

alias MyFoo = Foo!([Option1 : 123], [Option2 : "foo"]);

Where each AA literal is passed as a template alias parameter (or an
element in a template tuple parameter):

... Foo(Options...)

I'm typing this on a pad, I cannot show some working code, but they idea is
to check Options elements with

// Option[i] is an AA, for some Key and some Value
is(typeof(Options[i]) == Value[Key], Value, Key)

and then act on the only key/value pair stored in Options. You can get the
only key with Options[i].keys[0] and the associated value with
Options[i][Options[i].keys[0]]


Re: Is there kind of "associative tuple" - like syntax in D?

2014-02-21 Thread Justin Whear
On Fri, 21 Feb 2014 19:09:56 +, Uranuz wrote:


>> You could do something like this:
>>
>> alias Foo!(
>> OptionType.optType1, 100, OptionType.optType2, "example,
>> ...etc...
>> ) MyFoo;
> 
> Yes. I already use this. But it makes it not semanticaly obvious that
> OptionType.optType1 is a kind of `key` and 100 is `value`. Also it needs
> to parse it and check for correctness that you have `key` and
> corresponding value. Also code that realize parsing could shadow main
> logic of class/function. Another point is that `key`: `value` form is
> easier to read than sequence of some values separated by ','. You often
> need to move every key-value pair to single line to make it readeble.
> 
> May be it's just syntactic sugar and isn't looking in D'ish way or
> something.

I can't think of any way to get `:` or `=` to indicate assignment here.  
This is as clean as I could get things in 10 minutes (runs with `rdmd -
main`):


enum OptionType
{
Option1,
Option2
}

struct OptionPair(OptionType opt, T)
{
enum option = opt;
T value;

this(T v)
{
value = v;
}
}

class Foo(Opts...)
{
// Prove it works
static this()
{
import std.stdio;
foreach (opt; Opts)
writeln(opt.option, " = ", opt.value);
}
}

alias opt1 = OptionPair!(OptionType.Option1, int);
alias opt2 = OptionPair!(OptionType.Option2, string);

alias MyFoo = Foo!(opt1(23), opt2("foo"));


Re: convert int[][] to int**

2014-02-21 Thread Chris Williams

On Friday, 21 February 2014 at 19:13:13 UTC, Chris Williams wrote:

On Thursday, 20 February 2014 at 17:02:15 UTC, Dicebot wrote:
You can't do it without allocation because memory layout is 
different for int** and int[][] in D - are.ptr in latter 
points to slice struct (pointer+length) as opposed to raw 
pointer in former.


You should only have to copy the top list, though.

int*[] temp = new int*[ arr.length ];
for (size_t i = 0; i < arr.length; i++) {
temp[i] = arr[i].ptr;
}
int** output = temp.ptr;

Untested.


Addendum: Note that bearophile's code probably works out to the 
same thing.


Re: convert int[][] to int**

2014-02-21 Thread Chris Williams

On Thursday, 20 February 2014 at 17:02:15 UTC, Dicebot wrote:
You can't do it without allocation because memory layout is 
different for int** and int[][] in D - are.ptr in latter points 
to slice struct (pointer+length) as opposed to raw pointer in 
former.


You should only have to copy the top list, though.

int*[] temp = new int*[ arr.length ];
for (size_t i = 0; i < arr.length; i++) {
temp[i] = arr[i].ptr;
}
int** output = temp.ptr;

Untested.


Re: Is there kind of "associative tuple" - like syntax in D?

2014-02-21 Thread Uranuz


You could do something like this:

alias Foo!(
OptionType.optType1, 100,
OptionType.optType2, "example,
...etc...
) MyFoo;


Yes. I already use this. But it makes it not semanticaly obvious 
that OptionType.optType1 is a kind of `key` and 100 is `value`. 
Also it needs to parse it and check for correctness that you have 
`key` and corresponding value. Also code that realize parsing 
could shadow main logic of class/function. Another point is that  
`key`: `value` form is easier to read than sequence of some 
values separated by ','. You often need to move every key-value 
pair to single line to make it readeble.


May be it's just syntactic sugar and isn't looking in D'ish way 
or something.




Re: Is there kind of "associative tuple" - like syntax in D?

2014-02-21 Thread Justin Whear
On Fri, 21 Feb 2014 17:57:57 +, Uranuz wrote:

> My idea is that pass these options using syntax like this:
> 
> alias Foo!( [
>OptionType.optType1 : 100, OptionType.optType2 : "example",
>"someOtherOpt1": "someOtherOptValue", "someOtherOpt2": true
>   ]  ) MyFoo;
> 
> Using [] brackets it's just for example. It could be changed to {} (Like
> Object in JavaScript). Of course we can create Pair template:
> 
> template P( alias first, alias second )
> {  alias first key;
> alias second value;
> }
> 
> So we will rewrite previous code like that:
> 
> alias Foo!(
>P(OptionType.optType1, 100), P(OptionType.optType2, "example"),
>P("someOtherOpt1", "someOtherOptValue"),
>P("someOtherOpt2", true)
> ) MyFoo;
> 

You could do something like this:

alias Foo!(
OptionType.optType1, 100,
OptionType.optType2, "example,
...etc...
) MyFoo;

To see how to parse this sort of list, take a look at the implementations 
of std.typecons.Tuple and std.getopt.


Is there kind of "associative tuple" - like syntax in D?

2014-02-21 Thread Uranuz
In my template functions, classes it's necessary to write 
variadic template parameter list, where elements are options to 
this class/function  changing it's behaviour. But they are 
optional and may be not set at all. These options may be folowed 
by variadic template parameter list that will be processed in 
static foreach loop. What I'm thinking about is creating some 
sort of key-value tuple syntax like in associative arrays. For 
example I could set components or options of my template in 
easy-to-read manner.


I have option types in enum:

enum OptionType { optType1, optType2, optType3 };

Now I write something like this:

// 1.
class Foo( OptionType opt1, int value1, TL.. )
   if( opt1 == OptionType.optType1 )
{}

// 2.
class Foo( OptionType opt1, string value1, TL.. )
   if( opt1 == OptionType.optType2 )
{}

class Foo( OptionType opt1, string value1, OptionType opt2, int 
value2, TL.. )
   if( opt1 == OptionType.optType2 && opt2 == OptionType.optType1 
)

{}

// 4. Order of options can variate but will not change behaviour
class Foo( OptionType opt1, int value1, OptionType opt2, string 
value2, TL.. )

   if( opt1 == OptionType.optType1 &&  )
{}

What I want is to set and parse these options using universal 
template signature


class Foo( Opts... )
{}

and parse it using forech over tuple and `static if`.

My idea is that pass these options using syntax like this:

alias Foo!( [
  OptionType.optType1 : 100,
  OptionType.optType2 : "example",
  "someOtherOpt1": "someOtherOptValue",
  "someOtherOpt2": true
 ]  ) MyFoo;

Using [] brackets it's just for example. It could be changed to 
{} (Like Object in JavaScript). Of course we can create Pair 
template:


template P( alias first, alias second )
{  alias first key;
   alias second value;
}

So we will rewrite previous code like that:

alias Foo!(
  P(OptionType.optType1, 100),
  P(OptionType.optType2, "example"),
  P("someOtherOpt1", "someOtherOptValue"),
  P("someOtherOpt2", true)
) MyFoo;

But this is not very elegant at my point of sight. Another way 
that could help in this case is to have named parameters. I don't 
remember the correct name of this term. Pascal and Python and 
other languages have it. Syntax is that you can name parameter 
names for parameters that you pass when calling function (or in 
the case above when you are instantiating template). It could be 
realized using `=` character. For example:


alias Foo!( option1 = 100, option2 = "example", option3 = true ) 
MyFoo;


In this case some of these options (template parameters) can be 
missed and this should be able to handle in template body using 
`static if`, `foreach`.


May be all of these trick are sophisticated, hard-to-implement 
or/and break paradigm of D language. But these proposals could 
(maybe) improve readability of programms with huge amount of 
template code.




Re: Method template optimization that works in C++, but not very well D

2014-02-21 Thread Vladimir

On Thursday, 20 February 2014 at 22:36:58 UTC, Ali Çehreli wrote:

int proccessRowTemplate(size_t optionVariant)(in Row table)
{
int sum = 0;
foreach(size_t i; StaticRange!(Row.numberField))
{
static if (optionVariant & 1<

This version of the program looks more graceful than mine, and 
works faster. My example in github is updated.




Results on my system after that change:...
Simple processing: 35 ms
...
Template processing: 15 ms



I got same result in my system for dmd. It is good.

But for ldc and gdc the result is almost unchanged.  May be there 
are more ideas why this optimization does not help in cases gdc 
and ldc? I looked at the llvm-ir code my example ... At first 
glance, there is exactly what it should be.


In any case, thank you


Re: immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

2014-02-21 Thread Ali Çehreli

On 02/21/2014 08:46 AM, Gopan wrote:

> On Friday, 21 February 2014 at 14:04:45 UTC, FreeSlave wrote:
>> Another strange thing:
>>
>> import std.stdio;
>>
>> uint Test()
>> {
>> if (!__ctfe)
>> {
>> return 3;
>> }
>> return 2;
>> }
>>
>>
>>
>> void main()
>> {
>> immutable n = Test();
>> int[n] arr;
>> writeln("arrary length = ", arr.length, " ; n = ", n);
>> }
>>
>> Output:
>> arrary length = 2 ; n = 3
>>
>> When you think about it you understand that it's logically right
>> behavior, but it's not acceptable in practice.
>
> It looks like 'immutable n = Test();' is executed during both compile
> time and runtime.  Is that what is happening?

Yes. The compiler needs the value of n at compile time so it evaluates 
it at compile time.


I agree that it is confusing but I feel like it is the responsibility of 
the programmer to ensure consistent behavior.


Ali



Re: immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

2014-02-21 Thread Gopan

On Friday, 21 February 2014 at 14:04:45 UTC, FreeSlave wrote:

Another strange thing:

import std.stdio;

uint Test()
{
if (!__ctfe)
{
return 3;
}
return 2;
}



void main()
{
immutable n = Test();
int[n] arr;
writeln("arrary length = ", arr.length, " ; n = ", n);
}

Output:
arrary length = 2 ; n = 3

When you think about it you understand that it's logically 
right behavior, but it's not acceptable in practice.


It looks like 'immutable n = Test();' is executed during both 
compile time and runtime.  Is that what is happening?


Re: Optimization ???

2014-02-21 Thread Mattdef

On Friday, 21 February 2014 at 13:39:08 UTC, Orvid King wrote:

The single biggest reason that this is slower in D than in C# is
because of the GC. By default with MS.Net, and Mono (when 
compiled
with sgen) an allocation is almost literally just a 
bump-the-pointer,
with an occasional scan (no compaction for this code) and 
collection
of the 64kb (on MS.Net it actually the size of your CPU's L1 
cache)
gen0 heap. This particular code is unlikely to trigger a 
collection of
gen1 (L2 cache when on MS.Net), gen2 or the large object heap. 
In D

however, the allocations are significantly more expensive.

On 2/21/14, John Colvin  wrote:

On Friday, 21 February 2014 at 09:29:42 UTC, Mattdef wrote:

Thanks for yours replies.

I know it is the conversion of uint that is the problem but my
C#
code has the same conversion. So C# is better than D for 
string

conversions ?

(sorry for my english)


It's quite possible that C# has faster string conversion in at
least some cases.

In particular, making lots of small strings is very garbage 
heavy
and the D garbage collector isn't as sophisticated as the one 
in

C#


Thanks for yours answers !


Re: Why function template 'among' is of complexity O(1) and not O(n)?

2014-02-21 Thread anonymous

On Thursday, 20 February 2014 at 13:40:38 UTC, anonymous wrote:

When a
value is needed at compile time (e.g. initializer for a static
variable, length of a static array), then CTFE is forced. When
the value is not needed at compile time, the optimizer may go 
for

it, but that's not guaranteed.


On Thursday, 20 February 2014 at 21:23:08 UTC, anonymous wrote:
On Thursday, 20 February 2014 at 17:08:11 UTC, Jakob Ovrum 
wrote:

On Thursday, 20 February 2014 at 13:40:38 UTC, anonymous wrote:
When the value is not needed at compile time, the optimizer 
may go for it, but that's not guaranteed.


That's not really true. The optimizer will never try CTFE 
because of the halting problem. Runtime is runtime, 
compile-time is compile-time - they are clearly separated by 
the context of the expression alone.


LDC does it. The halting problem just dictates that it can't be
done in all cases.


While it's evaluation at compile time, that optimization should
not be called "CTFE". The way I had worded it, it sounded like
__ctfe may or may not be true, depending on the optimizer's mood.
That's not so, of course.


Re: immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

2014-02-21 Thread anonymous

On Friday, 21 February 2014 at 13:38:58 UTC, Gopan wrote:

Attempting to learn CTFE, I tried the following test.

size_t counter;

uint Test()
{
if (!__ctfe)
{
++counter;// This code is for execution at run time
}
return 2;
}

void main()
{
writeln("counter = ", counter);

immutable int n = Test();


As this is a local variable, this is a runtime initialization, no
__ctfe here. Doesn't matter that it's immutable. It's
static/global vs local. So, this correctly does ++counter.

Make it static immutable n, and counter won't be incremented.


int[n] arr;


Not sure if this should compile. n is a run-time value. It just
happens that it can be CTFE'd. A more problematic case:
---
void main()
{
immutable n = __ctfe ? 1 : 2;
int[n] a;
assert(a.length == n); // fails, wat
}
---

	writeln("arrary length = ", arr.length, " ; counter = ", 
counter);

}

output:
counter = 0
arrary length = 2 ; counter = 1

For array declaration to be successful, its size has to be 
known at compile time.  The above code compiles too.  But 
__ctfe seems to be false while performing Test().


Instead, if I write
int[Test()] c;
writeln("c.length = ", c.length, " ; counter = ", counter);
output is
counter = 0
c.length = 2 ; counter = 0

What is wrong in my mind?

Thanks,
Gopan


Re: immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

2014-02-21 Thread FreeSlave

Another strange thing:

import std.stdio;

uint Test()
{
if (!__ctfe)
{
return 3;
}
return 2;
}



void main()
{
immutable n = Test();
int[n] arr;
writeln("arrary length = ", arr.length, " ; n = ", n);
}

Output:
arrary length = 2 ; n = 3

When you think about it you understand that it's logically right 
behavior, but it's not acceptable in practice.


Re: immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

2014-02-21 Thread FreeSlave

On Friday, 21 February 2014 at 13:38:58 UTC, Gopan wrote:

Attempting to learn CTFE, I tried the following test.

size_t counter;

uint Test()
{
if (!__ctfe)
{
++counter;// This code is for execution at run time
}
return 2;
}

void main()
{
writeln("counter = ", counter);

immutable int n = Test();
int[n] arr;
	writeln("arrary length = ", arr.length, " ; counter = ", 
counter);

}

output:
counter = 0
arrary length = 2 ; counter = 1

For array declaration to be successful, its size has to be 
known at compile time.  The above code compiles too.  But 
__ctfe seems to be false while performing Test().


Instead, if I write
int[Test()] c;
writeln("c.length = ", c.length, " ; counter = ", counter);
output is
counter = 0
c.length = 2 ; counter = 0

What is wrong in my mind?

Thanks,
Gopan


Use enum n = Test() or make immutable n global variable i.e. 
place it before main.


immutable int n = Test(); int[n] x; ---- compiles, but __ctfe is false. How?

2014-02-21 Thread Gopan

Attempting to learn CTFE, I tried the following test.

size_t counter;

uint Test()
{
if (!__ctfe)
{
++counter;// This code is for execution at run time
}
return 2;
}

void main()
{
writeln("counter = ", counter);

immutable int n = Test();
int[n] arr;
	writeln("arrary length = ", arr.length, " ; counter = ", 
counter);

}

output:
counter = 0
arrary length = 2 ; counter = 1

For array declaration to be successful, its size has to be known 
at compile time.  The above code compiles too.  But __ctfe seems 
to be false while performing Test().


Instead, if I write
int[Test()] c;
writeln("c.length = ", c.length, " ; counter = ", counter);
output is
counter = 0
c.length = 2 ; counter = 0

What is wrong in my mind?

Thanks,
Gopan


Re: Optimization ???

2014-02-21 Thread Orvid King
The single biggest reason that this is slower in D than in C# is
because of the GC. By default with MS.Net, and Mono (when compiled
with sgen) an allocation is almost literally just a bump-the-pointer,
with an occasional scan (no compaction for this code) and collection
of the 64kb (on MS.Net it actually the size of your CPU's L1 cache)
gen0 heap. This particular code is unlikely to trigger a collection of
gen1 (L2 cache when on MS.Net), gen2 or the large object heap. In D
however, the allocations are significantly more expensive.

On 2/21/14, John Colvin  wrote:
> On Friday, 21 February 2014 at 09:29:42 UTC, Mattdef wrote:
>> Thanks for yours replies.
>>
>> I know it is the conversion of uint that is the problem but my
>> C#
>> code has the same conversion. So C# is better than D for string
>> conversions ?
>>
>> (sorry for my english)
>
> It's quite possible that C# has faster string conversion in at
> least some cases.
>
> In particular, making lots of small strings is very garbage heavy
> and the D garbage collector isn't as sophisticated as the one in
> C#
>


Re: Optimize my code =)

2014-02-21 Thread John Colvin

On Thursday, 20 February 2014 at 21:32:10 UTC, Robin wrote:

Hiho,

here are the results of both compilers (DMD and LDC2) on my 
system:


LDC:
=
allocationTest ...
Time required: 5 secs, 424 msecs
multiplicationTest ...
Time required: 1 secs, 744 msecs
toStringTest ...
Time required: 0 secs, 974 msecs
transposeTest ...
Time required: 0 secs, 998 msecs
scalarMultiplicationTest ...
Time required: 0 secs, 395 msecs
matrixAddSubTest ...
Time required: 0 secs, 794 msecs
matrixEqualsTest ...
Time required: 0 secs, 0 msecs
identityMatrixTest ...
Time required: 0 secs, 393 msecs
=

DMD:
=
allocationTest ...
Time required: 3 secs, 161 msecs
multiplicationTest ...
Time required: 2 secs, 6 msecs
toStringTest ...
Time required: 1 secs, 365 msecs
transposeTest ...
Time required: 1 secs, 45 msecs
scalarMultiplicationTest ...
Time required: 0 secs, 405 msecs
matrixAddSubTest ...
Time required: 0 secs, 809 msecs
matrixEqualsTest ...
Time required: 0 secs, 430 msecs
identityMatrixTest ...
Time required: 0 secs, 350 msecs
=

All in all I must say that I am more pleased with the DMD 
results as I am kind of worried about the LDC allocation test 
performance ...


I also had to rewrite parts of the codes as some functions just 
weren't "pure" or "nothrow" such as the whole things around 
this.data[] += other.data[].


Robin


what flags did you use?


Re: Static arrays and std.algorithm.sort

2014-02-21 Thread John Colvin

On Thursday, 20 February 2014 at 17:24:55 UTC, D Apprentice wrote:

Greetings, D wizards.

Given a static array, int[5] a, presumed to be filled with 
random

numbers, how does one sort it using std.algorithm.sort? Calling
sort(a) by itself errors out with:

test.d(7): Error: template std.algorithm.sort does not match any
function template declaration. Candidates are:
/usr/share/dmd/src/phobos/std/algorithm.d(8387):
std.algorithm.sort(alias less = "a < b", SwapStrategy ss =
SwapStrategy.unstable, Range)(Range r) if ((ss ==
SwapStrategy.unstable && (hasSwappableElements!Range ||
hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
hasAssignableElements!Range) && isRandomAccessRange!Range &&
hasSlicing!Range && hasLength!Range)
test.d(7): Error: template std.algorithm.sort(alias less = "a <
b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if
((ss == SwapStrategy.unstable && (hasSwappableElements!Range ||
hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
hasAssignableElements!Range) && isRandomAccessRange!Range &&
hasSlicing!Range && hasLength!Range) cannot deduce template
function from argument types !()(int[5])

This is a general interest question. As I understand it, D 
static

arrays are value types, as opposed to their dynamic siblings
which are reference types, and I suspect that is the underlying
issue here.

One little idiom I found, though I do not know if it's very
efficient, is using the array slice syntax:

sort (a[0..a.length]);

This works, but I'm curious if there's another (better) way? The
biggest advantage that I can see to the slice syntax is that it
allows the programmer to sort only part of the array, which one
could do in C with qsort.

Source:

import std.stdio;
import std.algorithm;

void main ()
{
int[5] a = [9, 5, 1, 7, 3];
//sort (a); //Fails
//sort (a[0..a.length]); //Works
writeln (a);
}

Thank you for your time.


static arrays are not slices. Using [] gives you a slice from a 
static array. I often find myself writing this:


int[5] aStatic = [9, 5, 1, 7, 3];
auto a = aStatic[];

and just being careful not to leak references.


Re: Optimization ???

2014-02-21 Thread John Colvin

On Friday, 21 February 2014 at 09:29:42 UTC, Mattdef wrote:

Thanks for yours replies.

I know it is the conversion of uint that is the problem but my 
C#

code has the same conversion. So C# is better than D for string
conversions ?

(sorry for my english)


It's quite possible that C# has faster string conversion in at 
least some cases.


In particular, making lots of small strings is very garbage heavy 
and the D garbage collector isn't as sophisticated as the one in 
C#


Re: [video tutorial] Defensive programming with Design By Contract basics

2014-02-21 Thread Mengu

On Friday, 21 February 2014 at 09:59:04 UTC, simendsjo wrote:

On Friday, 21 February 2014 at 09:46:20 UTC, Mengu wrote:

On Thursday, 20 February 2014 at 10:28:45 UTC, simendsjo wrote:

http://youtu.be/wFqHTCBt72M


enjoyed it, thanks!

what are you going to talk about next?


I only have a rough outline in my head that will probably 
change as I go:
* Split the project in two DUB packages (preparing for web 
frontend)

* Calling the existing CLI app using std.process
* Web frontend
* Reusable game code - both CLI and web interface use the 
library rather than web using std.process

* Unittesting
* DDoc and ddox
* Publishing to code.dlang.org


and that basically turns it into a great dlang series, thanks.


Re: [video tutorial] Defensive programming with Design By Contract basics

2014-02-21 Thread simendsjo

On Friday, 21 February 2014 at 09:46:20 UTC, Mengu wrote:

On Thursday, 20 February 2014 at 10:28:45 UTC, simendsjo wrote:

http://youtu.be/wFqHTCBt72M


enjoyed it, thanks!

what are you going to talk about next?


I only have a rough outline in my head that will probably change 
as I go:
* Split the project in two DUB packages (preparing for web 
frontend)

* Calling the existing CLI app using std.process
* Web frontend
* Reusable game code - both CLI and web interface use the library 
rather than web using std.process

* Unittesting
* DDoc and ddox
* Publishing to code.dlang.org


Re: [video tutorial] Defensive programming with Design By Contract basics

2014-02-21 Thread Mengu

On Thursday, 20 February 2014 at 10:28:45 UTC, simendsjo wrote:

http://youtu.be/wFqHTCBt72M


enjoyed it, thanks!

what are you going to talk about next?


Re: Optimization ???

2014-02-21 Thread Mattdef

Thanks for yours replies.

I know it is the conversion of uint that is the problem but my C#
code has the same conversion. So C# is better than D for string
conversions ?

(sorry for my english)