Re: Mysterious identifier in std.traits.ParameterStorageClassTuple

2018-07-24 Thread arturg via Digitalmars-d

On Tuesday, 24 July 2018 at 21:05:05 UTC, Jean-Louis Leroy wrote:
What is `PT` here: 
https://github.com/dlang/phobos/blob/master/std/traits.d#L1224

Where does it come from?


https://dlang.org/spec/expression.html#is_expression

look for
6. is ( Type Identifier == TypeSpecialization )


Re: Determine if CTFE or RT

2018-06-24 Thread arturg via Digitalmars-d-learn

On Sunday, 24 June 2018 at 19:10:36 UTC, Mr.Bingo wrote:

On Sunday, 24 June 2018 at 18:21:09 UTC, rjframe wrote:

On Sun, 24 Jun 2018 14:43:09 +, Mr.Bingo wrote:

let is(CTFE == x) mean that x is a compile time constant. 
CTFE(x)
converts a x to this compile time constant. Passing any 
compile time

constant essentially turns the variable in to a compile time
constant(effectively turns it in to a template with template 
parameter)




You can use __ctfe:

static if (__ctfe) {
// compile-time execution
} else {
// run-time execution
}


This does not work:


import std.stdio;

auto foo(int i)
{
if (__ctfe)
{
return 1;
} else {
return 2;
}
}

void main()
{
writeln(foo(3));
}


should print 1 but prints 2.


you have to call foo with ctfe
enum n = foo(3);
writeln(n);


Re: Quick Refresher book?

2018-06-16 Thread arturg via Digitalmars-d-learn

On Saturday, 16 June 2018 at 23:33:18 UTC, Aedt wrote:
Hello, I was wondering if there's any quick refresher resource 
to brush up on my D after a long time? Is there a short and 
quick language reference book like "A Tour of C++"?


if you havent seen it yet, there is the dlang tour
https://tour.dlang.org


Re: Build interface from abstract class

2018-05-29 Thread arturg via Digitalmars-d-learn

On Tuesday, 29 May 2018 at 19:06:24 UTC, DigitalDesigns wrote:

On Monday, 28 May 2018 at 22:15:40 UTC, arturg wrote:

this might help you,
https://dpaste.dzfl.pl/2cf844a11e3f

you can use them to generate the functions as strings.


Thanks,

So, the problem I'm having is that I cannot use the generated 
interface for the abstract class because the abstract class 
needs the interface defined. I need to be able to forward 
define the interface then extend it.


D doesn't like this

main.d(10): Error: interface `main.B` base `A` is forward 
referenced


interface A;
mixin(Generate!(B,A));
interface B : A
{

}

abstract class C : B
{

}



would it work if you define the interface but mixin the members?

interface A
{
mixin(InterfaceFromClass!C);
}


Re: Build interface from abstract class

2018-05-28 Thread arturg via Digitalmars-d-learn

this might help you,
https://dpaste.dzfl.pl/2cf844a11e3f

you can use them to generate the functions as strings.


Re: Sealed classes - would you want them in D? (v2)

2018-05-17 Thread arturg via Digitalmars-d

On Thursday, 17 May 2018 at 07:30:58 UTC, KingJoffrey wrote:

On Thursday, 17 May 2018 at 06:03:19 UTC, arturg wrote:


you could declare the public api of your class inside an 
actual interface then use it instead of the class, that wont 
give you access to the private members of the class.


you mean like this?


module test;

interface Animal { string makeNoise(); }

class Dog : Animal
{
private string noiseType = "woof";

override string makeNoise()
{
return this.noiseType;
}
}

void main()
{
import std.stdio;

auto dog = new Dog;
dog.noiseType = "meow"; // grr!
writeln(dog.makeNoise()); // wtf! Thanks to D, my dog can 
now meow!

}




no, that uses type inferance.
you have to do
Animal dog = new Dog;


Re: Sealed classes - would you want them in D? (v2)

2018-05-17 Thread arturg via Digitalmars-d

On Thursday, 17 May 2018 at 05:06:54 UTC, KingJoffrey wrote:


If people want to propose putting each class in it's own 
module, that does not address my requirements, and therefore is 
not helpful to this discussion.


you could declare the public api of your class inside an actual 
interface then use it instead of the class, that wont give you 
access to the private members of the class.


Re: returning and receiving multiple values from a function

2018-05-14 Thread arturg via Digitalmars-d

On Tuesday, 15 May 2018 at 01:40:50 UTC, timepp wrote:

Now C++ allow this in a very clean way:

std::tuple foo() {   return {128, true, 
1.5f}; }



auto [value1, value2, value3] = foo();



Would D plan to support that in syntax level?


it depends if some dip like 
https://github.com/tgehr/DIPs/blob/tuple-syntax/DIPs/DIP1xxx-tg.md is accepted.


Re: Generating a method using a UDA

2018-05-09 Thread arturg via Digitalmars-d-learn

On Wednesday, 9 May 2018 at 10:16:22 UTC, Melvin wrote:
I'm trying to find a friendly syntax for defining things in a 
framework. For context, I've been looking into finding a 
solution for this problem 
(https://github.com/GodotNativeTools/godot-d/issues/1) on the 
Godot-D project. I've done some investigating already, and it 
looks like I can only achieve what I want with a mixin, but I'd 
like to get a second opinion.


Say we have a class that defines a custom Signal (an event). In 
an ideal world, the syntax would work similarly to this:


class SomeNode : GodotScript!Node
{
@Signal void testSignal(float a, long b);
// The declaration above would trigger the generation of 
this line
void testSignal(float a, long b) { 
owner.emitSignal("testSignal", a, b); }


@Method emitTest()
{
testSignal(3.1415, 42);
}
}


The reason I want to use a UDA is to stay consistent with the 
other UDAs already defined for Properties and Methods. It also 
looks friendlier than using a mixin. Does anyone here have any 
thoughts as to how this could work?


My main issue is injecting that generated method without 
resorting to using a mixin. I was hoping that any code I needed 
could be generated in the template that SomeNode inherits, but 
that doesn't look possible because I can't inspect the subclass 
(for good reason).


hi, i actually have something like that, which i should put on 
github.


i used it to learn about D's introspection, so its more of a 
prototype and will need some more work.


it looks like this:

class Test
{
mixin signalsOf!SigList;

interface SigList
{
@Signal void someFun(int);
}

void someFunHandler(int){}
}

signalsOf takes a type/template or function list, introspects 
them then generates the actual signal functions.

the additional api is similar to qt's api.

void main()
{
Test t = new Test;
t.connect!"someFun"();
t.someFun(4); // emit the signal
t.disconnect!"someFun"();
}

you can have different connection types and i also have string 
based connection and auto connection based on a naming convetion 
like signalname: someSig and slotname: onSomeSig.


Re: Found on proggit: Krug, a new experimental programming language, compiler written in D

2018-04-26 Thread arturg via Digitalmars-d
On Thursday, 26 April 2018 at 22:29:46 UTC, Nick Sabalausky 
(Abscissa) wrote:

On 04/26/2018 01:13 PM, arturg wrote:


why do people use this syntax?

if val == someVal

or

while val != someVal

it makes editing the code harder then if you use if(val == 
someVal).


The theory goes:

A. "less syntax => easier to read".
B. "There's no technical need to require it, and everything 
that can be removed should be removed, thus it should be 
removed".


Personally, I find the lack of parens gives my brain's visual 
parser insufficient visual cues to work with, so I always find 
it harder to read. And regarding "B", I just don't believe in 
"less is more" - at least not as an immutable, universal truth 
anyway. Sometimes it's true, sometimes it's not.


yeah same here,
and if people find delimiters anoying, editors with syntax 
highlighting can help with that by making them less visible so 
the important content sticks out more.


But not having some delimiter removes the ability to edit the 
text by using for exemple vims text object commands (vi(, yi[, 
and so on).
In this regard, ddoc's syntax is anoying because the identifier 
is inside the parens:

$(somemacro, content)
it would have been better if it was:
$somemacro(content).
Which can make html more editable then ddoc :/ as vim recognises 
tags as text objects.


Re: Found on proggit: Krug, a new experimental programming language, compiler written in D

2018-04-26 Thread arturg via Digitalmars-d

On Thursday, 26 April 2018 at 15:07:37 UTC, H. S. Teoh wrote:
On Thu, Apr 26, 2018 at 08:50:27AM +, Joakim via 
Digitalmars-d wrote:

https://github.com/felixangell/krug

https://www.reddit.com/r/programming/comments/8dze54/krug_a_systems_programming_language_that_compiles/


It's still too early to judge, but from the little I've seen of 
it, it seems nothing more than just a rehash of C with a 
slightly different syntax.  It wasn't clear from the docs what 
exactly it brings to the table that isn't already done in C, or 
any other language.



T


why do people use this syntax?

if val == someVal

or

while val != someVal

it makes editing the code harder then if you use if(val == 
someVal).


Re: Delegates and classes for custom code.

2018-04-17 Thread arturg via Digitalmars-d-learn

On Wednesday, 18 April 2018 at 01:58:40 UTC, arturg wrote:


is it this what you want?

   class A
   {
   int a;
   void delegate() onDraw;

   this(void delegate() dg)
   {
   onDraw = dg;
   }

   void drawText(string s)
   {
   s.writeln;
   }
   }

   void main()
   {
A a;
a = new A((){ a.a = 5; a.drawText("test"); "drawing 
all".writeln; });

}

but if you do A a = new A((){ a.a = 5; ...});
the dg cant capture 'a' yet.
so maybe it would be better to just do:
A a = new A;
a.onDraw = (){ a.drawText("test"); "draw rest".writeln; };


ah i see bauss already wrote the same.

some other aproach could be:

class Base
{
final void draw()
{ drawSelf(); }

abstract void drawSelf();
}

class A : Base
{
override void drawSelf()
{ ... }
}


Re: Delegates and classes for custom code.

2018-04-17 Thread arturg via Digitalmars-d-learn

On Wednesday, 18 April 2018 at 01:12:33 UTC, Chris Katko wrote:

That was all pseudo-code typed by hand.

I got my code to work today. I don't know if it's the prettiest 
it can be, but it works:


// TESTING ACCESS TO the OWNING function
//---
class test_window
{
float x;
float y;

void draw_text(string text)
{
writeln(text);  
}

this( void function(test_window) onDraw  )
{   
this.onDraw = onDraw;
}

void run() //called every frame
{
onDraw(this);
}

void function (test_window) onDraw;
}


void test_dialog()
{
auto t = new test_window(function void(test_window ptr)
{
with(ptr)
{
draw_text( format("Hello, world. [x,y]=[%f,%f]", x, y));
}
});

t.run();
}





And a second attempt/version:





// TESTING ACCESS to anything
// --

struct data_to_access_t
{
int tacos;
}

struct data_to_access2_t
{
struct beans
{
int x;
};

beans b;
}

class abc(T)
{
int x;
void delegate(T) run_delegate;

T data;

this(T t, void delegate(T) d)
{
data = t;
run_delegate = d;
}

void execute()
{
run_delegate(data);
}
}

void test_dialog_anything()
{   
data_to_access_t  d;
data_to_access2_t d2;
d.tacos = 4;
d2.b.x  = 5;

	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );
	auto y = new abc!data_to_access_t ( d, (d){writefln("test  
%d", d.tacos);}  );
	auto z = new abc!data_to_access2_t(d2, delegate void 
(d2){writefln("test2 %d", d2.b.x);}  );


x.execute();
y.execute();
z.execute();
}





My only questions are:

 -  is there any way to make it "smart" enough to take the type 
of the argument, instead of me manually giving it a type.


	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );

becomes
auto x = new abc( d, (d) => writefln("test  %d", d.tacos)  );

 - Is there any way to eliminate the first d? Which is 
essentially a "this" pointer.


	auto x = new abc!data_to_access_t ( d, (d) => writefln("test  
%d", d.tacos)  );

becomes
	auto x = new abc!data_to_access_t ( (d) => writefln("test  
%d", d.tacos)  );


 - And preferably, if possible, both. But I'll take what I can 
get.


is it this what you want?

   class A
   {
   int a;
   void delegate() onDraw;

   this(void delegate() dg)
   {
   onDraw = dg;
   }

   void drawText(string s)
   {
   s.writeln;
   }
   }

   void main()
   {
A a;
a = new A((){ a.a = 5; a.drawText("test"); "drawing 
all".writeln; });

}

but if you do A a = new A((){ a.a = 5; ...});
the dg cant capture 'a' yet.
so maybe it would be better to just do:
A a = new A;
a.onDraw = (){ a.drawText("test"); "draw rest".writeln; };


Re: Enum and Function Parameters Attributes -- No DIP Required

2018-04-12 Thread arturg via Digitalmars-d-announce

On Thursday, 12 April 2018 at 08:28:17 UTC, Mike Parker wrote:


Around the same time, a Pull Request was created to implement 
support for UDAs on function parameters [4]. In the comment 
thread for this PR, Andrei said that he and Walter "agree this 
can be integrated without a DIP." When he realized a DIP had 
already been submitted, he wanted to approve it "without too 
much paperwork."


[4] https://github.com/dlang/dmd/pull/7576


will templates be supported?
dont know, maybe something like this example:

void test(T)(T t) { }
void test2(Args...)(Args args) { }
void main()
{
// uda declaration as a ct-param
test!(@(1) int)(1);
test2!(@(1) int, @(2) string)(1, "test");
test!(@(1))(1); // inferred type but provided uda?
1.test!(@(1) int);
1.test2!(@(1) int, @(2) string)("test");
1.test!(@(1)); // inferred type but provided uda?

// or alternatively as a rt-param
test(@(1) 1); // inferred type but provided uda?
(@(1) 1).test;
test2(@(1) 1, @(2) "test");
test!(int)(@(1) 1);
test2!(int, string)(@(1) 1, @(2) "test");
}


Re: Recursive attribute for virtual functions?

2018-03-27 Thread arturg via Digitalmars-d

On Tuesday, 27 March 2018 at 23:34:20 UTC, arturg wrote:

On Tuesday, 27 March 2018 at 23:23:38 UTC, ag0aep6g wrote:


DMD might accept that, but I don't think it works in a 
meaningful way. How do you call the @system one?


Looks like the @safe one will always be called, even from 
@system code:



import std.stdio;

void talk() @system { writeln("@system"); }
void talk() @safe { writeln("@safe"); }

void main() @system
{
talk(); /* Prints "@safe". */
}



you can call them with __traits(getOverloads, T, "name")[index];

you can overload on types attributes and linkage, but seems 
like you can only merge overloads based on types.


i have some templates which can be used like this:

type.dgAt!("name", index);
dgAt!("name", index, somemodule);
dgAt!("name", index, "somemodule");
alias fun = aAt!("name", index, someTypeOrModule);

type.dgOf!("name", void function(int)@safe);
dgOf!("name", void function(int)@safe, module);
dgOf!("name", void function(int)@safe, "module");

from!(type, "name").aAt!1;
from!(type, "name").aOf!(void function(int));
from!(type, "name").dgAt!1;
from!(type, "name").dgOf!(void function(int));

but this fails:
type.dgOf!("name", extern(C) void function(int)@safe);

and this works:
alias funtype = extern(C) void function(int)@safe;
type.dgOf!("name", funtype);


Re: Recursive attribute for virtual functions?

2018-03-27 Thread arturg via Digitalmars-d

On Tuesday, 27 March 2018 at 23:23:38 UTC, ag0aep6g wrote:


DMD might accept that, but I don't think it works in a 
meaningful way. How do you call the @system one?


Looks like the @safe one will always be called, even from 
@system code:



import std.stdio;

void talk() @system { writeln("@system"); }
void talk() @safe { writeln("@safe"); }

void main() @system
{
talk(); /* Prints "@safe". */
}



you can call them with __traits(getOverloads, T, "name")[index];

you can overload on types attributes and linkage, but seems like 
you can only merge overloads based on types.


Re: Recursive attribute for virtual functions?

2018-03-27 Thread arturg via Digitalmars-d

On Tuesday, 27 March 2018 at 21:25:33 UTC, ag0aep6g wrote:

On 03/27/2018 11:10 PM, 12345swordy wrote:

Shouldn't it give a warning then?


I wouldn't mind a warning, or even an error. Putting both @safe 
and @system directly on a function is an error, too.


shouldn't it create a overload?
for example this fails:

class A
{
void talk()@safe {}
}

class B : A
{
alias talk = A.talk;
void talk()@system {}
}

but this works:

class A
{
void talk() {}
}

class B : A
{
alias talk = A.talk;
void talk(int) {}
}

this works also:

class C
{
void talk()@system {}
void talk()@safe {}
}


Re: Help with specific template function

2018-03-26 Thread arturg via Digitalmars-d-learn
On Monday, 26 March 2018 at 06:40:34 UTC, Vladimirs Nordholm 
wrote:

How would I resolve this issue?


use the type not the variables:
isNumeric!X && isNumeric!Y


Re: how to make private class member private

2018-03-17 Thread arturg via Digitalmars-d-learn

On Saturday, 17 March 2018 at 14:16:19 UTC, bauss wrote:
I don't like the name @deny, personally I would rather see the 
private attribute changed to something like:


private(true) // The member is oly visible to its parent.

private(false) // Same as just "private", visible to whole 
module.


Could be specialized to something like:

private(this) // Same as private(true)

private(module) // Same as private(false)



maybe extend that to a list of types?

private(typeof(this), Foo, Bar)

would mean only typeof(this), Foo and Bar from the same module 
have access.


Re: How give a module to a CTFE function

2018-03-12 Thread arturg via Digitalmars-d-learn

On Monday, 12 March 2018 at 22:34:10 UTC, Xavier Bigand wrote:


Ok, it works with the alias, I didn't see the last () in the 
implementFunctionsOf prototype.


Thank you a lot.


no problem. :)


Re: How give a module to a CTFE function

2018-03-12 Thread arturg via Digitalmars-d-learn

On Monday, 12 March 2018 at 22:28:30 UTC, Xavier Bigand wrote:


I forgot to precise, that I don't have a main, because I am 
trying to create an opengl32.dll. This is why I already have a 
mixin to inject to function definitions in the root scope.


you have to pass the string as a template arg so make 
implementFunctionsOf a template:


string implementFunctionsOf(string mod)()
{
}

then mix it in somewhere you want:

mixin(implementFunctionOf!"std.stdio");




Re: How give a module to a CTFE function

2018-03-12 Thread arturg via Digitalmars-d-learn

On Monday, 12 March 2018 at 21:00:07 UTC, Xavier Bigand wrote:

Hi,

I have a CTFE function that I want to make more generic by 
given it a module as parameter.



My actual code looks like :

mixin(implementFunctionsOf());


string implementFunctionsOf()
{
import std.traits;

string  res;

foreach(name; __traits(allMembers, myHardCodedModule))
{
}
return res;
}


I tried many things but I can't figure out the type of the 
parameter I should use for the function implementFunctionsOf.


you can use a alias or a string:

void fun(alias mod, string mod2)()
{
foreach(m; __traits(allMembers, mod))
pragma(msg, m);

foreach(m; __traits(allMembers, mixin(mod2)))
pragma(msg, m);
}

void main()
{
import std.stdio;
fun!(std.stdio, "std.stdio");
}


context pointer breaks getOverloads, shouldn't it be ignored by it?

2018-03-12 Thread arturg via Digitalmars-d-learn

void main()
{
class Foo
{
void fun(){}
}

foreach(m; __traits(allMembers, Foo))
foreach(sym; __traits(getOverloads, Foo, m))
{
}
}

this fails with:

onlineapp.d(9): Error: no property this for type 
onlineapp.main.Foo

onlineapp.d(9): Error: (Foo).this cannot be resolved

it works fine if i add a `static if(m != "this")` or 
alternatively use std.meta.Erase("this", __traits(allMembers, 
Foo)).


Re: is it possible to put some DDOC after auto generated blocks like unittest examples?

2018-03-05 Thread arturg via Digitalmars-d-learn

On Monday, 5 March 2018 at 14:50:54 UTC, Adam D. Ruppe wrote:
No, ddoc does not support that. You might be able to hack it 
with javascript though.


thanks, yeah eigther that or a d script to do some 
postprocessing, so it can work without javascript.


is it possible to put some DDOC after auto generated blocks like unittest examples?

2018-03-04 Thread arturg via Digitalmars-d-learn

///
void fun(){}

///$(TABLE $(TR $(TD Back to:) $(TD href="#fun">Declaration) $(TD $(LINK2 #top, Top

unittest
{

}

it basically should look like this:

Declaration
void fun()

Example
---

---
[Back to:] [Declaration] [Top]


and if i replace the embbeded html with $(LINK2 #fun, 
Declaration) inside the doc comment of the function it produses 
wrong html.


Re: isInputRange copied verbatim produces a different result than isInputRange from std.range

2018-03-04 Thread arturg via Digitalmars-d-learn

On Sunday, 4 March 2018 at 21:47:43 UTC, Jonathan M Davis wrote:
On Sunday, March 04, 2018 21:03:23 arturg via 
Digitalmars-d-learn wrote:


isn't this what DIP 1005 tried to solve?


No. What DIP 1005 was trying to solve was avoiding having to 
have imports used by your function signature or template 
constraint on top-level constructs be available to the entire 
module. It wanted the imports to only kick in when the symbol 
that needed them was used. So, it would be possible to then 
import isInputRange as part of a function that needed it in its 
template constraint without the rest of the module seeing that 
import, whereas right now, such an import would have to be at 
the top level and would affect the entire module. DIP 1005 
didn't do anything to make it so that other modules could see 
what you imported, and I doubt that any DIP ever would, because 
if that were possible, it would cause function hijacking, 
because you could force other modules to import what you wanted 
instead of what the person who wrote them imported.


- Jonathan M Davis


hm yeah i hoped that dip 1005 would be introspectable so you 
could use it instead of relying on udas.


Re: Get function argument name?

2018-03-04 Thread arturg via Digitalmars-d-learn

On Sunday, 4 March 2018 at 21:03:04 UTC, JN wrote:

Imagine a function like this:

void printValue(T)(string name, T value)
{
  writeln(name, " = ", value);
}

int x = 10;
printValue("x", x);

is it somehow possible to convert that printValue into a mixin 
or something, so I could do something like:


printValue(x);

and it will figure out the "x" part automatically?


you can pass it by alias:

import std.stdio;

void main(string[] args)
{
int x;
printName!(x);
}

void printName(alias var)()
{
writeln(__traits(identifier, var), " ", var);
}



Re: isInputRange copied verbatim produces a different result than isInputRange from std.range

2018-03-04 Thread arturg via Digitalmars-d-learn

On Sunday, 4 March 2018 at 19:58:14 UTC, ag0aep6g wrote:

On 03/04/2018 08:54 PM, aliak wrote:
wait a minute... so I can't use any std.range functions on a 
type if I add the range primitives as free functions? O.o


Yes. In other words: You can't implement range primitives as 
free functions. Because std.range (and std.algorithm, etc.) 
doesn't know about them.


isn't this what DIP 1005 tried to solve?

as long as you dont want to role your own test its not possible.

module moda;

struct Imports
{
string importString;
}

template isInputRange(R)
{
import std.traits: hasUDA, getUDAs, ReturnType;

static if(hasUDA!(R, Imports))
static foreach(u; getUDAs!(R, Imports))
mixin(u.importString);

enum bool isInputRange =
is(typeof(R.init) == R)
&& is(ReturnType!((R r) => r.empty) == bool)
&& is(typeof((return ref R r) => r.front))
&& !is(ReturnType!((R r) => r.front) == void)
&& is(typeof((R r) => r.popFront));
}

-

module test;

import std.stdio;
import moda;

void main(string[] args)
{
isInputRange!Type.writeln;
}

bool empty(Type t) { return true; }
int front(Type t) { return 42; }
void popFront(Type t) {}

@Imports("import test: empty, front, popFront;")
struct Type
{
}




Re: importing std.array: empty in a struct messes things up

2018-03-04 Thread arturg via Digitalmars-d-learn

On Sunday, 4 March 2018 at 20:07:06 UTC, visitor wrote:

On Sunday, 4 March 2018 at 19:53:59 UTC, ag0aep6g wrote:

On 03/04/2018 08:45 PM, ag0aep6g wrote:
I don't know what's going on here. The error message doesn't 
make sense to me. Might be a bug in the compiler.


This one works:


struct Stack(T) {
T[] stack;
alias stack this;
bool empty() {return empty(stack);} /* not using UFCS */
import std.array: empty; /* has to come after the method */
}


Looks very much like a compiler bug now. As far as I know, the 
order of declarations shouldn't have an effect like that in 
structs. And UFCS should also be ok there, as far as I can 
tell.


?
https://run.dlang.io/is/Ws0qEx
https://run.dlang.io/is/Bancgx


struct Stack(T) {
import std.array: empty;
T[] stack;
alias stack this;
bool empty() { return empty(stack); }
}

void main()
{
Stack!int stack;
//bool x = stack.empty; // fails
bool x = stack.empty(); // works
}


Re: importing std.array: empty in a struct messes things up

2018-03-04 Thread arturg via Digitalmars-d-learn
I had the same issue, happens with any conflicting selective 
import.


It seems to work if you dont use selective imports, but importing 
it inside the function if possible is a better option.


Re: Opt-in non-null class references?

2018-03-03 Thread arturg via Digitalmars-d

On Saturday, 3 March 2018 at 18:28:42 UTC, aliak wrote:

On Friday, 2 March 2018 at 19:47:23 UTC, SimonN wrote:

If you know of other ways though I'm all ears :)

Cheers


maybe not exactly what you want, but here are some templates i 
wrote a while ago which basically are a more flexible form of the 
?. operator.


https://run.dlang.io/gist/598c59506699a0f81c3abbbaf7d5feee?compiler=dmd


Re: Traits redux

2018-03-03 Thread arturg via Digitalmars-d-learn

On Saturday, 3 March 2018 at 16:20:57 UTC, JN wrote:

https://run.dlang.io/gist/ec7008372d60ac52460dd58068f1ca6d?compiler=dmd

Why only listUDA2 works and listUDA doesn't? Why do I need to 
use __traits(getMember again, if I use what I saved in a 
variable, it doesn't work :(


because getUDAs returns only instantiations and ignores templates
and scince hasUDA or getSymbolsByUDA uses it non of them work 
anymore. :(


based on run.dlang.io it worked with dmd 2.071.2


Re: confused with data types

2018-02-18 Thread arturg via Digitalmars-d-learn

On Sunday, 18 February 2018 at 13:08:09 UTC, thorstein wrote:

On Sunday, 18 February 2018 at 12:51:04 UTC, thorstein wrote:

// Solution 1
foreach(row; arr)
{ foreach(col; row)
  { col[] *= skalar;
  }
}
return arr;

// Solution 2
import std.array;
return array(arr.map!(b => array(b[].map!(c => 
array(c[].map!(d => d * skalar));


// Solution 3
import std.algorithm;
arr.each!(a => a[].each!(b => b[] *= skalar));
return arr;

Q#1:
Does the compiler optimizes all solutions equally strong or 
does it prefer implementations like solution 1?


Q#2:
Solution 2 is a 1-liner but a bit harder to read. Why reducing 
solution 3 to:

return arr.each!(a => a[].each!(b => b[] *= skalar));
gives a compile error? I do writeln() the function result.

Q#3:
If I can:
static import std.array;
return std.array.array(arr.map!(b => 
std.array.array(b[].map!(c =>...


How would I apply a similar version with 'static import 
std.algorithm' to solution 3?

static import std.algorithm;
std.algorithm.arr.each!(a => a[]... //does obviously not work

Thanks, thorstein


Sorry, Solution 2 should be:

import std.array;
return array(arr.map!(b => array(b[].map!(c => c[] *= 
skalar;


and is as readable as Solution 3. However, Q#2 still remains.


Q#1: i would guess solution 1 would be the fastest and solution 2 
the slowest.

Q#2: you get a error because each returns void.
Q#3: you cant use ufcs with static imports, you have to call the 
function normaly:

static import algo = std.algorithm;
algo.each!((a) => algo.each!((b) => b[] *= skalar)(a))(arr);



Re: confused with data types

2018-02-17 Thread arturg via Digitalmars-d-learn

double[][] skalar_m_2d(double[][] arr, double skalar)
{
import std.algorithm;
// return arr.map(a=> a[] *= skalar).array;
arr.each!((ref a) => a[] *= skalar));
return arr;
}



Re: is this a bug with writeln / std.algorithm.remove?

2018-02-16 Thread arturg via Digitalmars-d-learn
On Friday, 16 February 2018 at 13:57:07 UTC, Steven Schveighoffer 
wrote:


You have a pretty good minimal test, put that in bugzilla along 
with the forum thread link and all the info we know. Mark it as 
a dmd bug, regression, along with the version where it 
regressed (2.076.1), and I would tag it as "rejects-valid"


-Steve


ok done
https://issues.dlang.org/show_bug.cgi?id=18451


Re: is this a bug with writeln / std.algorithm.remove?

2018-02-16 Thread arturg via Digitalmars-d-learn
On Friday, 16 February 2018 at 13:28:59 UTC, Steven Schveighoffer 
wrote:


Strictly speaking, this is not necessarily proof that it's in 
phobos, there could have been changes elsewhere that cause one 
of the conditions to fail.


However, testing this out, I found something very weird.

If you pragma(msg, isInputRange!(typeof(dgs))); inside your 
file, then it compiles (and prints true for that pragma).


Makes no sense at all. Definitely seems like a compiler bug. A 
pragma(msg) shouldn't affect the outcome.


-Steve


ok so what should the bug report look like?


Re: is this a bug with writeln / std.algorithm.remove?

2018-02-16 Thread arturg via Digitalmars-d-learn

On Friday, 16 February 2018 at 11:45:21 UTC, arturg wrote:

this code fails to compile:

void delegate(void*) dg;
void delegate(void*)[] dgs = [dg, dg, dg];
dgs.writeln;
dgs.remove(1).writeln();

if you comment out dgs.writeln; it works as expected,
it works if you use other types then void*:

void delegate(int*) dg;
void delegate(int*)[] dgs = [dg, dg, dg];
dgs.writeln;
dgs.remove(1).writeln();


the compiler is DMD64 D Compiler v2.078.2 and the error message 
is:


/usr/include/dlang/dmd/std/algorithm/mutation.d(1929): Error: 
template std.algorithm.mutation.moveAll cannot deduce function 
from argument types !()(void delegate(void*)[], void 
delegate(void*)[]), candidates are:
/usr/include/dlang/dmd/std/algorithm/mutation.d(1455):
std.algorithm.mutation.moveAll(InputRange1, 
InputRange2)(InputRange1 src, InputRange2 tgt) if 
(isInputRange!InputRange1 && isInputRange!InputRange2 && 
is(typeof(move(src.front, tgt.front
empty.d(9): Error: template instance 
std.algorithm.mutation.remove!(cast(SwapStrategy)2, void 
delegate(void*)[], int) error instantiating


running all dmd version on run.dlang.io
gives me this output:

Up to  2.075.1: Success with output:
-
[void delegate(void*), void delegate(void*), void delegate(void*)]
[void delegate(void*), void delegate(void*)]
-

Since  2.076.1: Failure with output:
-
/path/to/dmd.linux/dmd2/linux/bin64/../../src/phobos/std/algorithm/mutation.d(1929):
 Error: template std.algorithm.mutation.moveAll cannot deduce function from 
argument types !()(void delegate(void*)[], void delegate(void*)[]), candidates 
are:
/path/to/dmd.linux/dmd2/linux/bin64/../../src/phobos/std/algorithm/mutation.d(1455):
std.algorithm.mutation.moveAll(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt) if 
(isInputRange!InputRange1 && isInputRange!InputRange2 && 
is(typeof(move(src.front, tgt.front
onlineapp.d(7): Error: template instance 
std.algorithm.mutation.remove!(cast(SwapStrategy)2, void 
delegate(void*)[], int) error instantiating

-



is this a bug with writeln / std.algorithm.remove?

2018-02-16 Thread arturg via Digitalmars-d-learn

this code fails to compile:

void delegate(void*) dg;
void delegate(void*)[] dgs = [dg, dg, dg];
dgs.writeln;
dgs.remove(1).writeln();

if you comment out dgs.writeln; it works as expected,
it works if you use other types then void*:

void delegate(int*) dg;
void delegate(int*)[] dgs = [dg, dg, dg];
dgs.writeln;
dgs.remove(1).writeln();


the compiler is DMD64 D Compiler v2.078.2 and the error message 
is:


/usr/include/dlang/dmd/std/algorithm/mutation.d(1929): Error: 
template std.algorithm.mutation.moveAll cannot deduce function 
from argument types !()(void delegate(void*)[], void 
delegate(void*)[]), candidates are:
/usr/include/dlang/dmd/std/algorithm/mutation.d(1455):
std.algorithm.mutation.moveAll(InputRange1, 
InputRange2)(InputRange1 src, InputRange2 tgt) if 
(isInputRange!InputRange1 && isInputRange!InputRange2 && 
is(typeof(move(src.front, tgt.front
empty.d(9): Error: template instance 
std.algorithm.mutation.remove!(cast(SwapStrategy)2, void 
delegate(void*)[], int) error instantiating


Re: Dscanner - DCD - Dfix ... Editor support or the lack of it.

2018-01-28 Thread arturg via Digitalmars-d
On Sunday, 28 January 2018 at 17:51:19 UTC, Jonathan M Davis 
wrote:


Hmm. Thanks. I'll have to check that out. I haven't done 
anything with folds in ages.


Fortunately, I don't have to do anything with python right now 
though. The main reason that I used it before was so that I 
could have cross-platform scripts at a previous job when I 
couldn't use D (if it were for use by more than just me, I 
couldn't use D, because no one else in my group was doing 
anything with D and it wasn't part of our build system) - that 
and even if I had to write something Windows-specific, writing 
it in Python was worlds better than writing it in batch.


Right now, I'm able to use D for work, so I'm much more likely 
to just write scripts in D.


- Jonathan M Davis


in C++ you have header files as an overview of a type in D and 
other languages you can use code folding when you dont use any 
plugins.


Re: Dscanner - DCD - Dfix ... Editor support or the lack of it.

2018-01-28 Thread arturg via Digitalmars-d
On Sunday, 28 January 2018 at 16:02:36 UTC, Jonathan M Davis 
wrote:


Erm, you do realize that Vim has built-in commands for 
navigating nested brackets and parentheses, right? And 
automatic bracket closing is just a macro away. You don't even 
need a plugin for that.


LOL. One of the reasons that I hate python is that I can't hop 
between braces in it in vim, because it has no braces. It makes 
jumping from the top of a function to the bottom a lot harder. 
Even Pascal has begin and end (which I found out that vim 
understands when I was mucking around with some stuff in Pascal 
several months ago).




if you set foldmethod=indent in vim  you can navigate to the top 
or bottom of the fold with [z and ]z, or check help fold-commands.


Re: Struct initialization syntax

2018-01-17 Thread arturg via Digitalmars-d-learn

On Wednesday, 17 January 2018 at 17:37:07 UTC, H. S. Teoh wrote:
On Wed, Jan 17, 2018 at 05:31:03PM +, Azi Hassan via 
Digitalmars-d-learn wrote:
The D tour for structs uses a syntax similar to that of C++ in 
order to initialize a Person struct : Person p(30, 180). Is 
this syntax supported in D ? Running that part of the code 
neither works on the playground nor on my machine (dmd 
v2.076.0).


You're probably looking for this syntax:

auto p = Person(30, 180);


T


looks like a bug in the 3rd example.


Re: Detect if variable defined

2017-09-29 Thread arturg via Digitalmars-d-learn

On Friday, 29 September 2017 at 18:03:52 UTC, Joseph wrote:

static if ()
{
 enum x;
}

static if (isDefined!x)
{
}

What's the correct way to check if a variable has been defined? 
(note x may or may not be defined above. I need to know if it 
is)


import std.traits;
static if(hasMember!(T, "x"))
{
}

or if at module level

static if(__traits(hasMember, mixin(__MODULE__), "x"))
{
}


Re: no print function output do while

2017-09-28 Thread arturg via Digitalmars-d-learn

On Thursday, 28 September 2017 at 20:17:24 UTC, Ali Çehreli wrote:

On 09/28/2017 12:18 PM, dark777 wrote:
On Thursday, 28 September 2017 at 18:46:56 UTC, Ali Çehreli 
wrote:

On 09/28/2017 08:13 AM, dark777 wrote:

no print function output do while

in my program after entering the data and select the 
function that will print on the screen the same is not 
printing ..


and if I choose 'q' or 'Q' does the program not close what 
is happening?

should not it work just like in C ++?

https://pastebin.com/iiMVPk4x


You made a simple logic error. Change the following || to &&:

    }while(choice != 'q' || choice != 'Q');

Ali


I think it should not give this error

good but until now I do not understand why after I enter with 
data in the function add_human


the same is not printed when I choose the 'p' or 'P' option in 
the case


void print_list(Human[] human_list)
{
  foreach(human; human_list)
    {
     writefln("\nNome: %s",human.name);
     writefln("Peso: %0.2f",human.peso);
     writefln("Idade: %d\n",human.age);
    }
}


It's because add_human is appending to its own array. Change it 
to by-ref:


void add_human(ref Human[] human_list)

Ali


while(choice != 'q' || choice != 'Q');
doesn't seem to exit the loop, while this works:
while(choice != 'q');
or
while(!(choice == 'q' || choice == 'Q'));

wouldn't it be better to use a labeled statement instead?

endless : while(true)
{
...

switch(choice)
{
...

case 'Q':
case 'q': break endless;

...
}
}


Re: Base class' constructor is not implicitly inherited for immutable classes. A bug or a feature?

2017-07-20 Thread arturg via Digitalmars-d-learn

On Wednesday, 19 July 2017 at 16:00:56 UTC, Piotr Mitana wrote:

Hello, I have this code:

immutable class Base
{
this() {}
}

immutable class Derived : Base {}

void main()
{
new immutable Derived();
}

I'd like class Derived to automatically inherit the default 
constructor from Base. However, this is not the case:


main.d(6): Error: class main.Derived cannot implicitly generate 
a default ctor when base class main.Base is missing a default 
ctor


Is it a bug or it should be like this?


compiles with:
dmd 2.073

fails with:
dmd 2.074
dmd 2.075


Re: Project Highlight: Derelict

2017-06-26 Thread arturg via Digitalmars-d-announce

On Monday, 26 June 2017 at 14:30:13 UTC, Mike Parker wrote:
I've just published a wall of text about Derelict. I don't 
think I've ever written so much about it in one sitting, so it 
was a fun post to write. As well as (the reminder of how fast 
time is slipping away aside) a nice walk down memory lane.


The Blog:
https://dlang.org/blog/2017/06/26/project-highlight-derelict/

Reddit:
https://www.reddit.com/r/programming/comments/6jldos/derelict_a_collection_of_d_bindings_to_c_libraries/


s/you don't tend find/you don't tend to find/

s/As the D has evolved/As D has evolved/


Re: Generic operator overloading for immutable types?

2017-06-12 Thread arturg via Digitalmars-d-learn

On Monday, 12 June 2017 at 19:51:37 UTC, Gary Willoughby wrote:
I don't know how H. S. Teoh managed to answer 'before' I posted 
but thanks guys! :)


might be a bug, happened here 
http://forum.dlang.org/post/ohbr5l$2mng$1...@digitalmars.com also.


Re: new contract syntax DIP

2017-05-23 Thread arturg via Digitalmars-d

On Tuesday, 23 May 2017 at 17:28:21 UTC, MysticZach wrote:
I made a pull request for a new DIP dealing with contract 
syntax:


https://github.com/dlang/DIPs/pull/66

I write the DIP in response to the discussions for DIP 1003: 
http://forum.dlang.org/thread/wcqebjzdjxldeywlx...@forum.dlang.org


This DIP is not under any kind of formal review yet. I just 
wanted to let people know that it's there.


how about @uda based contracts?

@in(x => x < 100)
@out((ret) { assert(ret > 0, "some text"); })
int fun(int i) { return someVal; }

they could also be used on type definitions,

@out((t) { assert(t); })
 class NotNull {}

or temporarly on instances

@in(t => t !is null) auto notNull = new NotNull;

you could also have @inout as a combination.
another feature would be that they could be introspected.


Re: Problem with using readln.

2017-04-30 Thread arturg via Digitalmars-d-learn

On Sunday, 30 April 2017 at 05:53:09 UTC, Andrew Edwards wrote:

string line;
parse!int((line = readln)).writeln;



is there a reason you mix normal call and ufc or just some style?
you can do this and remove some ()

(line = readln).parse!int.writeln;


Re: DIP 1005 - Preliminary Review Round 1

2017-04-23 Thread Arturg via Digitalmars-d
On Sunday, 23 April 2017 at 12:03:47 UTC, Andrei Alexandrescu 
wrote:

On 4/22/17 4:52 PM, Joakim wrote:

On Saturday, 22 April 2017 at 11:54:08 UTC, Mike Parker wrote:

DIP 1005 is titled "Dependency-Carrying Declarations".

https://github.com/dlang/DIPs/blob/master/DIPs/DIP1005.md

All review-related feedback on and discussion of the DIP 
should occur in this thread. Due to DConf taking place during 
the review period, the period will be extended by a week. The 
review period will end at 11:59 PM ET on May 13 (3:59 AM GMT 
on May 14), or when I make a post declaring it complete.


At the end of Round 1, if further review is deemed necessary, 
the DIP will be scheduled for another round. Otherwise, 
because the DIP comes from a language author and no formal 
review period by the language authors is necessary, the DIP 
will be marked "Accepted" or "Rejected" at the author's 
discretion.


An extensive discussion regarding this DIP has already taken 
place [1].


Thanks in advance to all who participate.

Destroy!

[1] 
http://forum.dlang.org/thread/o2psvk$1m96$1...@digitalmars.com?page=1


I thought this DIP was invalidated by the self-important 
workaround?


http://forum.dlang.org/post/o72kq8$ggc$1...@digitalmars.com

https://github.com/dlang/druntime/pull/1756#issuecomment-277463742

Why is this still up for review?


Mostly out of a sense of conformity. We asked Michael to give 
no special treatment of DIPs originating from us, and this one 
was open, so he put it up for review. It is likely it will end 
up rejected in favor of 
https://github.com/dlang/druntime/pull/1756.



Thanks,

Andrei


this example doenst work with the from!"modName" template, would 
it work with dip1005?


module moda;

struct Foo{int i;}

module modb;

void fun(from!"moda".Foo){}

module app;

template test(alias f)
{
mixin("void test(" ~ 
from!"std.traits".Parameters!f.stringof[1..$-1] ~ "){}");

}

void main()
{
import moda, modb;
test!fun(Foo(5));
}

could dip1005 be introspected?

// you can make the above work with this or is there a better way?
template test(alias f)
{
import traits;
enum paramImports =
{
string res;
foreach(p; Parameters!f)
{
   static if(!isBuiltinType!p) res ~= "import " ~ 
moduleName!p ~ ";\n";

}
return res;
}();

mixin(paramImports);
mixin("void test(" ~ Parameters!f.stringof[1..$-1] ~ "){}");
}


Re: DIP10005: Dependency-Carrying Declarations is now available for community feedback

2016-12-30 Thread ArturG via Digitalmars-d
On Friday, 30 December 2016 at 23:49:23 UTC, Andrei Alexandrescu 
wrote:


The main win, which indeed is not emphasized enough, is better 
encapsulation. Walter pointed that out, and I will redo the DIP 
to put that front and center.


Maybe i can provide an example where i think DCD's would be 
usefull.
Im experimenting with a more Qt like signals and slots 
implementation,
it introspects some type for function declarations with the 
@("Signal") uda

and mixes them into the current type.
It currently looks like this:

// moda.d
interface TestSignals
{
   import modb: TestType;
   @("Signal"):
  void someTestSig(TestType);
}

// modb.d
struct TestType{}

// test.d
class A : SignalObject
{
   import moda: TestSignals;
   import modb: TestType; // has to be manually imported for the 
generated signal


   mixin signalsOf!(SignalList, TestSignals);

   interface SignalList
   {
  @("Signal"):
 void foo(int);
 void bar(string, int = 100);
 int bar(int a, int b);
   }

   void someFun(string s) { s.writeln; }
}

class B : SignalObject
{
   struct SignalList
   {
  @("Signal"):
 void someSig(string);
   }

   mixin signalsOf!SignalList;

   void fooHandler(int i){ i.writeln; }

   int onBar(int a, int b){ writeln(a + b); return a + b; }
   void onBar(string s, int i){ writeln(s, i); }

   import modb: TestType;
   void someTestSigHandler(TestType t){ t.writeln; }
}

class C : SignalObject
{
   import modb: TestType; // has to be manually imported for the 
generated signal


   mixin signalsOf!(A, B);

   // i wanted to support string based signal declaration
   // but that would require double manual import declarations

   // import modb: TestType;

   // enum signalList =
   // q{
   //import modb: TestType;
   //@("Signal"):
   //void someSig(TestType);
   //int someOtherSig();
   // }

   // mixin signalsOf!signalList;
}

void main(string[] args)
{
   auto a = new A;
   auto b = new B;
   auto c = new C;

   a.connect!"foo"();
   a.connect(b); // connect all bar's with all onBar's

   a.foo(66);
   a.bar("asd");
   a.bar(4, 6);

   c.connect!"someSig"();
   b.connect!"someSig"();

   c.someSig("emitted by c forwarded by b handled by a");

   a.connect!"someTestSig"();
   c.connect!"someTestSig"();

   import modb: TestType;
   TestType t;
   a.someTestSig(t);
   c.someTestSig(t);
}

i assume with DCD's i could remove those manual imports if they 
get some traits.





Re: DIP10005: Dependency-Carrying Declarations is now available for community feedback

2016-12-15 Thread ArturG via Digitalmars-d
On Thursday, 15 December 2016 at 19:52:50 UTC, Andrei 
Alexandrescu wrote:

On 12/15/2016 02:22 PM, Timothee Cour via Digitalmars-d wrote:

Some more details on my proposa based on UDA:

...


I now understand the idea, thank you.

My question is, doesn't this take things too far? Earlier I 
wrote:



The acceptability of the proposal decays exponentially with its
deviation from existing import syntax.


Indeed adding less syntax is better, but that's not an 
absolute; the optimum isn't necessarily at the "zero syntax 
added" point. This is because there are several things to 
harmonize in language design, which naturally are in tension.



Andrei


Something like Timothee Cour's @deps proposal is interesting,
because it adds the same options to DCD's as module level imports 
have.


They can be applied to any symbol that supports udas which the 
current syntax from the dip doesnt.


As he displayed, they can be used to group symbols together which 
makes it more dry, but that can also be a drawback when 
refactoring depending which version you use.


And you dont have to support all shown features as that syntax is 
easier extendable.


The initial version could support only import statements.


Re: DIP10005: Dependency-Carrying Declarations is now available for community feedback

2016-12-14 Thread arturg via Digitalmars-d
On Wednesday, 14 December 2016 at 22:56:54 UTC, Andrei 
Alexandrescu wrote:


The acceptability of the proposal decays exponentially with its 
deviation from existing import syntax. -- Andrei


sorry, i missed the import keyword :/

T1 fun(T1, T2)(T1 t1, T2 t2)
import
{
 version(A)
 { import someMod: T1, T2; }
 else
 { import someOtherMod: T1, T2;}

 import std.stdio;

// this import block would support only import statemens, version 
and static if etc...


}
{
 t2.writeln;  // use symbols imported by the import block
 T1 ret = t1 + t2;
 return ret;
}


Re: DIP10005: Dependency-Carrying Declarations is now available for community feedback

2016-12-14 Thread ArturG via Digitalmars-d
On Wednesday, 14 December 2016 at 19:39:55 UTC, Andrei 
Alexandrescu wrote:

On 12/14/2016 02:04 PM, Meta wrote:
On Wednesday, 14 December 2016 at 17:32:10 UTC, H. S. Teoh 
wrote:

What about:

/* Showing full declaration just for context */
bool myFunc(R1, R2)(R1 r1, R2 r2)
import {
std.range : isInputRange,
std.traits : isNum = isNumeric
}
if (isInputRange!R1 && isInputRange!R2 &&
isNum!(ElementType!R1))
in { assert(someCondition!R1); }
out(result) { assert(result == expectedResult(...)); }
body
{
...
}



as ketmar said, would the import block have any restrictions what 
code could be used inside, would this work?


T1 fun(T1, T2)(T1 t1, T2 t2)
import
{
version(A) { someMod: T1, T2; }
else { someOtherMod: T1, T2; }

// static if or any other code?
}
{
T1 ret = t1 + t2;
return ret;
}



Re: @property

2016-12-09 Thread ArturG via Digitalmars-d-learn
My issue isn't about @property, it just shows 3 cases where i 
think that dmd is missing a check for alias this.


Even if D didnt had @property or parentesis less function call,
due to alias opCall this it should be possible to call opCall 
without parentesis.




Re: @property

2016-12-08 Thread ArturG via Digitalmars-d-learn
On Thursday, 8 December 2016 at 22:46:32 UTC, Jonathan M Davis 
wrote:
On Thursday, December 08, 2016 22:11:22 ArturG via 
Digitalmars-d-learn wrote:
On Thursday, 8 December 2016 at 16:54:57 UTC, Adam D. Ruppe 
wrote:

> On Thursday, 8 December 2016 at 16:53:13 UTC, Satoshi wrote:
>> is there any advantage of marking function as @property??
>
> Not really. I think it just changes the meaning of
> typeof(thatfunc) but otherwise it does nothing.
>
> However, if you use it in a base class, you must also use it 
> when overriding the function.


it does when you add it to for example a struct with alias 
opCall

this.
reported it as a bug
https://issues.dlang.org/show_bug.cgi?id=16951

but seems to be addressed by https://wiki.dlang.org/DIP23


...

- Jonathan M Davis


i actually didnt want to use @property at all, as i asumed that 
by using alias opCall this it would always call opCall not only 
sometimes.


the issue was about the commented line
// a; // Error: var has no effect in expression (a)

the rest can be solved by @property or a custom toString.


Re: @property

2016-12-08 Thread ArturG via Digitalmars-d-learn

On Thursday, 8 December 2016 at 16:54:57 UTC, Adam D. Ruppe wrote:

On Thursday, 8 December 2016 at 16:53:13 UTC, Satoshi wrote:

is there any advantage of marking function as @property??


Not really. I think it just changes the meaning of 
typeof(thatfunc) but otherwise it does nothing.


However, if you use it in a base class, you must also use it 
when overriding the function.


it does when you add it to for example a struct with alias opCall 
this.

reported it as a bug
https://issues.dlang.org/show_bug.cgi?id=16951

but seems to be addressed by https://wiki.dlang.org/DIP23


wrong result from ParameterStorageClassTuple?

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

alias PSC = ParameterStorageClass;
alias PSCT = ParameterStorageClassTuple;

void fun1(return ref int){}
void fun2(return out int){}

PSCT!fun1 == (PSC.return_ | PSC.ref_) // false
PSCT!fun2 == (PSC.return_ | PSC.out_) // false

PSCT!fun1 == PSC.return_ // true
PSCT!fun2 == PSC.return_ // true

how to differentiate them?


Re: @property get/set or public varaible?

2016-12-05 Thread ArturG via Digitalmars-d-learn
On Sunday, 4 December 2016 at 20:44:05 UTC, Jonathan M Davis 
wrote:
On Sunday, December 04, 2016 15:30:22 vladdeSV via 
Digitalmars-d-learn wrote:

Hello!

I have a question not directly related to D as it is with 
coding standards.


My issue at hand is if I have one variable for a class, which I
want to be directly accessible for anything else, should it be
  1. public, or
  2. private, with @property get/setters?

 From what I have been told is that variables should be 
private.
But if I do not want to make any checks whatsoever when 
setting a

variable, I see no benefit to the private approach.

Are there any other reasons to use get/setters?





This might not be usefull for ure current usecase but if you want 
a property to behave like a field, it has to be a field.
So a boxed type might be better depending how much you want to 
manage.

Here are some property like examples:

   struct Prop(T)
   {
  private T value;

  alias opCall this;
  ref T opCall() { return value; }
  ref T opCall(T val) { return value = val; }
  string toString() { import std.conv: to; return 
value.to!string; }

   }

   struct ReadOnly(T)
   {
  private T value;

  alias opCall this;
  T opCall() { return value; } // return a copy
  string toString() { import std.conv: to; return 
value.to!string; }

   }

   struct WriteOnly(T)
   {
  private T value;

  void opAssign(T val) { value = val; }
  string toString() { return typeof(this).stringof; }
   }

// alternative write only so you can chain opCall 
writeOnly(33)(56)(66);

struct AltWriteOnly(T)
   {
  private T value;

  ref typeof(this) opCall(T val) { value = val; return this; }
  string toString() { return typeof(this).stringof; }
   }

   struct FunProp(T) if(isSomeFunction!T)
   {
  private T value;

  alias value this;
  void opAssign(T val) { value = val; }
  string toString() { return T.stringof; }
   }


   class Test
   {
   Prop!int someVal;
   ReadOnly!string name;
   WriteOnly!int someOtherVal;
   FunProp!(void delegate(int)) funProp;

   this()
   {
   name.value = "Test";
   }
   }

   void main()
   {
   auto test = new Test;
   test.someVal = 66;
   test.someVal++;
   test.someOtherVal = 100;
   test.funProp = (int i) => i + test.someVal;
   test.someVal.writeln;
   test.name.writeln;
   test.funProp(33).writeln;
   test.funProp.writeln;
   test.someOtherVal.writeln;
   }

haven't done extencive tests with them but they can be used as 
builing blocks, you can add other operator overloads to manage 
other access to the value.

you can build better properties without @property :/


Is there some trait like getOverloads that works with mixin templates?

2016-11-26 Thread ArturG via Digitalmars-d-learn

a simple example:

mixin template v1()
{
void foo(){}
}

mixin template v2()
{
void foo(int){}
}

class Test
{
mixin v1;
mixin v2;
}

void main()
{
__traits(getOverloads, Test, "foo").length.writeln; // 0
}

i know you can use alias to manually make them visible for 
getOverloads.
but i could use a automated way, at least for unnamed template 
mixins

or to be able to merge all into the same named mixin scope.

is there a way to do this?


Re: If Statement with Declaration

2016-11-07 Thread ArturG via Digitalmars-d

On Thursday, 3 November 2016 at 22:29:34 UTC, Jerry wrote:


So I was thinking of a way of extending if statements that have 
declarations. The following being as example of the current use 
of if statements with declarations:


if(int* weDontPollute = someFunc())
{
 // use weDontPollute
}

That's great and all, but it only works by checking if the 
variable evaluates to true or false. Which is fine for a 
pointer but otherwise useless for anything else, like integers 
where zero is usually valid input (index for array). So 
currently the only way to do something like this in the 
language, that i've found, is to use a for statement.


for(int i = someFunc(); i >= 0;)
{
// use i

break;
}

Not that ideal to use a for statement. It makes it hard to read 
and if the break condition isn't there it might very well be an 
infinite loop. So I was thinking of some sort of syntax like 
this:


if(int i = someFunc(); i >= 0)
{
// use i
}
Thoughts on this sort of feature?


Hi, i refactored some templates[1] i had, so that you can provide 
your own predicate functions.


Variant 1 eager version:

auto when(alias pred, alias fun, T)(T type = T.init)

Variant 2 a lazy version, uses two templates:

auto when(alias pred, T)(T type = T.init)
auto call(alias fun, T)(T type)

check/modify the examples found here
[1] http://melpon.org/wandbox/permlink/g7V0gj4V7SGPjwqL

*OT is dpaste broken (cant seem to create new pastes) or is it 
just me?


Re: Construct D Arrray with explicit capacity

2016-10-30 Thread arturg via Digitalmars-d-learn

On Sunday, 30 October 2016 at 18:10:09 UTC, Nordlöw wrote:
Is there a recommended way to create a builtin D array with a 
given capacity?


I'm aware of the `.capacity` property.

Is it ok to mutate it?


you cant mutate capacity directly because its only a getter but 
you could use arr.reserve(someVal);


Re: Pattern matching in D?

2016-10-21 Thread ArturG via Digitalmars-d

On Friday, 21 October 2016 at 02:40:45 UTC, Stefan Koch wrote:

On Friday, 21 October 2016 at 02:16:44 UTC, Chris M. wrote:
So I know you can do some pattern matching with templates in 
D, but has there been any discussion about implementing it as 
a language feature, maybe something similar to Rust's match 
keyword (https://doc.rust-lang.org/stable/book/patterns.html)? 
What would your guys' thoughts be?


How is this diffrent from "switch-case" ?


switch is a statement, rusts match is an expression and can 
return a value.



i posted this[1] templates a while ago with which you can 
probably do most of what rust can do with the match expressing 
(not tested havent looked into rust much and pattern matching 
isnt the main purpose of them), by combining existing D features.


e.g.

5.call!(a => a == 3? "three" :
 a == 5? "five"  : "nomatch").writeln;
prints:
five

5.call!((a){ a == 3? "three".writeln :
 a == 5? "five".writeln  : null;}).writeln;
prints:
five
5


[1] http://melpon.org/wandbox/permlink/ngUYhp7SS6uY283b


Re: TryElseExpression DIP

2016-09-05 Thread arturg via Digitalmars-d

On Monday, 5 September 2016 at 18:07:52 UTC, pineapple wrote:


It works like this:

try:
do_something()
except Exception as e:
pass # Runs when an error inheriting from Exception was 
raised

else:
pass # Runs when no error was raised
finally:
pass # Runs unconditionally, evaluates last

Imitating this functionality in D,

try{
do_a_thing();
}catch(Exception exception){
handle_error();
}else{
depends_on_success_of_thing();
}finally{
do_this_always();
}

Would be equivalent to

bool success = false;
try{
do_a_thing();
success = true;
}catch(Exception exception){
handle_error();
}finally{
try{
if(success){
depends_on_success_of_thing();
}
}finally{
do_this_always();
}
}


hm, isn't this similar/same as the python version?

  try{
  doSomething();

  scope(success) "if no Exception thrown".writeln;
  }
  catch(Exception e)
  {
   ...
  }



Re: mixin template hide

2016-07-24 Thread arturg via Digitalmars-d-learn

On Sunday, 24 July 2016 at 18:38:53 UTC, Eppason wrote:



The obvious solution is to refactor Bar, but in the real world, 
it is much harder and life would be much easier if I could 
remove foo from exists inside S. At worse, if Bar did depend on 
foo, I would simply get errors about missing foo.


I doubt it is possible, but maybe some tricks?


you could define a flag for foo, like:

mixin template BAR(bool addFoo = true)
{
mixin FOO;

static if(addFoo)
{
void foo(){}
}
}



Re: Overloads

2016-06-26 Thread ArturG via Digitalmars-d-learn

On Sunday, 26 June 2016 at 11:23:14 UTC, Márcio Martins wrote:

Consider this snippet:

struct X {
  int foo(Args...)(Args args) if (Args.length > 1) { return 
Args.length; }


  int foo() { return 0; }

  int foo(int y) { return 1; }

  alias Name = string;

  int field_;
}


void listMembers(T)(ref T x) {
  foreach (Member; __traits(derivedMembers, T)) {
pragma(msg, Member, " ", __traits(getOverloads, x, 
Member).length);
//pragma(msg, __traits(getProtection, __traits(getMember, 
x, Member))); // Error: argument string has no protection

  }
}

void main() {
  X x;
  listMembers(x);
  //auto fptr =  // Error: x.foo(Args...)(Args args) if 
(Args.length > 0) is not an lvalue

}

Output:
foo 0LU
Name 0LU
field_ 0LU
foo 0LU
Name 0LU
field_ 0LU


There seems to be a few problems here:
1. It seems like getOverloads is returning 0 for 'foo' - is 
this a bug? Was expecting a 3 or at least a 2 if the template 
would be ignored.
2. That alias breaks getProtection - is this bug? Seems like it 
should be public.


These two make it quite hard to iterate over and collect info 
about arbitrary aggregates.


I want to get a list of all *public* members, including 
pointers to all public member functions and their overloads, 
excluding template member functions. This is turning out to be 
hard due to these "unexpected behaviors".


Is there anything else I can do?


__traits(getOverloads, x, Member).length works if you place the 
template after a function of the overloads and then it returns 2.


it fails as soon as the first member of the overload set is any 
template, so i guess it must be a bug.

e.g.

struct Fails
{
void foo()(){}
void foo(int){}
}

struct Works
{
void foo(int){}
void foo()(){}
}

__traits(getOverloads, Fails, "foo").length.writeln; // 0
__traits(getOverloads, Works, "foo").length.writeln; // 1


named args

2016-06-23 Thread ArturG via Digitalmars-d

http://melpon.org/wandbox/permlink/u8lpOZ9owC7QXfa3
hi, that code is based on ideas and code from this[1] thread.

some examples:

// named and in order
  args!(fun, a=>6, b=>65, s=>"test", f=>1.4);

// named and out of order   
  args!(fun, b=>65, f=>1.4, s=>"test", a=>6);

// unnamed and in order
  args!(fun, 6, 65, "test", 1.4);

// mixed and out of order
  args!(fun, b=>65, 1.4, 6, "test");

// with defaults
  args!(fun, 6, 65);
  args!(fun, s=>"some text", 6);

// setting member variables
  auto foo = new Foo().set!(my => 13, ms => "Foo", mx => 4, mf => 
1.6);


// calling static member functions
  args!(Foo.print, s=>foo.ms, f=>foo.mf, y=>foo.my, x=>foo.mx);

// calling member functions
  foo.args!(foo.someFun, 4, x=>6, "test", f=>1.99);
  foo.args!("someFun", 4, x=>6, "test", f=>1.99);


i currently don't have much time right now so havent done alot of 
tests, some issues


properly handling overloads,
calling special methods e.g. constructors, opCall
and probably more

[1] 
http://forum.dlang.org/thread/awjuoemsnmxbfgzhg...@forum.dlang.org


Re: foo => "bar" key/value literals in D!

2016-06-11 Thread ArturG via Digitalmars-d-announce
On Saturday, 11 June 2016 at 15:46:59 UTC, Vladimir Panteleev 
wrote:


Taking an address creates a function pointer, which loses the 
argument names. (Doesn't it?)


unfortunatly yes, but it works as a struct or class initializer
https://dpaste.dzfl.pl/6aad852aea90


Re: Monads in D

2016-06-11 Thread ArturG via Digitalmars-d

On Saturday, 11 June 2016 at 14:26:20 UTC, Atila Neves wrote:



Why? Because I could, I don't plan on using this for anything 
serious. I think "with" is my favourite D feature right now. I 
also wrote the Writer and State monads (not that D needs them):


https://github.com/atilaneves/felix


Atila


im not an expert but is it something similar to this idea[1] as 
it seems to be used in a similar way.


[1] 
http://forum.dlang.org/thread/ltalqpmpscdoziser...@forum.dlang.org


Re: foo => "bar" key/value literals in D!

2016-06-11 Thread ArturG via Digitalmars-d-announce
On Saturday, 11 June 2016 at 09:07:43 UTC, Andrei Alexandrescu 
wrote:


No, both are nice to have. If one name is needed for both, 
"args" is indeed a good commonality. "Invoke function f with 
these args" and "Construct an object of type T with these 
args". The problem is it's not very intuitive in usage.


Perhaps "call" for functions and "make" for objects are better. 
If we add these to std.experimental.functional and 
std.experimental.conv and they get a lot of usage we might make 
a small change to the language.



Andrei


would'nt it be possible to take the type as a runtime param
and support struct, class and all callables?
e.g.

().args!(a=>5, b=>6);

auto st = SomeStruct().args!(a=>3);

auto sc = new SomeClass().args!(x => 20, y => 50);

().args!(x => 6);

or named and positional args
().args!(x => 9)(3, 6);


Re: stretto...@tutanota.com

2016-06-11 Thread ArturG via Digitalmars-d-learn

you could also use a simple wrapped cast

Ret castTo(Ret, T)(T t) if(is(T == class))
{
return cast(Ret) t;
}

then do

foo.stuff[0].castTo!Dong.x.writeln;

and if you want to guard the access you could try

foo.stuff[0].castTo!Dong.cc!((d){d.x = 5;});

cc is an alias for checkCall which is a template you can find here
http://forum.dlang.org/thread/ltalqpmpscdoziser...@forum.dlang.org,
it treats Type.init as false and ignores the call to fun.

but its not restricted to nullables only e.g.

float someF;
iota(0, someF).writeln; // normally would throw an AssertError

someF.cc!(f => iota(0, f)).writeln; // returns an empty range 
without calling iota, as float.nan is treated as false.

same as
0.0.cc!(f => iota(0, f)).writeln;


Re: isCallable and templates

2016-06-11 Thread ArturG via Digitalmars-d-learn
On Friday, 10 June 2016 at 17:32:03 UTC, Steven Schveighoffer 
wrote:

Consider:

import std.traits;
class Foo
{
   void bar() {}
   void baz()() {}
}

This works:

static assert(isCallable!(Foo.bar));

This does not:

static assert(isCallable!(Foo.baz));

However, clearly I can call baz due to IFTI (with the 
equivalent syntax, someFoo.baz() or someFoo.baz). Is there a 
way to fix this?


-Steve


i guess thats the same reason that

isCallable!(unaryFun!someString) -> false

if not, then it probably would also be usefull if it would be 
evaluated to true.


Formated string with assert inside template constraints?

2016-06-09 Thread ArturG via Digitalmars-d-learn

is it supposed to work?
normally it works e.g.

assert(0, "some\nstring");
prints:
some
string

but if you do it inside a template constraint like this:

void someTemp(T)(T t) if(isCallable!T.call!((b){assert(b, 
"some\nstring");}))

{
}

it prints:
some\x0astring


chainable scopes

2016-06-08 Thread ArturG via Digitalmars-d
this is a library implementation based on the with expression[1] 
idea

i posted a while ago and is kinda related to the ?. operator.

as we cant fully implement the above idea as a library i tried to 
do

what's possible which are basically chainable scopes[2].
implemented as 2 templates:

unchecked version: takes a Type and calls fun(type),
returns either type or return type of fun

auto call(alias fun, T)(T type)

checked version: takes a Type, does a check and if true, calls 
fun(type),

returns either type, return type of fun or ReturnType!(fun!T).init

auto checkCall(alias fun, T)(T type, T falseValue = T.init)

as im not an expert, are there any possible improvements?

(long post, only the top part is important the rest are just 
examples)
[1] 
http://forum.dlang.org/thread/zgzgdknkeyahlbypi...@forum.dlang.org


[2] https://dpaste.dzfl.pl/5ecc288f572c



Re: Why do some T.init evaluate to true while others to false?

2016-05-30 Thread ArturG via Digitalmars-d-learn

On Friday, 27 May 2016 at 14:48:59 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 14:43:47 UTC, ArturG wrote:

if(value is typeof(value).init) ...


that still requiers a special case for floating points, arrays 
and optionally empty string literals.


Have you tried? That should work in all cases.


does this count?

struct Foo
{
int x;
float f;
}

void main()
{
Foo foo;
if(foo is typeof(foo).init) "A: does'nt work".writeln;
foo = Foo();
if(foo is typeof(foo).init) "B: works".writeln;
}


if you remove the float from the struct both cases work or if you 
define the float inside the struct like this:


struct Foo
{
int x;
// float f = float.init; // does'nt work
float f = float.nan;
}


Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn
On Friday, 27 May 2016 at 18:03:23 UTC, Steven Schveighoffer 
wrote:


I didn't change the default. The default is to pick the first 
member and use that as the init value. I may not have even 
considered what foo.init might be when I was creating my enum.


-Steve


by default i ment this

enum foo
{
bar
}
foo f;
if(f) "dosnt print".writeln;

but i understand what you mean which adds a problem to my 
checkThen template, as the return type of the template depends on 
the return type of the callable which right now returns the init 
value of the callable return type if the type you pass into the 
template evaluates to false.


an example:

class Foo { int x; }
Foo foo(){ return null; }

foo.checkThen!( f => f.x = 5; ).writeln; // writes f.x.init 
because i kinda need a common return type if foo wouldnt return 
null




Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn
On Friday, 27 May 2016 at 16:56:21 UTC, Steven Schveighoffer 
wrote:

Why are you expecting it to be?

Won't work for enums with first elements that are non-zero 
either:


enum foo : int {
 bar = 1;
}

foo f;

if(f) writeln("this will output too");

-Steve



but by default it works you just changed the default so its ok 
that it doesnt work.


Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn

On Friday, 27 May 2016 at 15:24:18 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 15:19:50 UTC, ArturG wrote:

yes but i have to check for that when some one does


Why? This is no different than if they set any of the other 
four billion possible values.


What do you mean?

operation on float.nan gives you a float.nan so why does the 
shortcut evaluate to true and not false wouldnt that make more 
sense?



float f;
if(f) "why does this print".writeln; // it should not

same for char

char c;
if(c) "why does this print".writeln; // it should not

it works for most other types is there any reason why it doesnt 
work or couldnt work with floating points and character types?


Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn

On Friday, 27 May 2016 at 15:07:50 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 14:56:28 UTC, ArturG wrote:

   float f;
   if(f is float.init) "float init".writeln;
   f = float.nan;
   if(f is float.init) "float nan".writeln;


You changed it to a value that isn't float.init, so of course 
it isn't going to match!


float.nan and float.init are NOT the same thing. float.init is 
a kind of NAN, but not the same kind.


yes but i have to check for that when some one does

float.nan.checkThen!((f){ this fun should not run });

which should be the same as

float.init.checkThen!((f){ this fun should not run });


Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn

On Friday, 27 May 2016 at 14:48:59 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 14:43:47 UTC, ArturG wrote:

if(value is typeof(value).init) ...


that still requiers a special case for floating points, arrays 
and optionally empty string literals.


Have you tried? That should work in all cases.


   float f;
   if(f is float.init) "float init".writeln;
   f = float.nan;
   if(f is float.init) "float nan".writeln;



Re: Why do some T.init evaluate to true while others to false?

2016-05-27 Thread ArturG via Digitalmars-d-learn

On Friday, 27 May 2016 at 09:25:55 UTC, Marc Schütz wrote:

On Thursday, 26 May 2016 at 16:45:22 UTC, ArturG wrote:
im just playing with this template[1] is there anything else i 
missed? (if you dont mind)
it basically treats any T.init as false and skips the 
function/delegate and just returns type.


[1] https://dpaste.dzfl.pl/d159d83e3167


If you just want to check whether something is equal to its 
type's .init value, use the `is` operator, which does a bitwise 
comparison:


if(value is typeof(value).init) ...


that still requiers a special case for floating points, arrays 
and optionally empty string literals.





Re: Why do some T.init evaluate to true while others to false?

2016-05-26 Thread ArturG via Digitalmars-d-learn

On Thursday, 26 May 2016 at 15:51:39 UTC, Basile B. wrote:


Oh, I'm so sorry ! I totally missed the point of the Q.

float.nan is not a "unique" value. Several values verify "nan" 
(Look at std.math.isNan). So I suppose it's simpler to test 
for nullity. Though with the sign there's also two possible 
0...


void main(string[] args)
{
writeln(float.nan == float.init); // false
import std.math: isNaN;
writeln(isNaN(float.nan));  // true
writeln(isNaN(float.init)); //true
}

So the shortcut in the compiler might be more simple, there is 
only a single test for "if(myFloat)"...


im just playing with this template[1] is there anything else i 
missed? (if you dont mind)
it basically treats any T.init as false and skips the 
function/delegate and just returns type.


[1] https://dpaste.dzfl.pl/d159d83e3167


Re: Why do some T.init evaluate to true while others to false?

2016-05-26 Thread ArturG via Digitalmars-d-learn

On Thursday, 26 May 2016 at 15:38:55 UTC, Basile B. wrote:



because nan is not 0 and that the shortcut for float is

if (fpValue) <=> if (fpValue != 0)
if (!fpValue)<=> if (fpValue == 0)

There's no relation between the initializer and the shortcut. 
It's not because for some values the shortcut matches to the 
initializer that it must always be the case...But I admit I 
don't know the exact rationale.


Does anyone know ?


Ok sorry for the noise and thanks anyway.


Re: Why do some T.init evaluate to true while others to false?

2016-05-26 Thread ArturG via Digitalmars-d-learn

On Thursday, 26 May 2016 at 15:29:52 UTC, Basile B. wrote:



float.init is not equal to 0.0f. In D FP points values are 
initialized to nan (not a number).


By the way for strings it works, it's like the array case I 
described in the first answer).


yes i guess i tested all/most types and know that float.init is 
float.nan but why is nan true and not false?


Re: Why do some T.init evaluate to true while others to false?

2016-05-26 Thread ArturG via Digitalmars-d-learn

On Thursday, 26 May 2016 at 15:25:26 UTC, ag0aep6g wrote:

On 05/26/2016 04:03 PM, ArturG wrote:

for example:

if(any floatingpoint.init) will be true
if(any char.init) also true
if("") also true

while others are false e.g.

string s;
if(s) will be false
all others are also false or did i miss any?


What does it matter?


You would have to create special cases for them.


Re: Why do some T.init evaluate to true while others to false?

2016-05-26 Thread arturg via Digitalmars-d-learn

On Thursday, 26 May 2016 at 15:15:57 UTC, Basile B. wrote:

On Thursday, 26 May 2016 at 15:14:21 UTC, Basile B. wrote:

On Thursday, 26 May 2016 at 15:11:50 UTC, Basile B. wrote:

On Thursday, 26 May 2016 at 14:03:16 UTC, ArturG wrote:

[...]



[...]
- integral(*): if (i) <=> if (i > 0)


I obviously meant:

- integral(*): if (i) <=> if (i <> 0)

and "<=>" stands for "equivalence"


I obviously meant:

integral(*): if (i) <=> if (i != 0),

"<>" is the Pascal operator for C's "!=" 


yes i know about most of those shortcuts its just float.init and 
char.init that work different then the other when you do this


if(someType) // will be true for float and char while someType is 
T.init




Re: Effect of declaring a class immutable ?

2016-05-26 Thread ArturG via Digitalmars-d-learn

On Thursday, 26 May 2016 at 14:12:23 UTC, chmike wrote:
I couldn't find any information about this on the dlang web 
site.


What is the effect adding the immutable attribute to a class 
like this


immutable class MyClass { ... }

The compiler doesn't complain.
Will it add the immutable attribute to all members ?


auto mc = new MyClass;

typeof(mc.someFieldOrFun).stringof.writeln; says yes

and if you define opCall you need to use
auto mc = new immutable MyClass;


Why do some T.init evaluate to true while others to false?

2016-05-26 Thread ArturG via Digitalmars-d-learn

for example:

if(any floatingpoint.init) will be true
if(any char.init) also true
if("") also true

while others are false e.g.

string s;
if(s) will be false
all others are also false or did i miss any?


Re: with and checked with expression?

2016-05-25 Thread ArturG via Digitalmars-d

On Wednesday, 25 May 2016 at 00:36:04 UTC, Seb wrote:

On Tuesday, 24 May 2016 at 19:03:11 UTC, ArturG wrote:

would something like this be usefull?


A general word of advice - try to keep your post short & 
concise. It is more likely to get replies then.




Yes i might have used to many examples, should have used dpaste 
for all of them.


Yes it would be to me, but I am not sure whether it would 
justify the rather uncommon #{} syntax. Does any language out 
there use it?




The syntax is of course up for debate, but similar to the with 
statement and others it creates its own scope so it should'nt be 
and exception and also use the {}.
Just picked the # because i needed a separator for the input and 
its optional parameters and it's a easy to reach single symbol 
which isnt ambigius with other D symbols.


We cant use the syntax from freatures which provide similar 
functionality from other languages[1], because they use existing 
D syntax and are'nt as flexible as the with expression/statement.


D already has similar syntax for struct initialiser and anonymous 
classes and as it can be chained it also kinda behaves like a 
eagerly called function/delegate.


[1] https://en.wikipedia.org/wiki/Method_cascading

For the expression?, imho it is very useful - existence checks 
are very common. I know that at least ruby and CoffeeScript 
have it. Do you know more?


c#, dart and others but they only have the ?. operator.
c# has ?[ for checked index and you might also want ?( for 
checked opCall which i didnt want to propose because it can be 
done with the with expression.




with and checked with expression?

2016-05-24 Thread ArturG via Digitalmars-d
ive read some discussions about some library solution for the ?. 
operator,

has there been anything added to phobos?

wouldnt a checked with expression be a more general/longer form 
of the ?. operator?


A with expression not only allows you to do unchecked/checked 
access to members but to any operation you can do on the type,
it allows method/statement cascading so that you dont have to 
return this from methods,
thereby you can combine it with function chaining without 
breaking the cascading,
and it can also be used to wrap any statement to integrate them 
into a function chain.



some example syntax:

   T t = T # { /*same as with statement*/ };   // works only with 
aggregate types, returns its input


   T t = T #aliasName {  };   // works with any type, can use 
aliasName to refer to the input like self/this, returns its input


   RetType t = T #aliasName, RetType varName {  };   // same as 
above but can change the return type


   // extention for the above, checks the input before executing 
the block,
   // if input is null/false the block does'nt get executed the 
return value will be null/T.init/RetType.init


   T t = T #? {  };

   T t = T #?aliasName {  };

   RetType t = T #?aliasName, RetType varName {  };

   // optionally

   #{ /*empty with expression*/ };  // originally not planned but 
would work like the statement expression
// mentioned in the kill the 
comma operator thread, no input no output and allways runs block


   // for single operations, the short null checked version is 
less verbose


   t?.foo = 5;   // if t is null no assignment happens,
   // same as if(t) t.foo = 5; or t#?{ foo = 5; };

   t.child = s?.child;  // if s is null, t.child will be null,
   // same as t.child = s? s.child : null; or t.child = s#?_, 
typeof(t.child) ret{ ret = child;};


   t?.child = s?.child?;   // if t is null no assignment, if s or 
s.child is null, t.child will be null,
   // same as if(t) t.child = (s && s.child)? s.child : null; or 
t#?lhs{ s#? { child#?rhs{ lhs.child = rhs; };};};


-
some examples:

   // using it with aggregate types

   struct Foo{ string name; int val; }
   class Bar{ string name; int val; }

   Foo()#{ name = "Foo"; val = 5; }.writeln;

   new Foo() #
   {
  import std.string : capitalize;
  name = someName.capitalize;
  val = 5;
   }.writeln;

   auto foo = Foo()#n{ name = "Foo"; val = 5; n.writeln; };

   new Bar#{ name = "Foo"; val = 5; }.writeln;
   auto bar = new Bar#{ name = "Foo"; val = 5; };

   auto someBar = (someCond? getBar() : new Bar) #{ name = "Bar"; 
val = 30; };

   auto someBar = getBar.or(new Bar) #{ name = "Bar"; val = 30; };

   auto dg = (string s, int v) => new Bar#{ name = s; val = v; };


   // some other random uses

   "test"#n{ import std.string; n.capitalize; }.writeln;

   66#n, string ret{ import std.conv; ret = n.to!string; }.foo();

   // writes the return value of someFun
   someFun()#n{ n == 5? doSomething() :
n == 6? doSomethingElse() : null; }.writeln;

   // writes five or six or no match
   someFun()#n, string ret{ ret = n == 5? "five" :
  n == 6? "six"  : "no match"; 
}.writeln;


   auto res = someFun.someOtherFun #n{ foreach(i; 0 .. n) 
i.writeln; }.fun(6) #n{ n.writeln; };


   //void fun(string name, int val, string, int);

   wrap!fun#{ name = "Test"; param2 = "some string";
  param3 = 66; val = 2; }();

   auto wrappedFun = wrap!fun#{
 name = "test";
 param2 = "some string";
 param3 = 66;
 val = 2;
 };
   wrappedFun.param0 = "Test";
   wrappedFun.param2 = "some other string";
   wrappedFun.val = 70;
   wrappedFun();


   // if(c.foo) c.foo.x = 55;
   c.foo?.x = 55;
   c.foo#?{ x = 55; };


   // if(someClass && someClass.child && someClass.child.child &&
   //someOtherClass && someOtherClass.child && 
someOtherClass.child.child)
   // { someClass.child.child.x = someOtherClass.child.child.x * 
2; }


   someClass?.child?.child?.x = someOtherClass?.child?.child?.x * 
2;


   someClass#?{ child#?{ child#?lhs {
  someOtherClass#?{ child#?{ child#?rhs {
  lhs.x = rhs.x * 2;
   };};};};};};


   //if(someClass) with(someClass){
   //   x = 5; x.writeln;
   //   if(child) with(child){
   //  x = 6; x.writeln;
   //  alias lhs = child;
   //  if(child) with(child){
   // if(someOtherClass) with(someOtherClass){
   //x = 10; x.writeln;
   //if(child) with(child){
   //   x = 59; x.writeln;
   //   if(child) with(child){
   //  lhs.x = x * 2;
   //  x = 44; x.writeln;
   //} } } } } }

   // same as above
   someClass #? { x = 5; x.writeln;
  child  #? { x = 6; x.writeln;
 child #?lhs {
someOtherClass #? { x = 10; x.writeln;
 

Re: Usage of custom class with JSONValue

2016-03-24 Thread arturg via Digitalmars-d-learn
On Thursday, 24 March 2016 at 08:24:46 UTC, Edwin van Leeuwen 
wrote:
JSONValue only works with the build in types, not with user 
defined types. Either you define a specific function for the 
class that returns a JSONValue. Easiest way to do that would be 
to build an associative array with strings as keys with the 
names, and JSONValues as values and turn that into JSONValue, 
i.e. (untested):

class MyClass
{
string[] _data;
alias _data this;
// ...
   JSONValue toJSON()
  {
JSONValue[string] aa;
JSONValue[] dataJSON = _data.map!((a) => 
JSONValue(a)).array;

aa["data"] = JSONValue(dataJSON);
return JSONValue(aa);
  }
}



isnt alias this supposed to do this implicitly?

convert this
auto jsValue = JSONValue(new MyClass());

into this
auto jsValue = JSONValue((new MyClass())._data);


Re: Named arguments via struct initialization in functions

2016-03-08 Thread arturg via Digitalmars-d

hi, has the UDA syntax been proposed already?

void fun(int foo, int bar, int bazDaz = 0){}

fun(10, 30, 50); // normal
fun(10, 30); normal with default

fun(10, 30, @bazDaz 50); // mixed
fun(@bazDaz 50, 10, 30) // mixed and reordered
fun(@bar 30, 10); // mixed, reordered and default

fun(@foo 10, @bar 30, @bazDaz 50); // named
fun(@bar 30, @bazDaz 50, @foo 10); // named and reordered

@foo int a = 10;
@bar int b = 30;
@bazDaz int c = 50;

fun(c, a, b); // hm allowed or not?

but if built in tuples could be used to do named args then it 
might be better to have those.




Re: DIP 88: Simple form of named parameters

2016-01-25 Thread arturg via Digitalmars-d

On Monday, 25 January 2016 at 08:55:55 UTC, Jacob Carlborg wrote:

On 2016-01-24 19:23, Chris Wright wrote:

It shouldn't. However, it is another way to pass function 
arguments, so

for thoroughness it would be better to mention it.


Added an example.

Is this what you intended? If so, please document it so other 
reviewers

don't have to wonder.


Added an example.


hi, named args is mainly a feature for the caller, is it really 
necessary to add a new syntax to the function definition?

besides making some args part of the api and some not.

and if you cant omit args with default initializer like in your 
example


void foo(int a: = 3, int b: = 4);
foo();
foo(a: 5, b: 6);
foo(b: 6); // this is not allowed since it's not legal to reorder 
the arguments


this feature is nothing more then a comment and the simplest way 
to implement this, is to add a single word comment type which 
might be usefull in more situations.




Re: DIP 88: Simple form of named parameters

2016-01-25 Thread arturg via Digitalmars-d

On Monday, 25 January 2016 at 13:40:18 UTC, HaraldZealot wrote:
On Saturday, 23 January 2016 at 14:19:03 UTC, Jacob Carlborg 
wrote:

This is mostly to prevent ugly hacks like Flag [1].

http://wiki.dlang.org/DIP88

[1] https://dlang.org/phobos/std_typecons.html#.Flag


Why not simply allow programmer to declare auto variable at 
function call side like in `foreach`?


E.g.

```d
void foo(int width, int height){...} //function definition

foo(width = 2, height = 3); // function call
```


the equal sign cant be used because D behaves like this

int width, height;

foo(width = 5, height = 10); // 5
 // 10
width.writeln;  // 5
height.writeln; // 10

void foo(int width, int height)
{
width.writeln;
height.writeln;
}

and in python

def foo(width, height):
print(width)
print(height)

width = 0
height = 0
foo(width = 5, height = 10) # 5
# 10
print(width)  # 0
print(height) # 0



Re: DIP 88: Simple form of named parameters

2016-01-25 Thread arturg via Digitalmars-d

On Monday, 25 January 2016 at 16:50:49 UTC, HaraldZealot wrote:

On Monday, 25 January 2016 at 14:35:09 UTC, arturg wrote:

On Monday, 25 January 2016 at 13:40:18 UTC, HaraldZealot wrote:
the equal sign cant be used because D behaves like this

int width, height;

foo(width = 5, height = 10); // 5
 // 10
width.writeln;  // 5
height.writeln; // 10

void foo(int width, int height)
{
width.writeln;
height.writeln;
}



You didn't pay attention, that in my proposal `foo(width = 5, 
height = 10);` width and height were declared in place of use, 
and scope is only this call


this code compiles right now which would make it a breaking 
change if you use the = and change the current behavior


module foo;

int width;
int height;

module app;
import foo;

void bar(int width, int height) {}

void main()
{
bar(width = 5, height = 10);
}



Re: DIP 88: Simple form of named parameters

2016-01-25 Thread arturg via Digitalmars-d

On Monday, 25 January 2016 at 16:17:27 UTC, Chris Wright wrote:



It's a comment that the compiler verifies. You could argue that 
the bulk of the type system is comments that the compiler 
verifies.


named arguments solve this problem

void foo(int a = 4, int b = 10, int c = 3) {}

foo(c : 5);

beeing callside documentation is only a byproduct.


Re: why the sort result is different with C#

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

On Friday, 22 January 2016 at 06:53:29 UTC, mzf wrote:

D code:
auto arr = ["b1=1", "b=2","a1=1", "a=2"];
writeln(arr.sort());

output:["a1=1", "a=2", "b1=1", "b=2"]

C# code:
var arr = new string[]{ "b1=1", "b=2", "a1=1", "a=2" };
Array.Sort(arr);

output:["a=2","a1=1","b=2","b1=1"]


 auto arr1 = ["b1=1", "b=2", "a1=1", "a=2"];
 auto arr2 = ["b1 = 1", "b = 2", "a1 = 1", "a = 2"];

 arr1.sort.writeln; // ["a1=1", "a=2", "b1=1", "b=2"]
 arr2.sort.writeln; // ["a = 2", "a1 = 1", "b = 2", "b1 = 1"]