Re: Cannot pass const(T) to function with ref const(T)

2021-03-13 Thread Andrey via Digitalmars-d-learn

Mistake. It says about simple argument:
cannot pass rvalue argument `x` of type `Word!(wstring, 
wstring)` to parameter `ref const(Word!(wstring, wstring)) base`


Function:
void _setPastBases(const ref Data item, const ref UsualWord 
base)


Cannot pass const(T) to function with ref const(T)

2021-03-13 Thread Andrey via Digitalmars-d-learn

Hello,
Dmd gives an error:
Error: function `_setPastBases(ref const(Data) item, ref 
const(Word!(wstring, wstring)) base)` is not callable using 
argument types `(const(Data), Word!(wstring, wstring))


where Data and Word - structs.

What happens and how to pass arguments?

Ldc compiles without such error.


Re: writeln and write at CTFE

2021-01-13 Thread Andrey via Digitalmars-d-learn
On Wednesday, 13 January 2021 at 11:31:16 UTC, Bastiaan Veelo 
wrote:
On Wednesday, 13 January 2021 at 09:11:53 UTC, Guillaume Piolat 
wrote:

On Wednesday, 13 January 2021 at 08:35:09 UTC, Andrey wrote:

Hello all,
Tell me please how can I "writeln" and "write" in function 
that is used in CTFE?

At the moment I get this:
import\std\stdio.d(4952,5): Error: variable impl cannot be 
modified at compile time


Or may be exist some other ways to do it?


pragma(msg, );


This may however not do what you wish it to do: 
https://forum.dlang.org/post/mailman.4526.1499573493.31550.digitalmars-d-le...@puremagic.com


— Bastiaan.


Function "ctfeWriteln" doens't exist.

pragma(msg, ...) is used only for CT values.

Today is 2021. Dlang still doesn't have ctfe write functions?


writeln and write at CTFE

2021-01-13 Thread Andrey via Digitalmars-d-learn

Hello all,
Tell me please how can I "writeln" and "write" in function that 
is used in CTFE?

At the moment I get this:
import\std\stdio.d(4952,5): Error: variable impl cannot be 
modified at compile time


Or may be exist some other ways to do it?


Cannot implicitly convert expression of type const(string[]) to string[]

2021-01-08 Thread Andrey via Digitalmars-d-learn

Hello,


struct Value
{
int value;
string data;
string[] text;
}

void test(const ref Value value)
{
Value other = void;
other.text = value.text;
}

void main()
{
Value row;
row.value = 10;
row.data = "ggg";

test(row);
}


I want to pass variable "row" inside function "test" as a read 
only parameter.

Inside I create another variable and try to assign field "text".
On that line I get:
Error: cannot implicitly convert expression value.text of type 
const(string[]) to string[].


1. How to assign correctly (and without dup/ugly cast())?
2. Or how to pass "row" correctly?


Re: Pass enum variable as const ref arg

2020-12-04 Thread Andrey via Digitalmars-d-learn

Thank you!


Re: Pass enum variable as const ref arg

2020-12-04 Thread Andrey via Digitalmars-d-learn

Hm, you mean that enum variable is not a real variable?
I thought that to make CT variable you should mark it as enum (in 
c++ as constexpr).

How to do it here?


Pass enum variable as const ref arg

2020-12-04 Thread Andrey via Digitalmars-d-learn

Hello,


void test(const ref string[3] qazzz) { qazzz.writeln; }

void main()
{
enum string[3] value = ["qwer", "ggg", "v"];
test(value);
}


Gives errors:

onlineapp.d(26): Error: function onlineapp.test(ref 
const(string[3]) qazzz) is not callable using argument types 
(string[3])
onlineapp.d(26):cannot pass rvalue argument ["qwer", 
"ggg", "v"] of type string[3] to parameter ref const(string[3]) 
qazzz


WTF?


New vs length on dymamic array

2020-11-09 Thread Andrey via Digitalmars-d-learn

Hello,

Are here any differences in creation of dynamic array with known 
size?



auto array = new wchar[](111);


and


wchar[] array;
array.length = 111;


Re: Call method of object variable

2020-10-16 Thread Andrey via Digitalmars-d-learn

Thank you!


Call method of object variable

2020-10-16 Thread Andrey via Digitalmars-d-learn

Hi,
I have got:

struct Qaz
{
wstring read() {return null;}
wstring hear() {return "";} }

void main()
{
// ...
static if(some_condition) alias method = Qaz.hear;
else alias method = Qaz.read;

// ...
Qaz qaz;

qaz.method(); // ???
}


How to call alias "method" on object "qaz"?


Re: Count template parameters of method

2020-10-12 Thread Andrey via Digitalmars-d-learn

And what about:

void test() {}

and

void text(alias qqq)() {}

?


Count template parameters of method

2020-10-11 Thread Andrey via Digitalmars-d-learn

Hello,

How to count a number of parameters in uninitialized template 
method?


For example:

struct Test
{
void abc(int a, bool status, string text)() {}
{


The method "Test.abc" has three template paramenters.

I know that "TemplateArgsOf" exists but it is used only for 
INITIALIZED templates...


Re: Sum string lengths

2020-05-14 Thread Andrey via Digitalmars-d-learn

Thanks everyone.


Sum string lengths

2020-05-13 Thread Andrey via Digitalmars-d-learn

Hi,
I want to sum lengths of all strings in array:

auto data = ["qwerty", "az", ""];


Fold and reduce doesn't work:

auto result = data.fold!`a + b.length`(0U);


gives error:
static assert:  "Incompatible function/seed/element: 
binaryFun/uint/string"


How to do it in one line?


Re: declaration of inner function is already defined

2020-05-13 Thread Andrey via Digitalmars-d-learn

On Wednesday, 13 May 2020 at 12:58:11 UTC, Adam D. Ruppe wrote:

On Wednesday, 13 May 2020 at 12:45:06 UTC, Andrey wrote:

Why this works:


It's just defined that way. Local functions follow local 
variable rules - must be declared before use and names not 
allowed to overload each other.


There might be a deeper reason too but like that's the main 
thing, they just work like any other local vars.


Overload for local functions will be very useful thing. Otherwise 
it is PHP or C.


declaration of inner function is already defined

2020-05-13 Thread Andrey via Digitalmars-d-learn

Hi,

Why this works:
void setBases(string type)(ref int data, string base, string[] 
syllables)

{

}

void setBases(string type, T)(ref int data, const ref T source)
{

}

void main()
{
int q = 6;
setBases!"tt"(q, "qwerty", ["tg", "jj"]);
setBases!"tt"(q, q);
}


and this doesn't work:

void main()
{
void setBases(string type)(ref int data, string base, 
string[] syllables)

{

}

void setBases(string type, T)(ref int data, const ref T 
source)

{

}

int q = 6;
setBases!"tt"(q, "qwerty", ["tg", "jj"]);
setBases!"tt"(q, q);
}


The error is:
declaration setBases(string type, T)(ref int data, ref const T 
source) is already defined


?


Call of C function breaks memoty layout

2020-01-24 Thread Andrey via Digitalmars-d-learn

Hello,
I'm trying to bind C library for Tcl/Tk in D code. There is a 
function called "Tcl_CreateInterp()" which I declared as 
extent(C). When I call this function then layout of memory become 
broken - one of my global wstring variables loses it's value.
I don't know why it is happens. If I comment the call - I get 
normal execution.


May be somebody had faced with such problem. What to do?

My code:

struct Tcl_Interp;
extern (C)
{
   Tcl_Interp* Tcl_CreateInterp() nothrow;
}


Re: CTFE and assoc array

2020-01-19 Thread Andrey via Digitalmars-d-learn
On Saturday, 18 January 2020 at 21:44:35 UTC, Boris Carvajal 
wrote:


I read that thread. But:
Deprecation: initialization of immutable variable from static 
this is deprecated.

Use shared static this instead.


And we get? No CTFE with static immutable AA?


CTFE and assoc array

2020-01-18 Thread Andrey via Digitalmars-d-learn

Hello,

Why this doesn't work?


import std;

struct Qwezzz
{
shared static this()
{
qaz = qazMap;
}

enum qazMap = ["rrr": "vv", "hty": "4ft6"];
static immutable string[string] qaz;
}

void main()
{
enum sorted = Qwezzz.qaz.keys.sort();
}


The variable "qaz" is static immutable and doesn't work in CTFE.


Re: undefined symbol: _D3std7variant...

2019-10-22 Thread Andrey via Digitalmars-d-learn

On Tuesday, 22 October 2019 at 12:57:45 UTC, Daniel Kozak wrote:

Have you try to clean all caches? Try to remove .dub folder


I removed .dub folder but this error appears again.


undefined symbol: _D3std7variant...

2019-10-22 Thread Andrey via Digitalmars-d-learn

Hello,
During compilation on linking stage I get strange errors (LDC):
lld-link: error: undefined symbol: 
_D3std7variant__T8VariantNVmi56TSQBf8typecons__T5TupleTAyuTSQCgQCf__TQCaVmi32TSQCzQBu__TQBoTAQBmTQBqZQCbTQnTQCbZQDrZQCqTQBcTQCrZQEh4typeMxFNbNdNeZC8TypeInfo

referenced by E:\Programs\LDC2\import\std\variant.d:753
  
.dub\obj\builder.obj:(_D3std7variant__T8VariantNVmi56TSQBf8typecons__T5TupleTAyuTSQCgQCf__TQCaVmi32TSQCzQBu__TQBoTAQBmTQBqZQCbTQnTQCbZQDrZQCqTQBcTQCrZQEh__T4peekTQDhZQkMNgFNdZPNgAyu)   referenced by E:\Programs\LDC2\import\std\variant.d:753
  
.dub\obj\builder.obj:(_D3std7variant__T8VariantNVmi56TSQBf8typecons__T5TupleTAyuTSQCgQCf__TQCaVmi32TSQCzQBu__TQBoTAQBmTQBqZQCbTQnTQCbZQDrZQCqTQBcTQCrZQEh__T4peekTQBwZQkMNgFNdZPNgAAyu)  referenced by E:\Programs\LDC2\import\std\variant.d:820
  
.dub\obj\builder.obj:(_D3std7variant__T8VariantNVmi56TSQBf8typecons__T5TupleTAyuTSQCgQCf__TQCaVmi32TSQCzQBu__TQBoTAQBmTQBqZQCbTQnTQCbZQDrZQCqTQBcTQCrZQEh__T3getTQEdZQjMNgFNdZNgSQFxQEs__TQEmTQEjTQEjZQEy)


How to solve?
This is the first time when linking fails on Phobos library.


Re: contains method on immutable sorted array

2019-10-22 Thread Andrey via Digitalmars-d-learn

On Monday, 21 October 2019 at 20:44:29 UTC, Nicholas Wilson wrote:

works, so I guess contains doesn't work with immutable?
If you can do some more research into this and confirm it then, 
please file a bug report.


As I understand - yes. It doesn't work with immutable object.
Also I see the same problem with 'const' and 'shared' object:

shared values = sort(cast(wstring[])["й", "ц", "ук", "н"]);
const values = sort(cast(wstring[])["й", "ц", "ук", "н"]);
values.contains("ук"w).writeln; // error


So you think it is a bug in compiler?


contains method on immutable sorted array

2019-10-21 Thread Andrey via Digitalmars-d-learn

Hello,
I have got a global constant immutable array:
immutable globalvalues = sort(cast(wstring[])["й", "ц", "ук", 
"н"]);


Somewhere in program I want to check an existance:

globalvalues.contains("ук"w).writeln;


But get an error:
Error: template std.range.SortedRange!(wstring[], "a < 
b").SortedRange.contains cannot deduce function from argument 
types !()(wstring) immutable, candidates are:

/dlang/ldc-1.17.0/bin/../import/std/range/package.d(10993):
std.range.SortedRange!(wstring[], "a < 
b").SortedRange.contains(V)(V value) if 
(isRandomAccessRange!Range)


Why I can't check?


Re: Import sources from parent project

2019-10-20 Thread Andrey via Digitalmars-d-learn

On Saturday, 19 October 2019 at 18:54:28 UTC, Andre Pany wrote:
In dub.json of your child apps you need to add a dependency to 
parentapp.


I added via "dependencies" parameter and after got this error: 
"Detected dependency cycle".


Import sources from parent project

2019-10-19 Thread Andrey via Digitalmars-d-learn

Hi,
I have got this structure of my project:

parentapp
dub.json
source
common.d
childapp1
dub.json
source
app.d
somefile.d
childapp2
dub.json
source
app.d


The "childapp1" and "childapp2" are standanole subprograms. I 
want to import file "common.d" in both "app.d". How to do it 
correctly?


I tried to write "import common;" but got error: " Error: module 
`common` is in file 'common.d' which cannot be read".

In "parentapp/dub.json" I also added these lines:

"dependencies": {
"parentapp:childapp1": "*",
"parentapp:childapp2": "*"
},
"subPackages": [
"./childapp1/",
"./childapp2/"
]


Problem with aliasing member function

2019-08-18 Thread Andrey via Digitalmars-d-learn

Hello,
I can't compile this piece of code:

struct Object
{
void run(wstring ending, uint index)(int number)
{

}
}

void tester(alias callback, T)(int number, T object = null)
{
static if(is(T == typeof(null))) alias handler = callback;
else auto handler(wstring ending, uint index) = 
object.callback!(ending, index);

handler!("rfv", 5)(word);
}

void main()
{
Object obj;
tester!(Object.run)(10, );
}


Here in tester I want to alias a template method and call it on 
object if this object isn't null. But I don't understand how to 
do it.

How to solve the problem?


How to get name of my application (project)

2019-08-03 Thread Andrey via Digitalmars-d-learn
Hello, how to get name of my application (project) that we write 
in dub.json? Is there any compile-time constant like __MODULE__?


Re: Memory allocation failed in CT

2019-07-13 Thread Andrey via Digitalmars-d-learn

On Tuesday, 9 July 2019 at 19:04:53 UTC, Max Haughton wrote:
Is this a 64 or 32 bit compiler? Also could you post the source 
code if possible?


You could try "--DRT-gcopt=profile:1" druntime flag to see if 
the compiler is running out of memory for real


Thanks for help. I solved my issue by rewritting code.


Re: Memory allocation failed in CT

2019-07-09 Thread Andrey via Digitalmars-d-learn

On Tuesday, 9 July 2019 at 17:59:24 UTC, Max Haughton wrote:

On Tuesday, 9 July 2019 at 17:48:52 UTC, Andrey wrote:

Hello,
I have got a problem with compile-time calulations.
I have some code generator that should create some long string 
of code during CT and after generation I mixin it. If I run it 
normally - in run time - then there is no error and I get 
expected output - string with size ~ 3.5 MB.

If I run it in CT then I recieve an error:

[...]


I don't understand why...
The only operation in my generator is string concatination: 
_result ~= "some code...".


Are you using the -lowmem flag? This enables the GC during 
compilation i.e. you might be running out of memory (CTFE is 
not efficient with memory during evaluation)


I tried to turn on this flag but no success. The same error...


Re: Memory allocation failed in CT

2019-07-09 Thread Andrey via Digitalmars-d-learn

On Tuesday, 9 July 2019 at 17:59:24 UTC, Max Haughton wrote:

On Tuesday, 9 July 2019 at 17:48:52 UTC, Andrey wrote:


I in addition wrote "buffer.reserve(10 * 1014 * 1024);" and it 
also doesn't help.


Memory allocation failed in CT

2019-07-09 Thread Andrey via Digitalmars-d-learn

Hello,
I have got a problem with compile-time calulations.
I have some code generator that should create some long string of 
code during CT and after generation I mixin it. If I run it 
normally - in run time - then there is no error and I get 
expected output - string with size ~ 3.5 MB.

If I run it in CT then I recieve an error:
core.exception.OutOfMemoryError@core\exception.d(702): Memory 
allocation failed


0x7FF65A80BE73
0x7FF65A80BE73
0x7FF65A80BB46
0x7FF65A7FBA5C
0x7FF65A8035EC
0x7FF65A804311
0x7FF658BA733E
0x7FF658CC561F
0x7FF658CC0CD8
0x7FF658CB3728
0x7FF658CB3826
0x7FF658CB4762
0x7FF658CB3826
0x7FF658CB3CD0
E:\Programs\LDC2\bin\ldc2.exe failed with exit code 1.


I don't understand why...
The only operation in my generator is string concatination: 
_result ~= "some code...".


Mixin mangled name

2019-07-01 Thread Andrey via Digitalmars-d-learn

Hello,
Is it possible to mixin in code a mangled name of some entity so 
that compiler didn't emit undefined symbol error? For example 
mangled function name or template parameter?


Mixin mangled name

2019-07-01 Thread Andrey via Digitalmars-d-learn

Hello,
Is it possible to mixin in code a mangled name of some entity so 
that compiler didn't emit undefined symbol error? For example 
mangled function name or template parameter?


Re: Alias overload of function

2019-06-09 Thread Andrey via Digitalmars-d-learn

On Sunday, 9 June 2019 at 10:42:12 UTC, Basile-z wrote:

On Sunday, 9 June 2019 at 10:22:36 UTC, Andrey wrote:

Hello,
I have got 2 functions:

void myFunc(string name, int a)(wstring value) {}
void myFunc(string name, int a)() {}


I want to make an alias (for example for second function 
without argument):

alias myAlias(int a) = myFunc!("Name", a);


but compiler says:

... matches more than one template declaration


So how solve this problem?


use __traits(getOverloads) to apply to all of them in a static 
foreach.


Hmm... Cannot understand how to write getOverloads. My case:

struct Outer
{
   static template Inner(alias a, alias b, T)
   {
   void myFunc() {}
   }
}


This doesn't work (inside Outer):

pragma(msg, __traits(getOverloads, Inner, "myFunc", true));


Alias overload of function

2019-06-09 Thread Andrey via Digitalmars-d-learn

Hello,
I have got 2 functions:

void myFunc(string name, int a)(wstring value) {}
void myFunc(string name, int a)() {}


I want to make an alias (for example for second function without 
argument):

alias myAlias(int a) = myFunc!("Name", a);


but compiler says:

... matches more than one template declaration


So how solve this problem?


Re: Extract code of function

2019-05-26 Thread Andrey via Digitalmars-d-learn

On Sunday, 26 May 2019 at 18:21:23 UTC, Dennis wrote:

On Sunday, 26 May 2019 at 18:14:23 UTC, Jacob Carlborg wrote:

No, that's not possible.


Some hacky solutions are possible by importing a source file as 
a string and parsing it manually. dglsl actually extracts D 
function code to put into glsl shaders. Here's the snippet. 
See: 
https://github.com/icecocoa6/dglsl/blob/master/source/dglsl/translator.d#L140


Interesting solution... Thanks for a hint.


Extract code of function

2019-05-26 Thread Andrey via Digitalmars-d-learn

Hello,
Is it possible to extract code of some function into string 
variable using CT reflextion?

For example:

int test(bool flag)
{
return flag ? 100 : getRandom();
}

enum string code = GetFunctionCode!test; // "return flag ? 100 
: getRandom();"


What compiles faster?

2019-05-19 Thread Andrey via Digitalmars-d-learn

Hello,
Let we have got 3 template functions:

void func1(int a)() {}
void func2(int a, string b)() {}
void func3(int a, string b, bool c)() {}


As we see, the first function accepts 1 template argument, the 
second - 2 and the third - 3.


What compiles faster:
1. When a program has got 100 realizations of the first variant?
2. When a program has got 100 realizations of the second variant?
3. When a program has got 100 realizations of the third variant?


CTFE sort of tuples

2019-05-01 Thread Andrey via Digitalmars-d-learn

Hello, I have got this code:


alias Group = Tuple!(int[], "data", int, "key");

void main()
{
enum group = [
Group([1,2,3,4], 1),
Group([5,3], 1),
Group([4,5,4, 8, 9, 4], 1),
Group([2,3,4], 1),
];

enum result = group.sort!"a.data < b.data"().array(); }


I want to sort array of tuples using "data" element in CTFE. But 
this code give me errors:

/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/mutation.d(2782): Error: reinterpreting cast 
from Tuple!(int[], "data", int, "key")* to ubyte* is not supported in CTFE
/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/mutation.d(3014):
called from here: swap(r[i1], r[i2])
/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/sorting.d(1672):
called from here: swapAt(r, 2LU, 3LU)
/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/sorting.d(2112):
called from here: shortSort(r)
/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/sorting.d(1875):
called from here: quickSortImpl(r, r.length)
onlineapp.d(32):called from here: sort([Tuple([1, 2, 3, 
4], 1), Tuple([5, 3], 1), Tuple([4, 5, 4, 8, 9, 4], 1), 
Tuple([2, 3, 4], 1)])
onlineapp.d(32):called from here: array(sort([Tuple([1, 
2, 3, 4], 1), Tuple([5, 3], 1), Tuple([4, 5, 4, 8, 9, 4], 1), 
Tuple([2, 3, 4], 1)]))


As I understand the function "sort" sometimes can't be run at CT 
because of reinterpreting cast.

In this case how to sort?


incomplete mixin expression

2019-04-24 Thread Andrey via Digitalmars-d-learn

enum Qaz : wstring
{
One = "один"
}

template Qwerty(Values...)
{
enum text = "Values[%d]";
enum args = iota(Values.length).map!(value => 
format!text(value)).join(',');


pragma(msg, args);

alias Qwerty = Alias!(mixin("AliasSeq!(" ~ args ~ ");"));
}

void main()
{
Qwerty!(10, Qaz.One, "qwerty").writeln;
}


Output:
Values[0],Values[1],Values[2]
onlineapp.d(44): Error: incomplete mixin expression 
AliasSeq!(Values[0],Values[1],Values[2]);
onlineapp.d(54): Error: template instance 
`onlineapp.toUnderlyingType!(10, 
"\x3e\x04\x34\x04\x38\x04\x3d\x04", "qwerty")` error instantiating


Why mixin is "incomplete"?


Re: Check if function argument can be handled in CT

2019-04-24 Thread Andrey via Digitalmars-d-learn

On Wednesday, 24 April 2019 at 08:28:06 UTC, Basile.B wrote:

On Wednesday, 24 April 2019 at 07:53:47 UTC, Andrey wrote:


I know about this template. Unfortunally, it doesn't work inside 
functions.

void test(string arg1, string arg2)
{
enum isKnown1 = is(typeof((){enum v = arg1;}));
enum isKnown2 = is(typeof((){enum v = arg2;}));
writeln(isKnown1);
writeln(isKnown2);
}

void main()
{
test("qwerty", "qaz");
}


Output:

false
false


And I don't want to execute function using CTFE. The function 
should be ran as usual.


Example:

char[] test(string arg1, string arg2)
{
static if(isCTArg(arg1) && isCTArg(arg2))
{
enum result = "CT: " ~ arg1 ~ " and " ~ arg2; // no 
allocations

return result;
}
else
{
import std.format : format;

auto result = format!"RT: %s and %s"(arg1, arg2); // at 
least 1 allocation

return result;
}
}

void main()
{
// ...
auto val = test(some_CT_or_RT_arg1, some_CT_or_RT_arg2); // 
not CTFE.

// ...
}


Check if function argument can be handled in CT

2019-04-24 Thread Andrey via Digitalmars-d-learn

Hi all,
Do you know can we detect that some argument of a function can be 
handled in CT?

For example:

int value1 = 10;
someFunction(value1);
int value2 = getValueFromUserInput();
someFunction(value2);



void someFunction(int arg)
{
   static if(argCanBeHandledInCT(arg))
   {
   // perform some calculations during compilation
   }
   else
   {
   // perform some calculations during runtime
   }
}


Such thing would be good for code optimisation.
For example we pass some strings as arguments and in function 
they are concatenated. So instead of concating them in RT (and 
allocating memory) we can do all these actions in CT and get one 
resulting string.


Make partial alias of template function

2019-04-23 Thread Andrey via Digitalmars-d-learn

Hello,
I want to make partial alias of template function "format":

void qaz(alias tmp, Values...)()
{
alias message = format!tmp;

// ...

enum v = message(Values);
}

void main()
{
qaz!("test %s!", "Qwerty");
}


But I get this:

Error: static assert:  "Orphan format specifier: %s"
instantiated from here: format!("test %s!")


Also tried:

alias message(Args...) = format!(tmp, Args);


The same thing.

How to do it?


Inherit enum members

2019-04-21 Thread Andrey via Digitalmars-d-learn

Hello,
I have got 2 enums. How to inherit one enum from another?

enum Key : string
{
K1 = "qwerty",
K2 = "asdfgh"
}

enum ExtendedKey : Key
{
E1 = "q1",
E2 = "w2",
E3 = "e3"
}


Result:
onlineapp.d(27): Error: cannot implicitly convert expression 
"q1" of type string to Key
onlineapp.d(28): Error: cannot implicitly convert expression 
"w2" of type string to Key
onlineapp.d(29): Error: cannot implicitly convert expression 
"e3" of type string to Key


How to understand this?


Re: How to mixin finction name?

2019-04-14 Thread Andrey via Digitalmars-d-learn

On Sunday, 14 April 2019 at 11:44:16 UTC, Boris Carvajal wrote:

On Sunday, 14 April 2019 at 10:07:30 UTC, Andrey wrote:
Create some function in loop and use it. But I don't know how 
to mixin names?



import std.stdio;
void main()
{
 enum letters = ['A', 'B', 'C'];
 static foreach(ch; letters)
 {
 mixin("void print" ~ ch ~ "(uint i) { writeln('" ~ ch 
~ "', \" - \", i); }");

 }

 printA(1);
 printB(2);
 printC(3);
}


I want to mixin only name - not the full function code.


How to mixin finction name?

2019-04-14 Thread Andrey via Digitalmars-d-learn

Hi,
I want to do something like this:

void main()
{
enum letters = ['A', 'B', 'C'];
static foreach(ch; letter)
{
  void mixin("print" ~ ch)(uint i)
{
writeln(ch, " - ", i);
}
}

printB(6);
}


Create some function in loop and use it. But I don't know how to 
mixin names?


Output:

onlineapp.d(59): Error: no identifier for declarator void
onlineapp.d(59): Error: found i when expecting . following uint
onlineapp.d(59): Error: found ) when expecting identifier 
following uint.

onlineapp.d(60): Error: found { when expecting ,
onlineapp.d(61): Error: found ; when expecting ,
onlineapp.d(62): Error: expression expected, not }
onlineapp.d(63): Error: found } when expecting ,
onlineapp.d(65): Error: found ; when expecting ,
onlineapp.d(66): Error: expression expected, not }
onlineapp.d(67): Error: found End of File when expecting ,
onlineapp.d(67): Error: found End of File when expecting )
onlineapp.d(67): Error: found End of File when expecting ;
onlineapp.d(67): Error: found End of File when expecting } 
following compound statement
onlineapp.d(67): Error: found End of File when expecting } 
following compound statement


Access outer member of struct from inner struct

2019-04-02 Thread Andrey via Digitalmars-d-learn

Hello,
In this example how can I access the members "read" and "q" of 
struct Outer from Inner struct?

struct Outer
{
ulong q = 1;
Inner inner;

void read(ulong value)
{
q += value;
}

void run()
{
q.writeln;
read(5);
}

struct Inner
{
void write(string text)
{
read(text.length);
writeln(q);
}
}
}

void main()
{
Outer ttt;
ttt.run();
}


During compilation I get:
onlineapp.d(55): Error: this for read needs to be type Outer 
not type Inner

onlineapp.d(56): Error: need this for q of type ulong


Error: this.__lambda2 has no value

2019-04-01 Thread Andrey via Digitalmars-d-learn

Hello,
My code:

import std.string : join;

enum Key : string
{
First = "qwerty",
Last = "zaqy"
}

struct Qaz
{
enum text(alias Values) = Values.map!(value => "bool has" ~ 
value ~ " = false;").join();

}

//enum text(alias Values) = Values.map!(value => "bool has" ~ 
value ~ " = false;").join();


void main()
{
pragma(msg, Qaz.text!([Key.First, Key.Last]));
}


During compilation I get:

/dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/iteration.d(475): Error: 
this.__lambda2 has no value
onlineapp.d(33): Error: template instance 
`onlineapp.Qaz.text!(["qwerty", "zaqy"])` error instantiating
onlineapp.d(33):while evaluating pragma(msg, 
(Qaz).text!(["qwerty", "zaqy"]))


If I uncomment that line and use

pragma(msg, text!([Key.First, Key.Last]));

then compilation is passed.
What happens?


Pass template parameter into q{} string

2019-04-01 Thread Andrey via Digitalmars-d-learn

Hello,

enum Key : string
{
  First = "qwerty",
  Last = "zaqy"
}

void main()
{
enum decl(alias values1) = q{
static foreach(value; values1)
mixin("bool " ~ value ~ " = false;");
};

enum qqq = [Key.First, Key.Last];
mixin(decl!qqq);
}


I don't understand how to pass template parameter "values1" into 
q{} string to get this output:

static foreach(value; [Key.First, Key.Last])
mixin("bool " ~ value ~ " = false;");

or

static foreach(value; qqq)
mixin("bool " ~ value ~ " = false;");


Wrong initialization of variables

2019-04-01 Thread Andrey via Digitalmars-d-learn

Hello,
Simple code:

import std.stdio;

mixin template DeclFlag(alias values)
{
static foreach(value; values)
{
mixin("bool has" ~ value ~ " = false;");
}
}

enum Key : string
{
First = "qwerty",
Last = "zaqy"
}

void main()
{
enum data = [Key.First, Key.Last];
mixin DeclFlag!(data);

static foreach(value; data)
{
writeln(mixin("has" ~ value));
}
}


The output is:

true
true


But in template mixin DeclFlag all variables are inited with 
"false" value!


Also with AST switch I get code where there aren't any lines with 
text "bool hasqwerty = false;" or "bool haszaqy = false;". What 
happens?


Re: How to decode UTF-8 text?

2019-03-29 Thread Andrey via Digitalmars-d-learn

On Wednesday, 27 March 2019 at 19:16:21 UTC, kdevel wrote:

On Wednesday, 27 March 2019 at 13:39:07 UTC, Andrey wrote:


Thank you!




How to decode UTF-8 text?

2019-03-27 Thread Andrey via Digitalmars-d-learn

Hello,
I have got some text with UTF-8. For example this part:

Παράλληλη αναζήτηση


How to decode it to get this result?

Παράλληλη αναζήτηση


I have tried functions like "decode", "byUTF", "to!wchar"... but 
no success.


Input string is correct - checked it with 
"https://www.browserling.com/tools/utf8-decode;.


Build AA from two simple array

2019-03-23 Thread Andrey via Digitalmars-d-learn

Hello,
I have got 2 simple arrays with the same length:

int[] values = [1, 2, 3, 4, 5];
char[] keys = ['a', 'b', 'c', 'd', 'e'];
 auto result = buildAA(keys, values); // [a: 1, b: 2, c: 3, d: 
4, e: 5]


I want to build AA "result" using "values" and "keys". How to do 
it?


How to break from parallel foreach?

2019-02-26 Thread Andrey via Digitalmars-d-learn

Hello,
How to break from parallel foreach?
More general question - how to control such loop?


Re: Creating fixed array on stack

2019-01-12 Thread Andrey via Digitalmars-d-learn

On Friday, 11 January 2019 at 15:23:08 UTC, Dgame wrote:

On Friday, 11 January 2019 at 14:46:36 UTC, Andrey wrote:

Hi,
In C++ you can create a fixed array on stack:

int count = getCount();
int myarray[count];


In D the "count" is part of type and must be known at CT but 
in example it is RT.

How to do such thing in D? Without using of heap.


You could try alloca:


import core.stdc.stdlib: alloca;

pragma(inline, true) auto stack(T, alias len)(void* p = 
alloca(T.sizeof * len)) {

return (cast(T*) p)[0 .. len] = T.init;
}

void main() {
import std.stdio: writeln;

int size = 42;
auto a = stack!(int, size);
writeln(a);
a[] = 2;
writeln(a);
}



Thank you.
But this requires using of C function "alloca". I think this 
cause some RT overhead (and in output asm code) in comparison 
with C++ variant. Or I'm not right?


Creating fixed array on stack

2019-01-11 Thread Andrey via Digitalmars-d-learn

Hi,
In C++ you can create a fixed array on stack:

int count = getCount();
int myarray[count];


In D the "count" is part of type and must be known at CT but in 
example it is RT.

How to do such thing in D? Without using of heap.


Filter AA at compile time

2018-12-26 Thread Andrey via Digitalmars-d-learn

Hi,
I want to filter AA at compile time and do this:

void main()
{
// datamap is some AA
enum qaz = "qq";
enum types = datamap.byKeyValue.filter!(pair => 
qaz.isGood(pair)).assocArray();


types.writeln;
}


But compiler says:
Error: _aaRange cannot be interpreted at compile time, because 
it has no available source code


Why, where is a problem? And how to filter it correctly? Write my 
own foreach-loop?


Mixin operator 'if' directly

2018-12-19 Thread Andrey via Digitalmars-d-learn

Hi,
Here is a template mixin:

mixin template create(alias input, uint index, alias data)
{
if(input.length < index) return;

// ... some code
}


When I try to compile it, I get:

Error: declaration expected, not if


Is it possible to mixin operator 'if' directly inside my template 
mixin?


chunkBy array at compile time

2018-12-19 Thread Andrey via Digitalmars-d-learn

Hi,
I have got this code:

import std.array : array;
import std.algorithm.mutation;
import std.algorithm.iteration;
import std.stdio;

void main()
{
string input = "sieviaghp";
enum data = ["emo", "emoze", "emow", "emuo", "evuo", "ete", 
"ie", "vuo", "sie", "w"];


enum index = 3;
enum filtered = data.filter!(value => value.length > 
index).array();

pragma(msg, filtered);

enum GetSeq = filtered.chunkBy!((first, second) => 
first[index] == second[index]);//.array();

pragma(msg, GetSeq);
}
There is an array of strings. I filter it using length of each 
element. Result should be:

["emoze", "emow", "emuo", "evuo"]
Then I want to chuck it using symbol at position 'index' to get 
this:

["emoze"] // group 1, symbol 'z'
["emow"] // group 2, symbol 'w'
["emuo", "evuo"] // group 1, symbol 'o'

Everything I'm doing at COMPILE time!

But when I try to build program I get this strange error:

/dlang/dmd/linux/bin64/../../src/druntime/import/core/memory.d(827): Error: 
`fakePureErrno` cannot be interpreted at compile time, because it has no 
available source code
onlineapp.d(15):compile time context created here


So, what is wrong here and how to chunkBy at compile time?


Re: Reverse and sort array elements

2018-12-18 Thread Andrey via Digitalmars-d-learn

On Tuesday, 18 December 2018 at 12:32:35 UTC, angel wrote:

On Tuesday, 18 December 2018 at 12:07:37 UTC, Andrey wrote:


Thank you everybody.
Here was another problem that local variable 'array' shadows 
function 'array()' from std.array.


Reverse and sort array elements

2018-12-18 Thread Andrey via Digitalmars-d-learn

Hi,
Have array:

enum array = ["qwerty", "a", "baz"];

Need to reverse and sort array elements to get this result:

[a, ytrewq, zab]

Did this:

enum result = array.map!(value => value.retro()).sort();

Got:
Error: template std.algorithm.sorting.sort cannot deduce 
function from argument types !()(MapResult!(__lambda1, 
string[])), candidates are:
/usr/include/dmd/phobos/std/algorithm/sorting.d(1849,1):
std.algorithm.sorting.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)


How to solve the problem?


Initialize static array without explicit length

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

Hi,
I want to create a static array and immediately init it with 
values:

uint[x] data = [1,3,10,44,0,5000];


I don't want to set the length of it explicitly (x in square 
brackets). I want that compiler itself counted number of values 
(in example it is 6).


What should be a right syntax?


Re: How to pass -J switch to compiler via DUB?

2018-11-30 Thread Andrey via Digitalmars-d-learn

On Friday, 30 November 2018 at 11:21:04 UTC, fghost wrote:

On Friday, 30 November 2018 at 11:05:26 UTC, Andrey wrote:

Hi,
How to pass -J switch to compiler via DUB?
I want to import some text file at compile time:

string data = import("vertex.glsl");


In dub.json:
"dflags": [
"-J=vertex.glsl"
]

The file itself is located on the same level as "dub.json".


The -J switch takes a directory path, not path to the file 
directly.


Thanks to all.


How to pass -J switch to compiler via DUB?

2018-11-30 Thread Andrey via Digitalmars-d-learn

Hi,
How to pass -J switch to compiler via DUB?
I want to import some text file at compile time:

string data = import("vertex.glsl");


In dub.json:
"dflags": [
"-J=vertex.glsl"
]

The file itself is located on the same level as "dub.json".


Re: Cannot build project due to Derelict package

2018-11-26 Thread Andrey via Digitalmars-d-learn

On Monday, 26 November 2018 at 12:11:03 UTC, Alex wrote:

On Monday, 26 November 2018 at 11:57:40 UTC, Andrey wrote:

Hello,
I try to build my project using command "dub build" but I 
can\t because there is an error:
Fetching derelict-util 3.0.0-beta.2 (getting selected 
version)...

SSL connect error on handle 1F19AC0
And this happens every time... As I understand dub can't find 
package.


In dub.json I have this:

"dependencies": {
"derelict-glfw3": "~master"
}


I manually downloaded derelict-glfw3 and derelict-util from 
GitHub (master branch). What should I do to dub knew about 
these local packages?


There are some ways to let dub know about them:

https://forum.dlang.org/thread/fgpmytpzoifpdrhzk...@forum.dlang.org


Thanks!


Cannot build project due to Derelict package

2018-11-26 Thread Andrey via Digitalmars-d-learn

Hello,
I try to build my project using command "dub build" but I can\t 
because there is an error:
Fetching derelict-util 3.0.0-beta.2 (getting selected 
version)...

SSL connect error on handle 1F19AC0
And this happens every time... As I understand dub can't find 
package.


In dub.json I have this:

"dependencies": {
"derelict-glfw3": "~master"
}


I manually downloaded derelict-glfw3 and derelict-util from 
GitHub (master branch). What should I do to dub knew about these 
local packages?


Pass lambda into template

2018-09-03 Thread Andrey via Digitalmars-d-learn

Hello,

Here is a code with comments: https://run.dlang.io/is/BNl2Up.

I don't understand how to pass lambda into template.
I get an error:
onlineapp.d(18): Error: template instance `qwerty!((i) => "arg" 
~ i.to!string ~ "[0] == '?'", "||")` cannot use local __lambda1 
as parameter to non-global template qwerty(alias mapper, alias 
delimiter)


Re: Can't print enum values

2018-08-31 Thread Andrey via Digitalmars-d-learn

On Friday, 31 August 2018 at 12:21:48 UTC, aliak wrote:

auto ToUnderlyingType(alias a)() {
return cast(OriginalType!(typeof(a)))a;
}

void print(T...)(T args) {
writeln(staticMap!(ToUnderlyingType, args));
}



Oohhh. So easy! Killed 2 days - and templates and mixins tried... 
And the solution was to use TEMPLATE function with alias not 
regular...

Thank you!


Re: Can't print enum values

2018-08-31 Thread Andrey via Digitalmars-d-learn

On Thursday, 30 August 2018 at 12:04:26 UTC, vit wrote:

On Thursday, 30 August 2018 at 11:34:36 UTC, Andrey wrote:

On Thursday, 30 August 2018 at 11:09:40 UTC, vit wrote:

[...]


I want to create a reusable template for this purpose.
Why I can't use "staticMap" so that compiler it self would do 
this:

[...]
Just wrap some some symbol "args" with some expression at 
compile time.


It is the same as in C++:

[...]


D doesn't have expanding like C++

Unfortunately D has only simple automatic expading.


So how can one implement a reusable template "apply some function 
to each argument in template parameter pack" in D?


Re: Can't print enum values

2018-08-30 Thread Andrey via Digitalmars-d-learn

On Thursday, 30 August 2018 at 11:09:40 UTC, vit wrote:

args are runtime arguments.

import std.experimental.all;

enum MyEnum : string
{
First = "F_i_r_s_t",
Second = "S_e_c_o_n_d"
}

///alias QW(alias arg) = 
Alias!(cast(OriginalType!(typeof(arg)))arg);

auto QW(T)(const auto ref T x){
return cast(OriginalType!T)x;
}

void print(T...)(T args)
{
writeln(cast(OriginalType!(typeof(args[0])))args[0]); // 
Works...
///writeln(QW!(args[0]));// 
Doesn't work... MUST!

writeln(QW(args[0]));

static foreach(alias arg; args){
static if(is(typeof(arg) : MyEnum))write(QW(arg));
else write(arg);
}
write('\n');
//writeln(staticMap!(QW, args));// 
Doesn't work... MUST!

}

void main()
{
bool runTimeBool = true;
print(MyEnum.First, 7, runTimeBool, MyEnum.Second);
}


I want to create a reusable template for this purpose.
Why I can't use "staticMap" so that compiler it self would do 
this:

void print(T...)(T args)
{
   writeln(cast(OriginalType!(typeof(args[0])))args[0], 
cast(OriginalType!(typeof(args[1])))args[1], 
cast(OriginalType!(typeof(args[2])))args[2], 
cast(OriginalType!(typeof(args[3])))args[3]);

}
Just wrap some some symbol "args" with some expression at compile 
time.


It is the same as in C++:

template
void print(Args ...args)
{
   writeln(UnderlyingType(args)...); // UnderlyingType is a 
function here

}


Re: Static foreach internal variable

2018-08-30 Thread Andrey via Digitalmars-d-learn

On Thursday, 30 August 2018 at 09:49:15 UTC, drug wrote:

30.08.2018 11:19, Andrey пишет:


Thanks everybody. Works!




Can't print enum values

2018-08-30 Thread Andrey via Digitalmars-d-learn

Hello,
This code doesn't print enum values:

import std.meta;
import std.traits;
import std.stdio;

enum MyEnum : string
{
   First = "F_i_r_s_t",
   Second = "S_e_c_o_n_d"
}

alias QW(alias arg) = 
Alias!(cast(OriginalType!(typeof(arg)))arg);


void print(T...)(T args)
{
   writeln(cast(OriginalType!(typeof(args[0])))args[0]); // 
Works...
   writeln(QW!(args[0]));// 
Doesn't work... MUST!


   writeln(staticMap!(QW, args));// 
Doesn't work... MUST!

}

void main()
{
   bool runTimeBool = true;
   print(MyEnum.First, 7, runTimeBool, MyEnum.Second);
}


Must print "F_i_r_s_t" and "S_e_c_o_n_d", not just "First" and 
"Second".


Static foreach internal variable

2018-08-30 Thread Andrey via Digitalmars-d-learn

Hello,
is it possible to declare an internal variable in "static 
foreach" and on each iteration assign something to it?

Example:

static foreach(arg; SomeAliasSeq)
{
   internal = arg[0].converted;// a shortcut for expression 
"arg[0].converted"


   static if(internal.length == 0) { ... }
   else static if(internal.isNull) { ... }
   else { ... }
}


Re: Create constraint for each parameter in template arg pack

2018-08-28 Thread Andrey via Digitalmars-d-learn

On Tuesday, 28 August 2018 at 13:05:15 UTC, bauss wrote:
I'm not sure if there is a better way, but isInstanceOf 
(std.traits) seems to work with a static foreach and a static 
if.


template Qwerty(Values...)
{
static foreach (value; Values)
{
static if (!isInstanceOf!(Qaz, value))
{
static assert(0, "Values are not Qaz only ...");
}
}

// ...
}


Thank you everybody!



Create constraint for each parameter in template arg pack

2018-08-28 Thread Andrey via Digitalmars-d-learn

Hello,
Let we have two variadic templates:

template Qwerty(Values...) {}
template Qaz(alias type, Data...) {}


Now I want to add a constraint to "Qwerty" so that each type in 
"Values" pack must be a "Qaz" template. I don't care about values 
of "type" or "Data" in "Qaz".

How to do it in D?


Re: How to mixin repeated text?

2018-08-27 Thread Andrey via Digitalmars-d-learn

On Monday, 27 August 2018 at 11:56:08 UTC, Kamil Koczurek wrote:
Mixins seem to be an overkill here. Maybe something like this 
would suffice:


data[index + 1 .. index + 5].map!(k => k[0]).array == ""


Here there is dynamic code, with memory allocs.

I found solution:
---
import std.meta;
import std.traits;
import std.stdio;
import std.array : join;
import std.algorithm.iteration : map;
import std.conv : to;
import std.range;

string qaz(alias args, alias index, ubyte count)()
{
return iota(1, count).map!(j => args.stringof ~ '[' ~ 
index.stringof ~ '+' ~ j.to!string ~ "][0] == '&'").join("||");

}

void main()
{
ushort index = 1;
string[] args = ["", "123", "", "true", "", 
"77", ""];


if(index + 1 >= args.length || mixin(qaz!(args, index, 4)))
{
writeln(qaz!(args, index, 4)());
}
}
---


How to mixin repeated text?

2018-08-27 Thread Andrey via Digitalmars-d-learn

Hello again,
I have this part of code:

...
if(index + 3 >= data.length || data[index + 1][0] == '&' || 
data[index + 2][0] == '&' || data[index + 3][0] == '&' || 
data[index + 4][0] == '&')

{
   writeln("Some text...");
}


I don't want to write manually these four "or" conditions because 
in each case I know at compile time how many conditions should be.

I would be great if I could do something like this:

if(index + 3 >= data.length || mixin OrCondition!4) { ... }


where "OrCondition" will insert text using this expression:

data[index + j][0] == '&' // j is between [1 and 4]


I know that it is possible but don't know how to implement...


How to pass alias as template parameter?

2018-08-27 Thread Andrey via Digitalmars-d-learn

Hello,
This code doesn't compile:

---
import std.meta;
import std.stdio;

enum Option : string
{
First = "-first" ,
Second = "-second",
Qwerty = "-qwerty"
}

void handler(Option option)(string[] args, ref ushort index)
{
writeln("Case: ", args[index]);
}

void handler(string arg, ref ushort index)
{
writeln("Default: ", arg, " at index ", index);
}

alias Pair(alias key, alias value) = AliasSeq!(key, value);
alias Pairs = AliasSeq!(Pair!(Option.First, 
handler!(Option.First)), Pair!(Option.Second, 
handler!(Option.Second)), handler);


void parseArgs(alias sequence)(ushort index, string[] args)
{
alias last = sequence[$ - 1];
alias pairs = sequence[0 .. $ - 2];

for(ushort i = index; i < args.length; ++i)
{
string arg = args[i];
switch(arg)
{
static foreach(pair; pairs)
{
case pair.key:
pair.value(args, i);
break;
}

default:
last(arg, i);
break;
}
}
}

void main()
{
ushort index = 1;
string[] args = ["-second", "123", "-qaz", "true", "-first", 
"77", "value"];

parseArgs!Pairs(index, args);
}
---

Output:
onlineapp.d(52): Error: template instance `parseArgs!("-first", 
handler, "-second", handler, handler)` does not match template 
declaration parseArgs(alias sequence)(ushort index, string[] 
args)


I don't understand how to pass my "Pairs" alias into template 
function "parseArgs".


P.S. Yes, I know that exists "getopt".


Get max elemenr over RegexMatch

2018-08-24 Thread Andrey via Digitalmars-d-learn

Hello,
This code produces an error:

auto matches = content.matchAll(pattern);
auto max = matches.maxElement!"a => a.back.to!uint"();


I have a RegexMatch array like:
[["text1234", "1234"], ["zxs432fff", "432"], ["text000_", 
"000"]]

Max element here is 1234.

I apply map function "a => a.back.to!uint" to each Capture -> 
take last hit, convert it to uint and return for comparison.


But compiler says:
template std.algorithm.searching.extremum cannot deduce function 
from argument types !("a => a.back.to!uint", "a > 
b")(RegexMatch!(char[])), candidates are:

I can't understand what it wrong here.

This works:

matches.map!(a => a.back.to!uint)().maxElement()


I don't want to use this variant because, as I understand, here 
we create a temporary uint array and then search for max element. 
I.e. there is an unnecessary allocation of memory.


Test if variable has void value

2018-08-22 Thread Andrey via Digitalmars-d-learn

Hello,
How to test if variable has void value?


string text = void;
if(text == void)
{
   writeln("Is void");
}


Tried this:

if(is(text == void))

but doesn't work.


How to map elements of a tuple?

2018-08-22 Thread Andrey via Digitalmars-d-learn

Hello,
Is there a template/function/mixin... in the library that I can 
use to map elements of a tuple?


object.foo(Mapper!myMapFunction(1, bool, "Qwerty", 
EnumedColor.Red));


where "Mapper" is this mapper and "myMapFunction" is a template 
function that I want to apply to each member in tuple.


I know that there is std.algorithm.map but as I understand it is 
suitable only for arrays (types are the same).


[Unit tests] Mocking D objects

2018-08-22 Thread Andrey via Digitalmars-d-learn

Hello,
I know that D has build-in unit tests. If so, what mechanism D 
provides for mocking objects?

For example:

struct WebParser
{
   // ...

   int download(string path)
   {
   SomeHttpClient client(path);
   auto result = client.request(path, 10, "Qwerty");

   // ...

   return result.getSomething();
   }
}


Here I want to replace struct/class SomeHttpClient from 3d-party 
library with my own test implementation. Something like this 
maybe:

unittest
{
SomeMagicMockMechanism!(SomeHttpClient, MyMockedClient);

WebParser parser;
auto value = parser.download("www.example.com"); // uses 
MyMockedClient.request

assert(value == 10);

}


Re: Coreect way to create delegate for struct method.

2018-08-22 Thread Andrey via Digitalmars-d-learn

On Tuesday, 21 August 2018 at 22:52:31 UTC, Alex wrote:

Maybe, like this:


Thank you but here you use heap to create ab object. I want only 
on stack.

I know that one can do this:

test_handler.ptr = null;

and in place of call this:

handler.ptr = cast(void*)

but it is ugly...

Hmm, any other ideas?


Coreect way to create delegate for struct method.

2018-08-21 Thread Andrey via Digitalmars-d-learn

Hello,
This is a code:

import std.stdio;

struct Test
{
   static Test opCall()
   {
   Test test;
   test.handler = 

   return test;
   }

   void one() const { writeln("In handler: Address = ", , 
"; Text = ", text); }


   void execute()
   {
   text = "Inited!";
   writeln("Before: Address = ", , "; Text = ", text);
   handler();
   }

   void delegate() const handler = void;
   string text = "NoValue";
}

struct Qwerty
{
   void prepare()
   {
   _test = Test();
   }

   void execute()
   {
   _test.execute();
   }

private:
   Test _test  = void;
}

void main()
{
   Qwerty qwerty;
   qwerty.prepare();
   qwerty.execute();
}


Here I try to make a delegate for struct "Test" and method 
"one()".

When I launch it then I get this output:

Before: Address = 7FFC096A2C20; Text = Inited!
In handler: Address = 7FFC096A2BE8; Text = NoValue


It means that my delegate captures one object of Test, but in 
place of call uses another...
I want just to save my method into variable and after that use it 
on some arbitrary object of type "Test". How to do it in D?


In C++ it is very easy:

test.handler = ::one;

and call:

(this->*handler)();

or

(someTestObjPtr->*handler)();
I know axactly that in the first variant a context will be 
"this", and in the second - "someTestObjPtr".


Cast to original type each argument in template pack

2018-08-21 Thread Andrey via Digitalmars-d-learn

Hello,
I have a function:

string format(string pattern, T...)(T value)
{
   auto writer = appender!string();
   
writer.formattedWrite!pattern(convertToUnderlyingType(value)); 
//Tuple!T(value).expand.to!(OriginalType!T)


   return writer.data;
}


The "value" in this function can be any type including "enum". 
And if it is a "enum" I want to print it's contents not name.
So what I need - check if current argument in template pack is 
enum then convert it in original type. If current argument isn't 
enum - leave it as is. In my example I showed it with imaginary 
function "convertToUnderlyingType".

How to implement it in D?


Re: Deduce type of struct in function arguments

2018-08-21 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 17:45:25 UTC, Seb wrote:
... yet. Though you can vote for this DIP and show your support 
there:


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

It even comes with an implementation in DMD already:

https://github.com/dlang/dmd/pull/8460


How and where to vote?


Re: Make function alias

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 13:35:07 UTC, ag0aep6g wrote:

On 08/20/2018 03:14 PM, Andrey wrote:


Thanks everybody for your answers.


Re: Make function alias

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 13:14:14 UTC, Andrey wrote:
Mistake... this is:

static void log(bool newline = true)(string text)
{
   alias print(T...) = newline ?  : 

   _file.print(text);
   text.print();
}






Make function alias

2018-08-20 Thread Andrey via Digitalmars-d-learn

Hello,
I want to make an alias to function "std.stdio.writeln" and 
"std.stdio.write" and use it like:



static void log(bool newline = true)(string text)
{
   alias print(T...) = newline ?  : 

   _file.print();
   text.print();
}


Unfortunately, it doesn't work... Also tried with "enum print 
..." but also no success.

How to do it correctly?


Re: Deduce type of struct in function arguments

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 11:38:39 UTC, Paul Backus wrote:
Create an overload of foo that takes two arguments and combines 
them into a `Data` struct internally:


void foo(int a, string text)
{
Data data = {a, text};
foo(data);
}


Hmm, not very good solution. In C++ you can not to write type and 
compiler will deduce it automatically. In D, as I understand, 
this feature isn't supported.


Re: ushort + ushort = int?

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 09:56:13 UTC, Jonathan M Davis wrote:
It's a combination of keeping the C semantics (in general, C 
code is valid D code with the same semantics, or it won't 
compile) and the fact that D requires casts for narrowing 
conversions. When you add two shorts in C/C++, it converts them 
to int just like D does. It's just that C/C++ has implicit 
narrowing casts, so if you assign the result to a short, it 
then converts the result to short even if that means that the 
value could be truncated, whereas D requires that you 
explicitly cast to convert to int rather than silently 
truncating.


It does prevent certain classes of problems (e.g. there are 
plenty of bugs in C/C++ due to implicit narrowing conversions), 
but it can also get pretty annoying if you're doing much math 
on integer types smaller than int, and you either know that 
they aren't going to overflow or truncate, or you don't care 
that they will. But if you're only doing math on such small 
integeral types occasionally, then it pretty much just means 
that once in a while, you get briefly annoyed when you forget 
to add a cast, and the compiler yells at you.


- Jonathan M Davis


Understood.
Is there a workaround to reduce amount of manual casts of input 
types T into output T?
May be one can write some module-global operator "plus", 
"minus"..?


Like in C++:


template
T operator+(T first, T second)
{
   return static_cast(first + second);
}


Deduce type of struct in function arguments

2018-08-20 Thread Andrey via Digitalmars-d-learn

Hello,

I have a function and a struct:

void foo(ref Data data) { ... }



struct Data
{
   int a;
   string text;
}


How to pass struct into function without naming its type?

This doesn't work:


foo({1234, "Hello!"});


Re: ushort + ushort = int?

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 08:49:00 UTC, rikki cattermole wrote:
Yes. On x86 int's will be faster just an FYI so it does make 
sense to use them for computation.


Inconveniently always use casts. Why in D one decided to do in 
such way?


Re: ushort + ushort = int?

2018-08-20 Thread Andrey via Digitalmars-d-learn

On Monday, 20 August 2018 at 08:42:20 UTC, rikki cattermole wrote:

It's called integer promotion and it originates from C.
And yes C++ does have such support in some variant (I really 
don't feel like comparing the two).


And I should do? Always use "cast" operator when I operate not 
with ints?


ushort + ushort = int?

2018-08-20 Thread Andrey via Digitalmars-d-learn

Hello,
Here is a code that you can execute using online compiler 
https://run.dlang.io/:



import std.stdio;
void main()
{
   ushort first = 5;
   ushort second = 1000;

   ushort result = first + second;

   writeln(result);
}


I hae this error:
onlineapp.d(7): Error: cannot implicitly convert expression 
cast(int)first + cast(int)second of type int to ushort


Why they are "int" when I declared them as "ushort"???
ushort + ushort = ushort, not int.

In C++ there aren't any such issues...


Set optional function parameter

2018-08-17 Thread Andrey via Digitalmars-d-learn

Hello,
In D there is a nice function:

auto Tuple!(int,"status",string,"output") executeShell (
 scope const(char)[] command,
 const(string[string]) env = cast(const(string[string]))null,
 Config config = cast(Config)0,
 ulong maxOutput = 18446744073709551615LU,
 scope const(char)[] workDir = null,
 string shellPath = nativeShell()
) @trusted;


It has got 5 optional parameters. For example I want set only the 
fifth and all other leave with default values.


If it was C/C++ then I would write:
executeShell("my_command", nullptr, 0, 18446744073709551615, 
nullptr, "my/path");


Long and boring...

What about D? Does it support something like this:

executeShell("my_command", shellPath = "my/path");

or
executeShell("my_command", default, default, default, default, 
"my/path");


I mean - can I skip some arguments and set only one that I want?
Hm, Python, it seems to me, support this feature.


Convert output of map() to array of strings

2018-08-15 Thread Andrey via Digitalmars-d-learn

Hello,
I have the following code:

string[] list;
string text;
// ...
enum pattern = ctRegex!`^[0-9]+$`;
list = text.split('\n').map!(line => 
line.matchFirst(pattern).hit);


Compiler says that it can't convert result of map function to 
string[]...


What I want:
1. Split some text into lines using separator '\n'.
2. Apply to each line a regex pattern and extract matched text.
3. Result of these operations assign to variable of type string[].

Tried to do this:
list = text.split('\n').map!(line => 
line.matchFirst(pattern).hit).to!(string[]);

but no success...


Re: Concat enum of strings into one string

2018-08-15 Thread Andrey via Digitalmars-d-learn

On Tuesday, 14 August 2018 at 16:03:05 UTC, vit wrote:

import std.traits : EnumMembers;
import std.string : join;
import std.algorithm : map;

pragma(msg, [EnumMembers!Type].map!(x => cast(string)x).join(" 
"));


Thank you!

Jonathan M Davis, I understood.


Re: Concat enum of strings into one string

2018-08-14 Thread Andrey via Digitalmars-d-learn

On Tuesday, 14 August 2018 at 14:07:23 UTC, Timoses wrote:

Here's one version:

template StringEnumValues(alias Enum)
{
import std.traits : EnumMembers;
string[] StringEnumValues()
{
string[] enumValues;
static foreach (member; EnumMembers!Enum)
enumValues ~= member;
return enumValues;
}
}

import std.string : join;
pragma(msg, StringEnumValues!Type.join(" "));


Thank you. Hmm, I thought that standard library already has this 
stuff.


  1   2   >