Re: request assistance resolving curl error

2024-03-26 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 26 March 2024 at 07:13:24 UTC, confuzzled wrote:

Hello all,

I have two scripts. I copied the first directly from the alpaca 
website and massaged it with etc.c.curl until it compiled in D. 
The result is that it creates the order and returns the result 
to stdout. In the second script, I tried to use std.net.curl 
but cannot get it to work.


I think you should use the HTTP interface, did you check this 
docs?

https://dlang.org/phobos/std_net_curl.html#.HTTP
https://dlang.org/phobos/std_net_curl.html#.HTTP.addRequestHeader


Andrea


Re: how to assign multiple variables at once by unpacking array?

2023-10-08 Thread Andrea Fontana via Digitalmars-d-learn

On Sunday, 8 October 2023 at 07:44:04 UTC, Andrea Fontana wrote:


```
int a,b,c;

"1,2,3"
.splitter(',')
.zip(only(, , ))
.each!(x => *x[1] = x[0].to!int);

writeln(a, b, c);
```


or:

```
int a,b,c;

only(, , )
.zip("1,2,3".splitter(','))
.each!(x => *x[0] = x[1].to!int);

writeln(a, b, c);
```


Re: how to assign multiple variables at once by unpacking array?

2023-10-08 Thread Andrea Fontana via Digitalmars-d-learn

On Saturday, 7 October 2023 at 07:31:45 UTC, mw wrote:

https://stackoverflow.com/questions/47046850/is-there-any-way-to-assign-multiple-variable-at-once-with-dlang

How to do this Python code in D:

```

s = "1 2 3"
A,B,C = map(int, s.split(" "))
A,B,C

(1, 2, 3)

```

Is there a better way (since 2017)?


Ranges for the win!

```
int a,b,c;

"1,2,3"
.splitter(',')
.zip(only(, , ))
.each!(x => *x[1] = x[0].to!int);

writeln(a, b, c);
```


Re: importC - how to use more effectively?

2023-02-22 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 22 February 2023 at 15:00:56 UTC, WebFreak001 wrote:
I just first time used importC in a prototype project I just 
worked on. I used it to just import `libevdev.h` on linux to 
register a custom input device / make a simple userspace input 
driver.


A suggestion: try tcc as preprocessor. It works better than gcc 
for importc.


Andrea Fontana


Re: static assert("nothing")

2022-05-31 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 31 May 2022 at 09:52:10 UTC, realhet wrote:

On Tuesday, 31 May 2022 at 09:35:30 UTC, Andrea Fontana wrote:

On Tuesday, 31 May 2022 at 08:51:45 UTC, realhet wrote:
Check if that string is init.


assert("", "cool");
assert("ehh", "cool");
assert(string.init, "Not cool");

I feel some "JavaScript equality operator" vibes in this :D
Anyways, I will be extra careful with these.


assert(string.init is null) is the answer :)


Re: static assert("nothing")

2022-05-31 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 31 May 2022 at 08:51:45 UTC, realhet wrote:

Hi,

In my framework I just found a dozen of compile time error 
handling like:


...else static assert("Invalid type");

This compiles without error. And it was useless for detecting 
errors because I forgot the first "false" or "0" parameter.


The first is the assert condition, the message is opt.

I think it is because of the weird case of "every string casted 
to bool is true".


string s1;
string s2 = string.init; // Equivalent
string s3 = null; // Equivalent

string s4 = "";

assert(s1, "This fails");
assert(s2, "This fails too");
assert(s3, "This fails too");
assert(s4, "This pass");

There is an example in Phobos also:  
https://github.com/dlang/phobos/blob/master/std/uni/package.d

at line 8847: static assert("Unknown normalization form "~norm);

It is easy to make this mistake, but does static assert(string) 
has any meaningful use cases?


Check if that string is init.

Andrea




Re: CTFE and BetterC compatibility

2022-04-27 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 14:21:15 UTC, Claude wrote:

data.digits ~= parseDigit(str[0]);


Dynamic arrays are not supported using -betterC

Andrea





Re: How to print or check if a string is "\0" (null) terminated in the D programming language?

2022-04-06 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 6 April 2022 at 08:55:43 UTC, BoQsc wrote:
I have a feeling that some parts of my code contains 
unterminated strings and they do overflow into other string 
that is to be combined. I'd like to take a look at strings, 
analyse them manually and see if any of them end up terminated 
or not.


Please provide any relevant examples of how you do this.


string literals are zero-terminated in d.

If you need to pass a D string to a C function use toStringz()
https://dlang.org/library/std/string/to_stringz.html




Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-08 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 02:47:18 UTC, someone wrote:

https://dlang.org/articles/safed.html
https://dlang.org/dmd-linux.html#switches
http://ddili.org/ders/d.en/functions_more.html

Neither man dmd nor man dmd.conf appear to have a 
related/switch setting.


Does it means safeD is achieved by placing @safe attributes all 
over the place ? Or is it achieved by setting some global 
switch elsewhere ? Am I missing something ?


Just mark main() function with @safe and you're done.


Re: Idiomatic D code to avoid or detect devision by zero

2020-07-31 Thread Andrea Fontana via Digitalmars-d-learn
On Friday, 31 July 2020 at 13:55:18 UTC, Martin Tschierschke 
wrote:
What would be the idiomatic way to write a floating point 
division

occuring inside a loop and handle the case of division by zero.

c = a/b; // b might be zero sometimes, than set c to an other 
value (d).


(In the moment I check the divisor being zero or not, with an 
if-than-else structure,

but I find it ugly and so I ask here.)


You should give a look at:
https://dlang.org/phobos/std_experimental_checkedint.html

You can try with checked!Throw and catch exceptions, for example.

Andrea


Re: in not working for arrays is silly, change my view

2020-03-02 Thread Andrea Fontana via Digitalmars-d-learn
On Saturday, 29 February 2020 at 20:11:24 UTC, Steven 
Schveighoffer wrote:
1. in is supposed to be O(lg(n)) or better. Generic code may 
depend on this property. Searching an array is O(n).


Probably it should work if we're using a "SortedRange".


int[] a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
auto p = assumeSorted(a);

assert(3 in p);




Re: How to sum multidimensional arrays?

2020-02-27 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 27 February 2020 at 14:15:26 UTC, p.shkadzko wrote:

void main() {
int[][] m1 = rndMatrix(10, 2, 3);
int[][] m2 = rndMatrix(10, 2, 3);

auto c = m1[] + m2[];
}



I think you're trying to do this:

int[][] m1 = rndMatrix(10, 2, 3);
int[][] m2 = rndMatrix(10, 2, 3);
int[][] m3;

m3.length = m1.length;
foreach(i; 0..m1.length)
{
m3[i].length = m1[i].length;
m3[i][] = m1[i][] + m2[i][];
}

But of course that's not the best solution :)


Re: Error on using regex in dmd v2.088.1

2020-02-03 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 3 February 2020 at 07:11:34 UTC, Dharmil Patel wrote:

On Monday, 3 February 2020 at 07:03:03 UTC, Dharmil Patel wrote:

In my code I am using regex like this:

   auto rgxComma = regex(r",");

On compiling with dmd v2.076.1, it compiles successfully, but 
on compiling with dmd v2.088.1, I am getting lots of errors 
like:


/src/phobos/std/regex/internal/thompson.d-mixin-836(837): 
Error: template instance 
std.regex.internal.thompson.ThompsonOps!(EngineType!(char, 
Input!char), State, true).op!cast(IR)164u error instantiating


Can someone please help me solve this error?

Thanks
Dharmil


Hi Dharmil!
It works for me using 2.088.1 with docker.
Are you sure your installation is ok?

Andrea


Re: format with floating points GC allocating in DMD 2.090

2020-01-31 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 31 January 2020 at 08:45:55 UTC, bauss wrote:

On Friday, 31 January 2020 at 07:20:17 UTC, cc wrote:

char[4096] buf;
writeln(GC.stats.usedSize);
foreach (i; 0 .. 10) {
sformat(buf, "%f", 1.234f);
writeln(GC.stats.usedSize);
}



Report it as a bug because it's definitely a bug and there was 
changes to the GC in 2.090.0


2.086 x64 on linux:

0
64
112
160
208
256
304
352
400
448
496



Re: How to create a custom max() function without the ambiguity error.

2019-12-06 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 6 December 2019 at 12:34:17 UTC, realhet wrote:

Hi,

I'm trying to use a popular function name "max", and extend it 
for my special types:


For example:

module utils;
MyType max(in MyType a, in MyType a){...}  //static function

struct V3f{
  V3f max(in V2f b){...} //member function
}

module gl3n;
vec3 max(in vec3 a, in vec3 a) //another static function in 
different module


I also want to use std.algorithm.comparison.max as well.


I know that the ambiguity error can be avoided by public 
importing all the various max implementations into one place, 
but how to do this when I want to use 3 modules? Need a 4th 
module to combine them all? Is there a nicer way?
Another question that is it possible to extend the the template 
function "to" in more than one module and use it easily from my 
main project modules?


What about:

int max(int a, int b){ return 0; }

void main()
{
.max(3,4).writeln;  // 0
std.algorithm.comparison.max(3,4).writeln; // 4
}


Re: Slice/Substr [0..?lastIndexOf(".")] How refer itself without create a variable?

2019-12-05 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 5 December 2019 at 11:28:51 UTC, Marcone wrote:

Simple example:

writeln("Hi\nHow are 
you?\nGood".splitLines()[0][0..?lastIndexOf(r"\")]);


How to refer to this string in lastIndexOf() without create a 
variable?


Thank you.


One solution:

writeln(
"Hello\nHow are you?\nGood"
.splitLines()
.map!(x => x[0..x.lastIndexOf("o")])
);

But be careful: lastIndexOf could be < 0 if string is not found.


Re: Unexpectedly nice case of auto return type

2019-12-03 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 3 December 2019 at 09:48:39 UTC, Basile B. wrote:
You see what surprises me here is that we cannot express the 
special type that is `TypeNull` and that can only have one 
value (`null`) so instead we have to use `auto` or 
`typeof(null)`.


You can still create an alias anyway :)

alias TypeNull = typeof(null);





Re: Unexpectedly nice case of auto return type

2019-12-03 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 3 December 2019 at 07:24:31 UTC, Basile B. wrote:


A testA()
{
return alwaysReturnNull(); // Tnull can be implictly 
converted to A

}

still nice tho.


Why not [1]?

[1] typeof(null) alwaysReturnNull() { ... }

Andrea


Re: static assert(version(x)) ?

2019-11-26 Thread Andrea Fontana via Digitalmars-d-learn
On Tuesday, 26 November 2019 at 10:24:00 UTC, Robert M. Münch 
wrote:
How can I write something like this to check if any of a set of 
specific versions is used?


static assert(!(version(a) | version(b) | version(c)):

The problem is that I can use version(a) like a test, and the 
symbol a is not accessbile from assert (different, 
non-accessible namespace).


version(A) { enum isA = true; } else { enum isA = false; }
version(B) { enum isB = true; } else { enum isB = false; }

static assert(!(isA || isB));


Re: Anything like HPPTOD out there?

2019-11-25 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 25 November 2019 at 16:35:21 UTC, ParticlePeter wrote:
I would like to auto convert c++ header to d module. Is there 
some project aiming for this?


I know of VisualD c++ to d conversion wizzard [1] and LLVM 
tooling based CPP2D [2], both of them aiming for whole cpp 
conversion. But I a searching for something lightweight like 
HTOD extended to C++.


[1] https://rainers.github.io/visuald/visuald/CppConversion.html
[2] https://github.com/lhamot/CPP2D


Give DPP[1] a try!

[1] https://github.com/atilaneves/dpp




Re: What is the point of a synchronized lock on a single return statement?

2019-11-25 Thread Andrea Fontana via Digitalmars-d-learn
On Monday, 25 November 2019 at 09:24:43 UTC, Jonathan M Davis 
wrote:
On Monday, November 25, 2019 1:22:17 AM MST Andrej Mitrovic via 
Digitalmars- d-learn wrote:
From: 
https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8 c03/std/concurrency.d#L1913-L1916:


-
///
final @property bool isClosed() @safe @nogc pure
{
 synchronized (m_lock)
 {
 return m_closed;
 }
}
-

I don't understand the purpose of this lock. The lock will be 
released as soon as the function returns, and it returns a 
copy of a boolean anyway. Am I missing something here?


It ensures that no other code that locks m_lock is running when 
m_closed is accessed. I'd have to study std.concurrency in 
detail to know for sure why that would be needed, but it's not 
atypical when trying to maintain consistent state when multiple 
threads are interacting with each other.


- Jonathan M Davis



Probably to be sure to have a consistent status returned. See for 
example:


https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/std/concurrency.d#L2250




Re: Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?

2019-10-18 Thread Andrea Fontana via Digitalmars-d-learn
On Friday, 18 October 2019 at 10:55:59 UTC, Martin Tschierschke 
wrote:
Yes, it works as it is, but it is not the best solution to 
share know how.


I agree. I think D.learn should be moved to stackoverflow and 
D.general should stay here.


Re: How does one cast to an array type?

2019-10-17 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 17 October 2019 at 12:19:03 UTC, Vinay Sajip wrote:
Are arrays and objects part of a unified type system? 
Specifically, if I do


void foo(Object x) {
if (typeid(x) == typeid(Object[])) {
auto a = cast(Object[]) x;
}
}

I get a compilation error:

onlineapp.d(3): Error: cannot cast expression x of type 
object.Object to Object[]


What's the way to achieve the cast, which should be safe given 
the typeid check?


Thanks and regards,

Vinay Sajip


Did you try templates? It seems easier:
https://run.dlang.io/is/BbkTCw

Andrea



Re: How does D distnguish managed pointers from raw pointers?

2019-10-03 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 3 October 2019 at 14:13:55 UTC, IGotD- wrote:

According to the GC documentation this code snippet

char* p = new char[10];
char* q = p + 6; // ok
q = p + 11;  // error: undefined behavior
q = p - 1;   // error: undefined behavior

suggests that char *p is really a "fat pointer" with size 
information.


No it's not. char* is a plain pointer.

The example is wrong, since you can't assign a new char[10] to 
char*.


Probably they mean something like:
auto arr = new char[10]
char* p = arr.ptr;
...

This code actually compiles, but its behaviour is undefined, so 
it is a logical error.



In D arrays are fat pointer instead:

int[10] my_array;

my_array is actually a pair ptr+length.



Re: Using algorithms with ranges

2019-10-03 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 3 October 2019 at 05:33:04 UTC, mipri wrote:

void main() {
import std.range : iota;

foreach (x; iota(1, 10).withHistory)
writeln(x);
}



This doesn't work as expected, I think.

auto r = iota(1,10).withHistory;

writeln(r.front);
writeln(r.front);


Re: Avoid gratuitous closure allocations

2019-09-20 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 20 September 2019 at 11:21:22 UTC, Ali Çehreli wrote:
tl;dr Instead of returning an object that uses local state, 
return an object that uses member variables.


Really good to know tips!


Re: How'd I store possible types for each item of a list of Variants ?

2019-09-20 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 20 September 2019 at 08:58:09 UTC, oleobal wrote:


I'm kind of out of ideas at this point. Would anyone have an 
elegant solution to this problem?


Thanks !


Is this ok for you: https://run.dlang.io/is/VllpJk ?

Andrea



Re: Problem with using std.math: abs and std.complex: abs at the same time

2019-09-18 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 18 September 2019 at 12:03:28 UTC, berni wrote:

The following code doesn't compile:


import std.stdio;

void main()
{
   import std.complex: abs, complex;
   import std.math: abs;

   auto a = complex(1.0,1.0);
   auto b = 1.0;

   writeln(abs(a));
   writeln(abs(b));
}


What about https://run.dlang.io/is/PGasQD ?



Re: Dynamic array + AA array

2019-09-17 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 17 September 2019 at 14:33:30 UTC, Brett wrote:
The idea is to basically use a dynamic array for most of the 
items, then an array to get the rest.


T[] Base;
T[int] Rest;

Then if Base has a max size(usually it might be fixed due to 
some algorithm) the Rest AA can pick up any outside values 
easily.


The idea here is to be able to combine them as one "infinite" 
array of T.


Any indexing outside of Base gets carried in to Rest.


What if I try to read an index that was not assigned?
What if I try a foreach on it?




Re: Using CSS Data from Within My Code

2019-09-12 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 12 September 2019 at 09:54:35 UTC, Ron Tarrant wrote:

I found this presented as a solution in a 2016 post:

On Wednesday, 15 June 2016 at 22:05:37 UTC, captaindet wrote:


enum myCSS = q{
GtkNotebook {
background-color: #e9e9e9;
}
GtkNotebook tab {
background-color: #d6d6d6;
}
};


But when I try to use it, I get the following errors:

Warning: C preprocessor directive #e9e9e9 is not supported
Warning: C preprocessor directive #d6d6d6 is not supported

I thought it was odd having 'q' in front of the opening curly 
brace... is this a typo? Shorthand for "string quote"? 
Something like that?


Or do I need to escape these somehow?


They are named "token string" and contained code must be a valid 
d code. See https://dlang.org/spec/lex.html#token_strings




Re: Meaning of Scoped! ??

2019-07-30 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 30 July 2019 at 09:33:04 UTC, Ron Tarrant wrote:
Some things are almost impossible to research. For instance, in 
the GtkD wrapper code—specifically the Widget.d file—the 
following function definition appears:



	gulong addOnDraw(bool delegate(Scoped!Context, Widget) dlg, 
ConnectFlags connectFlags=cast(ConnectFlags)0)

{
		return Signals.connect(this, "draw", dlg, connectFlags ^ 
ConnectFlags.SWAPPED);

}



Scoped is a struct defined here:
https://github.com/gtkd-developers/GtkD/blob/e14091fb2df4d05348061f274c131700af89fb16/generated/gtkd/glib/c/types.d#L56

Looking at its source code, it seems it's a way to force the call 
of "destroy" method of wrapped object (Context in your case) when 
the struct goes out of its scope (and d-tor is called)


Andrea




Re: What is iota function full name

2019-06-21 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 21 June 2019 at 09:24:54 UTC, lili wrote:

in dictionary iota means:
a tiny or scarcely detectable amount
the 9th letter of the Greek alphabet
 but this function is not that mean.


Full answer:
https://stackoverflow.com/questions/9244879/what-does-iota-of-stdiota-stand-for


Re: Simultaneously assigning to all values in a tuple

2019-04-01 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 1 April 2019 at 10:12:50 UTC, Simen Kjærås wrote:

On Monday, 1 April 2019 at 09:46:34 UTC, Jacob Carlborg wrote:

On 2019-03-28 01:29, Jamie wrote:
Is it possible to assign to all values in a tuple at once if 
they are the same type?

I.e.

Tuple!(double, "x", double, "y") t;
t[] = 1.0;



Yes:

Tuple!(double, "x", double, "y") t;
t.expand = AliasSeq!(3.1, 4.2);


Since the question was how to assign to all values in a tuple:"

t.expand = Repeat!(2, 1.0);


t.expand = Repeat!(t.length, 1.0);




Re: Tuple!(string, int))[] field_orders

2019-03-14 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 14 March 2019 at 15:29:28 UTC, Ozan wrote:

Hi
In vibe.d / data / mongo / collection  I found the function
* ensureIndex(Tuple!(string, int))[] field_orders)

What could be the right way to use "Tuple!(string, int))[] 
field_orders"?
I tried different ways like [Tuple!("a", 1), Tuple!("b", 2)]", 
but compiler said "No"


Any hint?

Thanks & Regards,
Ozan


field_orders' type: Tuple!(string, int)[]

So you have to use [Tuple!(string, int)("b",2), ...]  or 
(shortcut) [tuple("b", 2), ...]




Andrea



Re: bug in doc?

2019-03-14 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 14 March 2019 at 14:22:52 UTC, spir wrote:

https://dlang.org/spec/hash-map.html#static_initialization:

immutable long[string] aa = [
  "foo": 5,
  "bar": 10,
  "baz": 2000
];


If I'm right, you can't use this syntax with global array. Insted 
this works:


void main()
{
  immutable long[string] aa = [
"foo": 5,
"bar": 10,
"baz": 2000
  ];
}

You should init global AAs using static this() { } as explained 
in the same doc


Andrea


Re: local class instance (at module-level)

2019-03-14 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 14 March 2019 at 11:05:22 UTC, spir wrote:


The most confusing error is:
Error: variable `_base.c0` is a thread-local class and cannot 
have a static initializer. Use `static this()` to initialize 
instead.


Error is reffering to: 
https://dlang.org/spec/module.html#staticorder


You can do this:

C c0;

static this()
{
 c0 = new C();
}

Andrea


Re: Strange appender behavior

2019-03-13 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 13 March 2019 at 13:03:27 UTC, tchaloupka wrote:

Is this expected?:

```
import std.stdio;
import std.algorithm;
import std.array;

void main()
{
auto d = Appender!string();
//auto d = appender!string(); // works

string[] arr = ["foo", "bar", "baz"];
arr.joiner("\n").copy(d);
writeln(d.data);
}
```

Using Appender outpust nothing, using appender works ok.


It sounds like a bug. If you use Appender!string(null) it works 
fine. Probably a problem with _data init?


Re: sort!("...") with template function?

2019-02-25 Thread Andrea Fontana via Digitalmars-d-learn
On Monday, 25 February 2019 at 12:37:31 UTC, Vladimirs Nordholm 
wrote:

Hello.

I wish to sort an array by calling a template function on a 
struct. In essence I want to do


foos.sort!("a.get!Dummy < b.get!Dummy");

but I get the error message


/dlang/dmd/linux/bin64/../../src/phobos/std/functional.d-mixin-215(215): Error: undefined identifier Dummy


Is there anyway I can get `sort` to recognise my Dummy type?

Example: https://run.dlang.io/is/9zDfdd


Maybe:
foos.sort!((a,b) => a.get!Dummy < b.get!Dummy);

Andrea


Re: Weird const behavior

2018-12-20 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 20 December 2018 at 14:49:10 UTC, Marko wrote:
But is this right? I mean if they are equal shouldn't they have 
the same behavior?


I don't think so:

float a = 1.0;
long b = 1;

writeln(a == b);
writeln(a/2 == b/2);






Re: Reverse and sort array elements

2018-12-18 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 18 December 2018 at 12:47:59 UTC, Andrey wrote:

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.


You call "array" the enum just like the array() function.
Change enum array into enum arr and array.map!... into arr.map!...


Re: D do not know which function to use apparently

2018-12-11 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 11 December 2018 at 15:17:10 UTC, Narxa wrote:

Yes, it worked:
---
int var = cast(int) floor(sqrt( cast(float) n ));


I thought floor already returned an 'int' but I was mistaken.

Thank you very much.


I think you don't need floor.

int var = cast(int)(sqrt(cast(float)n));

or:

int var = cast(int)(float(i).sqrt);

or:

int var = float(i).sqrt.to!int;

Andrea


Re: Wrapping a Dub project inside Meson

2018-11-22 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 22 November 2018 at 02:46:03 UTC, Adnan wrote:
Does anyone have experience with using meson to wrap around a 
dub project?


I have a typical dub project, meaning I have a dub dependency 
but I want to use meson for two reasons:


1. I want to distribute the application in form of a snap 
package (https://snapcraft.io/). Snapcraft does not recognize 
dub as a build tool afaik.


2. dub lacks very basic options like installing an app in 
users' PATH (https://github.com/dlang/dub/issues/839). The 
issue seems to be stalled for a while, which is quite a shame.


What I want to do is basically when I write `ninja` it should 
invoke `dub build`.


I would like to have a "dub plugin" for snapcraft (and other 
packaging systems).
Adding "install" to dub sounds it's like re-inventing the wheel 
to me.


Andrea





Re: Writing Postgresql extension in D

2018-11-15 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 15 November 2018 at 13:05:59 UTC, Ranjan wrote:
This is my first time on the Dlang forum. I like the language 
but my usecase is a bit different.


I want to write Postgresql extension in D. Currently extension 
can be written in C or C linked languages. Has anyone done this 
or can point me to some code.


Thanks


Did you read this: https://dlang.org/spec/interfaceToC.html ?

Andrea


Re: std.socket tutorials? examples?

2018-10-04 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 4 October 2018 at 08:32:13 UTC, Chris Katko wrote:

I've been Google'ing and there's like... nothing out there.

One of the top results for "std.socket dlang examples"... is 
for TANGO. That's how old it is.


Socket paradigm is quite standard across languages.

Anyway you can find a couple of example here:
https://github.com/dlang/dmd/blob/master/samples/listener.d
https://github.com/dlang/dmd/blob/master/samples/htmlget.d

Andrea


Re: Private struct constructor

2018-10-04 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 4 October 2018 at 07:31:21 UTC, Ritchie wrote:

Any reason why this works?

https://run.dlang.io/is/TALlyw


Why not?


Re: Template return type?

2018-10-03 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 3 October 2018 at 09:37:29 UTC, JN wrote:
int i = returnDefault!int(); obviously works, but the point is 
I would like to skip the explicit type.


See: 
https://forum.dlang.org/post/ufhibwmouxpivjylq...@forum.dlang.org




Re: How to implement D to HTML pages ?

2018-10-03 Thread Andrea Fontana via Digitalmars-d-learn
On Tuesday, 2 October 2018 at 18:27:04 UTC, Aurélien Plazzotta 
wrote:
Thank you both for all the links! I guess DiamondMVC is very 
powerful but I would rather avoid using such heavy artillery. 
I'm expecting the learning curve to be very long.


I currently use two libraries I wrote to keep things easy.

https://code.dlang.org/packages/arrogant
https://code.dlang.org/packages/reserved

The first one is a html5 parser. So you don't need any template, 
you can directly read html and then edit them just like you are 
used to do in js, for example.


For example:
   auto src = `Hello 
World`;

   auto arrogant = Arrogant();
   auto tree = arrogant.parse(src);

   // Change div content from "Hello World!" to "Hello D!"
   tree.byTagName("div").front.innerText = "Hello D!";

   // Print the edited html
   writeln(tree.document);

The second library is a scgi library that allow you to send data 
to any webserver that support scgi (f.e. nginx). It works like 
php:


import reserved;

@ReservedResponse
private void response(Request req, Output output)
{
   output ~= "Hello ";

   if ("name" in req.get)
  output ~= req.get["name"];
   else
  output ~= "World";

   // Using the library above you can do something like this 
instead:

   // output ~= tree.document;
}

mixin Reserved!"awesome_d_webservice";

So if you combine those two libraries you can output a 
validated/well-formed html5 document in a easy way.


Andrea


Re: Weird compilation error only as static library

2018-09-28 Thread Andrea Fontana via Digitalmars-d-learn
On Wednesday, 26 September 2018 at 19:08:45 UTC, Márcio Martins 
wrote:

Hi!

I am getting this error when compiling my code as a static 
library.

It works fine as an executable. I have no idea what's happening.
Has someone seen something like this before? What could be 
different?


This is the error:
/usr/include/dmd/druntime/import/core/stdc/stdint.d(159,26): 
Error: undefined identifier cpp_ulong

/usr/include/dmd/druntime/import/core/sys/posix/sys/types.d(109,11): Error: 
undefined identifier c_long
../../../.dub/packages/libuv-1.20.3/libuv/deimos/libuv/uv.d(367,2): Error: 
mixin `deimos.libuv.uv.uv_stream_s.UV_STREAM_FIELDS!()` error instantiating

It's a small library with libuv as the only dependency. It 
works fine compiling it's own example, but fails when I compile 
it as a dub dependency.


What are you importing on top of your code?

Andrea


Re: std.process: spawnProcess

2018-09-07 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 7 September 2018 at 14:36:42 UTC, Russel Winder wrote:
From what I can see, processes created with std.process: 
spawnProcess are not terminated when the creating process 
terminates, i.e. it seems Config.detached is the default for 
these process.


Is there a way of all spawned processes being terminated on 
main termination?





void main()
{

...
auto yourpid = spawnProcess(...);
scope(exit) kill(yourpid, SIGINT); // Or SIGKILL :)
// Or: scope(exit) wait(yourpid);
...
}

Andrea


Re: Is there any reason to use non-ref foreach?

2018-09-04 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 4 September 2018 at 07:06:43 UTC, Dukc wrote:
On Monday, 3 September 2018 at 13:34:36 UTC, Andrea Fontana 
wrote:

On Friday, 31 August 2018 at 09:59:20 UTC, Dukc wrote:
For me, it seems that for generality you should always add 
ref into foreach loop variable. The reason is this:


One good reason:
https://forum.dlang.org/thread/dlhrrgvzmhladnphi...@forum.dlang.org


I am almost sure it will stay how it is, because of the sheer 
amount of breakage changing that would cause. I still agree 
that in princliple, the general way to iterate should be 
something else (auto ref?). But as with autodecoding, the 
present way is already in too wide use to be worth changing.


But I think we need an official line to confirm whether one can 
use that without risking a deprectation.


Waiting for this to be merged:
https://github.com/dlang/dmd/pull/8437



Re: Is there any reason to use non-ref foreach?

2018-09-03 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 31 August 2018 at 09:59:20 UTC, Dukc wrote:
For me, it seems that for generality you should always add ref 
into foreach loop variable. The reason is this:


One good reason:
https://forum.dlang.org/thread/dlhrrgvzmhladnphi...@forum.dlang.org




Re: DStep rocks [was Example of using C API from D?]

2018-09-03 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 3 September 2018 at 10:50:17 UTC, Russel Winder wrote:
Interesting alternative to DStep. I came to D to avoid 
#include, but… I'll give it a whirl once I can get it compiled 
on Debian Sid. It seems the libclang-dev package does not 
install a libclang.so symbolic link, you have to be explicit 
about which version you want, e.g. libclang- 6.0.so on my 
Debian Sid installation.


I use dpp to generate d code to import:
- Create a temp.dpp file with #include inside
- Run "d++ --preprocess-only temp.dpp"

Now you have your .d file exactly like in dstep.

Andrea


Re: Pass lambda into template

2018-09-03 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 3 September 2018 at 09:09:44 UTC, Andrey wrote:

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)


Not the best solution, but did you try to make querty template 
global adding a third parameter to pass count?


Andrea


Re: Why std.array : array needs pure postblit?

2018-06-15 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 15 June 2018 at 11:48:59 UTC, Andrea Fontana wrote:

On Friday, 15 June 2018 at 11:25:49 UTC, Basile B. wrote:

Hello, i've tested locally and it can works by making 
`Appender.reserve()` and `Appender.ensureAddable()` function 
templates.




That was my idea too. But I wonder if pureness of reserve and 
ensureAddable have a particular reason.


My point is: if we remove pure from those functions it is 
inferred , isn't it? Why does we need to force it there?


Re: Why std.array : array needs pure postblit?

2018-06-15 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 15 June 2018 at 11:25:49 UTC, Basile B. wrote:

Hello, i've tested locally and it can works by making 
`Appender.reserve()` and `Appender.ensureAddable()` function 
templates.




That was my idea too. But I wonder if pureness of reserve and 
ensureAddable have a particular reason.


Why std.array : array needs pure postblit?

2018-06-15 Thread Andrea Fontana via Digitalmars-d-learn

Check this code:
https://run.dlang.io/is/PoluHI

It won't work, because array appender requires a pure postblit.

Why? Can we remove this limitation?

Andrea


Re: Is DWT busted?

2018-06-09 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 8 June 2018 at 05:00:57 UTC, TheGag96 wrote:
I'm sorry about bringing this into here instead of DWT's 
subforum, but it's somewhat dead and hasn't been getting a lot 
of attention. I decided to finally play around with DWT today 
and tried to build the example.


It's a known bug. I opened it on GitHub for kubuntu.




Re: how to define infix function

2018-06-04 Thread Andrea Fontana via Digitalmars-d-learn

On Saturday, 2 June 2018 at 23:17:48 UTC, Simen Kjærås wrote:

unittest
{
import std.algorithm.comparison;

alias min = Operator!(std.algorithm.comparison.min);

assert(1 /min/ 3 == 1);
}



Why not:

alias Δ = Operator!(std.algorithm.comparison.min);
assert(1 /Δ/ 3 == 1);

To improve readibility :)


Re: UDA and static struct fields

2018-05-24 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 24 May 2018 at 10:23:41 UTC, Andrea Fontana wrote:

On Thursday, 24 May 2018 at 09:17:10 UTC, Alex wrote:

On Thursday, 24 May 2018 at 08:48:30 UTC, Andrea Fontana wrote:


This line:

  mixin("alias tmp = " ~ s ~ ";");

There's no mention of Symbol in there. If you change it to 
this:


  mixin("alias tmp = Symbol" ~ s ~ ";");

then suddenly things work.

--
  Simen


What?


a dot is missing, but essentially, Simen found it :)

Line 20 in https://run.dlang.io/is/OGHJYX should be:

mixin("alias tmp = Symbol." ~ s ~ ";");


Whoops I didn't get it.
Thank you both.

Andrea


Why didn't that return any error, anyway?


Re: UDA and static struct fields

2018-05-24 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 24 May 2018 at 09:17:10 UTC, Alex wrote:

On Thursday, 24 May 2018 at 08:48:30 UTC, Andrea Fontana wrote:


This line:

  mixin("alias tmp = " ~ s ~ ";");

There's no mention of Symbol in there. If you change it to 
this:


  mixin("alias tmp = Symbol" ~ s ~ ";");

then suddenly things work.

--
  Simen


What?


a dot is missing, but essentially, Simen found it :)

Line 20 in https://run.dlang.io/is/OGHJYX should be:

mixin("alias tmp = Symbol." ~ s ~ ";");


Whoops I didn't get it.
Thank you both.

Andrea


Re: UDA and static struct fields

2018-05-24 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 24 May 2018 at 07:59:08 UTC, Simen Kjærås wrote:

On Thursday, 24 May 2018 at 07:47:54 UTC, Andrea Fontana wrote:

Is this a bug or am I missing something?

https://run.dlang.io/is/OGHJYX


Andrea


This line:

  mixin("alias tmp = " ~ s ~ ";");

There's no mention of Symbol in there. If you change it to this:

  mixin("alias tmp = Symbol" ~ s ~ ";");

then suddenly things work.

--
  Simen


What?


UDA and static struct fields

2018-05-24 Thread Andrea Fontana via Digitalmars-d-learn

Is this a bug or am I missing something?

https://run.dlang.io/is/OGHJYX


Andrea


Re: Speed of math function atan: comparison D and C++

2018-03-06 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 5 March 2018 at 20:11:06 UTC, H. S. Teoh wrote:
Walter has been adamant that we should always compute 
std.math.* functions with the `real` type

T


I don't understand why atan(float) returns real and atan(double) 
return real too. If I'm working with float, why does it return a 
real? If you want to comute with real is ok, but shouldn't be T 
atan(T) rather than real atan(T)?


I'm missing something.

Andrea


Re: single loop copy in D

2018-03-02 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 2 March 2018 at 09:44:20 UTC, psychoticRabbit wrote:

trying to do this C code, in D, but getting error:
"Error: assignment cannot be used as a condition, perhaps `==` 
was meant?"


any help much appreciated:

--
while ((*dst++ = *src++)) {}
--


You can't use this syntax inside a while/if/... to prevent 
mistakes due to similarity between assignment syntax (=) and 
comparison syntax (==)


Andrea



Re: iota to array

2018-02-25 Thread Andrea Fontana via Digitalmars-d-learn
On Sunday, 25 February 2018 at 09:30:12 UTC, psychoticRabbit 
wrote:

I would have preffered it defaulted java style ;-)

System.out.println(1.0); // i.e. it prints 'what I told it to 
print'.


System.out.println(1.0); // print 1.0
System.out.println(1.0); // print 1.0

So it doesn't print "what you told it to print"

Andrea Fontana


Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit

2018-02-14 Thread Andrea Fontana via Digitalmars-d-learn
On Wednesday, 14 February 2018 at 11:16:25 UTC, Martin 
Tschierschke wrote:

Ok, good to know!
I started with 16.04 and made the initial mistake to take the 
32 Bit version,

do you use 32 or 64 Bit?


64bit of course!

Andrea


Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit

2018-02-14 Thread Andrea Fontana via Digitalmars-d-learn
On Tuesday, 13 February 2018 at 22:21:18 UTC, Martin Tschierschke 
wrote:
I will downgrade to 16.04., the dist-upgrade to 17.10 was a 
mistake, resulting in problems with startx and newer kernels so 
I have to use 4.10.


In my experience dist-upgrade are long and messy :)
Usually I create a partition on disk; install a fresh (K)ubuntu 
on that partition; move data / config from old partition to new; 
delete (or backup) old partition.


I have both kubuntu 17.04 and 17.10 and dmd works fine.

Andrea


Re: package modules and how to generate a shared library plus .di file (I)

2017-12-07 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 7 December 2017 at 16:39:14 UTC, kdevel wrote:
Then (*) works as expected. But why do I have to use the prefix 
"mymod.:" in the

library case?


Because module names are not relative to file path, but to import 
path / compile path afaik.


Re: Directory Size

2017-12-06 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 6 December 2017 at 14:49:48 UTC, Vino wrote:


Hi Andrea,

  Thank you very much, as your code is pretty good for our 
scenario, just one request, the above is a part of our main 
code where we have many such sub code and all of our sub code 
use the container array(std.container.array) rather than 
standard array(std.array), so can you please guide me on how to 
implement the same code using the container array.


From,
Vino.B.


Just use Array! constructor.

auto mSize () {
string FFs = "/home/andrea/Scaricati";

   return
   Array!(Tuple!(string,string))(
   dirEntries(FFs, SpanMode.shallow)
   .filter!(a => a.isDir)
   .map!(a => tuple(a.name, 
a.dirEntries(SpanMode.depth).filter!(a=>a.isFile).map!(a => 
a.size).sum))

   .filter!(a => a[1] > 1024*1024*30)
   .map!(a => tuple(a[0], a[1].to!string))
   );
}



Re: Directory Size

2017-12-06 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 5 December 2017 at 17:21:29 UTC, Vino wrote:

Hi All,

 Is there any better ways to get the size of folders , The 
below code perfectly works , but i need return type as 
Array!(Tuple!(string, string)) rather then using the 
"Result.insertBack(d); 
Result.insertBack(to!string(SdFiles[].sum))" as per the below 
example.


E.g:
Array!(Tuple!(string, string)) Result;
Result = (d, to!string(SdFiles[].sum));

Program:
import std.algorithm: filter, map, sum, uniq;
import std.container.array;
import std.file: dirEntries, SpanMode, isDir, isFile;
import std.stdio: writeln;
import std.typecons: tuple, Tuple;
import std.conv: to;
/**/
/* Sub Function : Size of Dir List*/
/**/
auto mSize () {
string FFs = "C:\\Temp\\BACKUP";
Array!string Result;
	auto dFiles = Array!string ((dirEntries(FFs, 
SpanMode.shallow).filter!(a => a.isDir)).map!(a => a.name));

foreach (d; dFiles[])   {
		auto SdFiles = Array!ulong((dirEntries(d, 
SpanMode.depth).filter!(a => a.isFile)).map!(a => a.size));
		if (SdFiles[].sum / 1024 / 1024  > 30) { 
Result.insertBack(d); 
Result.insertBack(to!string(SdFiles[].sum)); }

}
return Result;
}

void main() {
writeln(mSize[]);
}

From,
Vino.B


Something like:

auto mSize () {
string FFs = "C:\\Temp\\BACKUP";

   return dirEntries(FFs, SpanMode.shallow)
   .filter!(a => a.isDir)
   .map!(a => tuple(a.name, 
a.dirEntries(SpanMode.depth).filter!(a=>a.isFile).map!(a => 
a.size).sum))

   .filter!(a => a[1] > 1024*1024*30)
   .map!(a => tuple(a[0], a[1].to!string))
   .array;
}

?


Re: Object oriented programming and interfaces

2017-12-05 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 5 December 2017 at 07:47:32 UTC, Dirk wrote:

What would be a good way to implement this?


Did you tried to use introspection?


Re: Passing Function as an argument to another Function

2017-12-04 Thread Andrea Fontana via Digitalmars-d-learn
On Monday, 4 December 2017 at 08:27:10 UTC, rikki cattermole 
wrote:

On 04/12/2017 8:22 AM, Vino wrote:

Hi All,

   Request your help on the below code, I want to send the 
name of the function ( First and Second) from main as an 
argument to another function(Mid) and the function "Mid" has 
to execute the function(First and Second).


Program:
import std.stdio;

void First (string Ftext) {
writeln("First :", Ftext);
}

void Second (string Stext) {
writeln("Second :", Stext);
}

void Mid( string Fun, string Mtext) {
Fun(Mtext);
}

void main () {
string Ftext = "FTest1";
string Stext = "STest2";
Mid(First, Mtext);
Mid(Second, Stext);
}

From,
Vino.B


Maybe:

import std.stdio;

void Mid(alias Fun)(string Mtext) {
Fun(Mtext);
}

void main () {
string Ftext = "FTest1";
string Stext = "STest2";
Mid!First(Ftext);
Mid!Second(Stext);
}


Re: Decimal handling for currency (precision)

2017-11-23 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 23 November 2017 at 14:47:21 UTC, aberba wrote:
Some suggest working with the lowest currency denomination to 
avoid decimal precision handling and only convert to the 
highest denominations (decimal) when displaying. I've also seen 
some use decimal value handling libraries.


I'm thinking lowest denominations will result in extremely 
large values that D's type system cannot store (if such large 
values makes sense or can happen with money in real life).


What will be your advise on the type to use by default, the 
currency denominations (100p instead of 1.0 dollars), and cost 
of computation.


From d-money doc:

"Here the design decision is to use an integer for the internal 
representation. This limits the amounts you can use. For example, 
if you decide to use 4 digits behind the comma, the maximum 
number is 922,337,203,685,477.5807 or roughly 922 trillion. The 
US debt is currently in the trillions, so there are certainly 
cases where this representation is not applicable. However, we 
can check overflow, so if it happens, you get an exception thrown 
and notice it right away. The upside of using an integer is 
performance and a deterministic arithmetic all programmers are 
familiar with."


922 trillion (+4 digits after comma) should be enough for common 
computations.


Re: reduce condition nesting

2017-11-23 Thread Andrea Fontana via Digitalmars-d-learn
On Thursday, 23 November 2017 at 13:47:37 UTC, Adam D. Ruppe 
wrote:

On Thursday, 23 November 2017 at 05:19:27 UTC, Andrey wrote:

for instance in kotlin it can be replace with this:

when {
c1 -> foo(),
c2 -> bar(),
c3 -> ...
else -> someDefault()
}


The `switch` statement covers some of these cases too.


Anyway you can create something like this:
https://run.dlang.io/is/7pbVXT



Re: reduce condition nesting

2017-11-23 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 23 November 2017 at 05:19:27 UTC, Andrey wrote:

Hello, is there way to reduce this condition:

if (c1) {
foo();
} else {
if (c2) {
bar();
} else {
if (c3) {
...
}
}
}


for instance in kotlin it can be replace with this:

when {
c1 -> foo(),
c2 -> bar(),
c3 -> ...
else -> someDefault()
}


if (c1) foo()
else if (c2) bar();
else if (c3) ...
else someDefault();

?



Re: User defined type and foreach

2017-11-16 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 16 November 2017 at 08:03:48 UTC, Tony wrote:
I made a stack data type and created an opIndex() so it could 
be turned into a dynamic array, and created empty() 
(unfortunate name), front() and popFront() methods, which I 
read allow it to be used with foreach.


However, when I use the class with foreach, the opindex gets 
called to create a dynamic array, rather than use the 
empty(),front(),popFront() routines. I would prefer it use the 
three methods, rather than create a dynamic array.


You can try to implement opApply().
Check:
http://ddili.org/ders/d.en/foreach_opapply.html



Re: Missing return value error not present with template

2017-11-15 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 15 November 2017 at 08:43:01 UTC, Tony wrote:

This code:
class MyClass {

public:
   int SomeMethod ()
   {

   }

}


void main()
{

}

gets a compile error:
Error: function test_warnings.MyClass.SomeMethod has no return 
statement, but is expected to return a value of type int


but if I make it a template class:

class MyClass(T) {

there is no compile error. I don't know why the error isn't 
given for the template code as well.


Because it's a template! If you try to instantiate it, it gives 
the same error. For example MyClass!int a;


Re: string version of array

2017-11-14 Thread Andrea Fontana via Digitalmars-d-learn
On Tuesday, 14 November 2017 at 07:56:06 UTC, rikki cattermole 
wrote:

On 14/11/2017 7:54 AM, Tony wrote:
Is there an easy way to get the string representation of an 
array, as would be printed by writeln(), but captured in a 
string?


struct Foo {
int x;  
}

void main() {
Foo[] data = [Foo(1), Foo(2), Foo(3)];

import std.conv : text;
import std.stdio;

writeln(data.text);
}

---

[Foo(1), Foo(2), Foo(3)]


Why not

import std.conv : to;
writeln(data.to!string);

?


Re: Writing some built-in functions for Bash, possible?

2017-10-18 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 18 October 2017 at 03:48:01 UTC, Ky-Anh Huynh wrote:

Hi,

I'm using Bash heavily in my systems. Things become slow and 
slow when I have tons of scripts :) And sometimes it's not easy 
to manipulate data.


You may have heard of recutils [1] which has a C extension to 
be loaded by Bash. Is it possible to write similar things in D, 
for Bash? I am not good at C; it's great if I explore this 
field:)


Some examples in C are in [2].

My experience: Dlang has `pipe` support however the syntax is 
not as clean as Bash :) Most of the times I see short (<1k loc) 
Bash scripts are easy to maintain than Ruby (and now D things) 
scripts.


Thanks for your reading.

[1]: https://news.ycombinator.com/item?id=15302035
[2]: 
http://git.savannah.gnu.org/cgit/bash.git/tree/examples/loadables/cat.c


You can write your script in D using
#!/usr/local/bin/rdmd
as shebang line.

Or, using dstep, you can convert C headers to D imports, so you 
can compile your own extension in D.


Andrea


Re: Splitting a sequence using a binary predicate on adjacent elements

2017-10-18 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 18 October 2017 at 07:26:20 UTC, Nordlöw wrote:
On Wednesday, 18 October 2017 at 07:01:19 UTC, Andrea Fontana 
wrote:
If you try to use your data with chunkBy!"a != b+1", it does 
not work, as expected.


What's the motivation behind this limitation?

Without it

chunkBy!"a + 1 == b"

is exactly what I want.


Probably it's an implementation problem. On source code you read:

// Issue 13595
version(none) // This requires support for non-equivalence 
relations

@system unittest
{
import std.algorithm.comparison : equal;
auto r = [1, 2, 3, 4, 5, 6, 7, 8, 9].chunkBy!((x, y) => 
((x*y) % 3) == 0);

assert(r.equal!equal([
[1],
[2, 3, 4],
[5, 6, 7],
[8, 9]
]));
}

And other.



Re: Splitting a sequence using a binary predicate on adjacent elements

2017-10-18 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 18 October 2017 at 06:45:37 UTC, Nordlöw wrote:
On Tuesday, 17 October 2017 at 14:15:02 UTC, Andrea Fontana 
wrote:

auto splitBy(alias F, R)(R range)


Because of lazyness shouldn't it be named something with 
splitter, say splitterBy, instead?


Yes but I think it is something more similar to chunkBy, but 
chunkBy says that "predicate must be an equivalence relation, 
that is, it must be reflexive (pred(x,x) is always true), 
symmetric (pred(x,y) == pred(y,x)), and transitive (pred(x,y) && 
pred(y,z) implies pred(x,z)). If this is not the case, the range 
returned by chunkBy may assert at runtime or behave erratically."


If you try to use your data with chunkBy!"a != b+1", it does not 
work, as expected.


I think that my implementation could superseed the current one, 
since it seems to work in a more generic way.


Andrea


Re: Splitting a sequence using a binary predicate on adjacent elements

2017-10-17 Thread Andrea Fontana via Digitalmars-d-learn

More phobos-ized version:

https://run.dlang.io/is/iwgeAl

Andrea




Re: Splitting a sequence using a binary predicate on adjacent elements

2017-10-17 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 13:09:18 UTC, Nordlöw wrote:
I can't find any algorithm/range in Phobos that can be used to 
split (eagerly or lazily) a sequence using a binary predicate 
on adjacent elements as follows


[1,2,3,5,10,11,12,13,20,21,100].splitBy!"a + 1 != b"()

should evaluate to

[[1,2,3], [5], [10,11,12,13], [20,21], [100]]

.

Is there one?


Try this:

import std.range;
import std.algorithm;
import std.stdio;

import std.typecons;

auto splitBy(alias F, R)(R range)
{

auto tmp = range
.map!(x => tuple(x, 0))
		.cumulativeFold!((a,b) => tuple(b[0], 
(!F(a[0],b[0]))?a[1]:a[1]+1))

.chunkBy!((a,b) => a[1] == b[1])
.map!(x => x.map!(y => y[0]));

return tmp;
}

void main()
{
	[1,2,3,5,10,11,12,13,20,21,100].splitBy!((a,b) => a+1 != 
b)().writeln;

}


Andrea


Re: initializing a static array

2017-10-10 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 10 October 2017 at 13:53:37 UTC, jmh530 wrote:

double[n] bar;
bar[] = 0;


This works at runtime only for mutable arrays, anyway.



Re: initializing a static array

2017-10-10 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 10 October 2017 at 13:36:56 UTC, Simon Bürger wrote:
Is there a good way to set them all to zero? The only way I can 
think of is using string-mixins to generate a string such as 
"[0,0,0,0]" with exactly n zeroes. But that seems quite an 
overkill for such a basic task. I suspect I might be missing 
something obvious here...


Maybe:

double[n] bar = 0.repeat(n).array;


Re: Does writing from NNTP work?

2017-10-04 Thread Andrea Fontana via Digitalmars-d-learn
On Wednesday, 4 October 2017 at 14:18:52 UTC, Tristan B. Kildaire 
wrote:

Does this work?


No, I don't read you. Try again :)


Re: Struct bug?

2017-10-02 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 2 October 2017 at 09:08:59 UTC, Biotronic wrote:
Not knowing what you're attempting to do, I'm not sure how to 
fix your problem. But if what I've described above does indeed 
cover it, initializing b in the constructor is the way to get 
it to work.


--
  Biotronic


Obviusly real example is quite different and larger.
Anyway: you cant put a default destructor on struct


Struct bug?

2017-10-02 Thread Andrea Fontana via Digitalmars-d-learn

Why this code doesn't write two identical lines?

https://dpaste.dzfl.pl/e99aad315a2a

Andrea


Re: Internal error mixing templates and CTFE

2017-09-15 Thread Andrea Fontana via Digitalmars-d-learn

On Friday, 15 September 2017 at 05:58:47 UTC, David Bennett wrote:

Is this an error in dmd, and should I open a bug report?


Internal error is always a bug, so it should be reported!

Andrea


Re: I need library for QR codes generation.

2017-09-06 Thread Andrea Fontana via Digitalmars-d-learn

On Wednesday, 6 September 2017 at 14:30:24 UTC, MGW wrote:
I need library for generation of QR codes. Who knows, give the 
link.


You can try to bind a c library like [1] using dstep. It should 
be easy.


Andrea

[1] https://github.com/fukuchi/libqrencode



Re: Problem with std.string.strip(): Can't use result in format routine

2017-09-05 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 5 September 2017 at 13:40:18 UTC, Ky-Anh Huynh wrote:

On Tuesday, 5 September 2017 at 13:17:34 UTC, Azi Hassan wrote:


Maybe it has something to do with how you read from STDIN. Can 
you show that part of the code to see if I can reproduce the 
issue ?


I used `lines(stdin)` as in 
https://dlang.org/phobos/std_stdio.html#.lines . My source code 
is here


https://github.com/icy/dusybox/blob/master/src/plotbar/main.d#L47 .

Thanks for your support.


I think formattedRead is consuming your string.

Andrea


Re: replace switch for mapping

2017-09-05 Thread Andrea Fontana via Digitalmars-d-learn
On Monday, 4 September 2017 at 20:54:27 UTC, EntangledQuanta 
wrote:
On Monday, 4 September 2017 at 09:23:24 UTC, Andrea Fontana 
wrote:
On Thursday, 31 August 2017 at 23:17:52 UTC, EntangledQuanta 
wrote:
Generally one has to use a switch to map dynamic components. 
Given a set X and Y one can form a switch to map X to Y:


[...]


Does this work for you?
https://dpaste.dzfl.pl/e2669b595539

Andrea


No, do you realize you are passing those enums at compile time? 
It won't work if they are "runtime" variables, which is the 
whole point of doing all this. You've essentially make a simple 
problem complicated. Why not just overload foo properly?


So at runtime you can do in a couple of ways if i'm right:
http://dpaste.com/02W9FX6

Andrea



Re: replace switch for mapping

2017-09-04 Thread Andrea Fontana via Digitalmars-d-learn
On Thursday, 31 August 2017 at 23:17:52 UTC, EntangledQuanta 
wrote:
Generally one has to use a switch to map dynamic components. 
Given a set X and Y one can form a switch to map X to Y:


[...]


Does this work for you?
https://dpaste.dzfl.pl/e2669b595539

Andrea




Re: How to make autocompletion for IDE?

2017-07-26 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 10:45:38 UTC, unDEFER wrote:

On Tuesday, 25 July 2017 at 10:35:14 UTC, Andrea Fontana wrote:

If you want to add UFCS suggestions to DCD it would be useful 
for your project and all other IDEs too!


Andrea


Thank you, I will think. But if it was easy, authors self would 
do it :-)


Did you try with [1]?

[1] http://forum.dlang.org/post/okktlu$2bin$1...@digitalmars.com


Re: How to make autocompletion for IDE?

2017-07-25 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 10:32:11 UTC, unDEFER wrote:
Yes this project where "Not working: UFCS suggestions and That 
one feature that you REALLY needed".. I want to have all 
features that I really need :-)
But If I will not find how do UFCS suggestions fast, I probably 
will use DCD for all other things..


If you want to add UFCS suggestions to DCD it would be useful for 
your project and all other IDEs too!


Andrea


Re: How to make autocompletion for IDE?

2017-07-25 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 10:23:33 UTC, Andrea Fontana wrote:

On Tuesday, 25 July 2017 at 10:06:47 UTC, unDEFER wrote:

Any ideas?


I think you should use/contribute to DCD project
https://github.com/dlang-community/DCC

Andrea


Sorry, this is the right link:
https://github.com/dlang-community/DCD


Re: How to make autocompletion for IDE?

2017-07-25 Thread Andrea Fontana via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 10:06:47 UTC, unDEFER wrote:

Any ideas?


I think you should use/contribute to DCD project
https://github.com/dlang-community/DCC

Andrea


Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 24 July 2017 at 15:21:54 UTC, Houdini wrote:

Hello,

I am a C++ coder, and I am learning D (just reading a book, for 
now).


D is very similar to C++ (and also grabs godd ideas from 
Python), but I have a naive question : why does Walter Bright 
chose to instanciate classes like in Java ? And why is it 
different for structs ?


Maybe this will help you:
https://stackoverflow.com/questions/10965577/usage-preference-between-a-struct-and-a-class-in-d-language





Re: Avoid if statements for checking neighboring indexes in a 2D array

2017-07-17 Thread Andrea Fontana via Digitalmars-d-learn

On Sunday, 16 July 2017 at 10:37:39 UTC, kerdemdemir wrote:
My goal is to find connected components in a 2D array for 
example finding connected '*'

chars below.


You can also use a queue to avoid recursion that should improve 
performances and readibility.


Probably using ndslice library could help you!

Andrea


Re: Check if a variadic argument is numeric?

2017-07-06 Thread Andrea Fontana via Digitalmars-d-learn

On Thursday, 6 July 2017 at 12:15:56 UTC, Hamborg wrote:
That compiles, but it returns false when I pass in a numeric 
value... :(


I think you should provide a code snippet then. I think I missed 
something about your question.


Andrea


  1   2   3   4   >