Re: Is there an alias for standard libraries to use in import statement?

2021-07-04 Thread Bastiaan Veelo via Digitalmars-d-learn

On Sunday, 4 July 2021 at 07:40:44 UTC, BoQsc wrote:
I just started with a fresh look at the D language and would 
like to be able to rewrite this code:



import std;
void main()
{
writeln("Hello D");
}


Into more readable standard library name:


import system;
void main()
{
writeln("Hello D");
}


That is [easy](https://run.dlang.io/is/af8dMY), just define the 
`system` module and publicly `import std`:


--- test.d
```d
import system;
void main()
{
writeln("Hello D");
}
```

--- system.d
```d
module system;
public import std;
```

But like Mike, I advise against this. It will confuse every D 
programmer that is trying to read your code. What is most natural 
depends heavily on your background and what language you are 
coming from. `std` is perfectly natural if you're coming from C++.


Fun fact (but equally ill advised): You can hide the entire 
import from view like this:

```d
void main()
{
writeln("Hello D");
}

/* Lean on Enter for a while */

import std;
```

-- Bastiaan.


Re: Is there an alias for standard libraries to use in import statement?

2021-07-04 Thread BoQsc via Digitalmars-d-learn

On Sunday, 4 July 2021 at 08:50:54 UTC, Mike Parker wrote:


You can use named imports, but then you have to use the name as 
a namespace:


```
import system = std;
void main()
{
system.writeln("Hello D");
}
```



These were the examples that might feel more readable and 
natural than simply a three letter junction:

import std;



What do you think?


If you're worried about the readability of `std` by itself, 
don't use it by itself. Import the specific modules you want:


```
import std.algorithm, std.range, std.stdio;
```



Thank you for showing the alternative.


or whatever. It's a non-issue, IMO. It's not like anyone using 
D doesn't know what std is.


It's not about knowing or not knowing, it's about the reading 
flow and ease on the thinking.
For me, it's always better to have things spelled correctly. 
Constant abbrevations do feel unnatural to me, even if I'm 
familiar of the complexity behind it.


Anyways, even if it is possible as you shown. I'm feeling like 
it's still non standard way and might confuse people when the 
whole D code base with community is about importing std library 
directly. But I'm glad I won't have to think about this problem 
anymore and that's important to have less important questions 
answered for more important things to accomplish.


Re: Is there an alias for standard libraries to use in import statement?

2021-07-04 Thread Mike Parker via Digitalmars-d-learn

On Sunday, 4 July 2021 at 07:40:44 UTC, BoQsc wrote:
I just started with a fresh look at the D language and would 
like to be able to rewrite this code:



import std;
void main()
{
writeln("Hello D");
}


Into more readable standard library name:


import system;
void main()
{
writeln("Hello D");
}


You can use named imports, but then you have to use the name as a 
namespace:


```
import system = std;
void main()
{
system.writeln("Hello D");
}
```



These were the examples that might feel more readable and 
natural than simply a three letter junction:

import std;



What do you think?


If you're worried about the readability of `std` by itself, don't 
use it by itself. Import the specific modules you want:


```
import std.algorithm, std.range, std.stdio;
```

or whatever. It's a non-issue, IMO. It's not like anyone using D 
doesn't know what std is.


Is there an alias for standard libraries to use in import statement?

2021-07-04 Thread BoQsc via Digitalmars-d-learn
I just started with a fresh look at the D language and would like 
to be able to rewrite this code:



import std;
void main()
{
writeln("Hello D");
}


Into more readable standard library name:


import system;
void main()
{
writeln("Hello D");
}


Or into this


import library.standard;
void main()
{
writeln("Hello D");
}



Or into this:


import library phobos;
void main()
{
writeln("Hello D");
}


These were the examples that might feel more readable and natural 
than simply a three letter junction:

import std;



What do you think?


Re: What's a good approach to DRY with the block code of a case-statement?

2021-04-28 Thread z via Digitalmars-d-learn
I'd recommend you to use templates with alias parameters but you 
mentioned that you need to retain function context(for gotos, 
continue, break, etc...)
One thing you could do is mix the ugly mixin solution with the 
good one:

```D
//inside the function, so that you can access locals
pragma(inline, true)
string getDRYstr(T, parameters...)() {
static assert(__ctfe);
string mixedinstr;
mixedinstr ~= /*code*/;
static if(/**/){mixedinstr ~= /*code*/;}
//...
mixedinstr ~= "break;";
return mixedinstr
}
```
There is no doubt that it is an ugly solution but the time saved 
not copy-pasting code could be worth it.


Re: What's a good approach to DRY with the block code of a case-statement?

2021-04-26 Thread ag0aep6g via Digitalmars-d-learn

On Monday, 26 April 2021 at 20:39:55 UTC, Jack wrote:
I have a block of code that the only thing that change is the 
type passed in one of the template functions called so I'd like 
to make a DRY for this. But I'm not just replacing by a 
function due to control-flow, for example, there are 
if-statements where one just break and the other return 0. I 
think I could do something with mixin() that would kinda mimic 
C's macro but I still find it messy. Any alternatives?


```d
static int doSomething()
{
switch(val)
{
case VAL_FOO:
auto obj = getObject!MyType(someData); // this is the 
type

   // that changes
if(obj.shouldExit()) break;

auto m = Message(...);
if(obj.doSomethingElse(m)) return 0;
break;

   // ...

   default:
}

return doSomethingY();
}
```


I think you're looking for this D idiom:

```d
sw: switch (rt_value)
{
static foreach (ct_value; ct_values)
{
case ct_value: some_template!ct_value; break sw;
}
}
```

Applied to your code it might look like this:

```d
import std.meta: AliasSeq;
alias stuff = AliasSeq!(VAL_FOO, MyType, VAL_BAR, MyOtherType, /* 
... */);

sw: switch (val)
{
static foreach (i; 0 .. stuff.length / 2)
{
case stuff[i]:
auto obj = getObject!(stuff[i + 1])(someData);
if(obj.shouldExit()) break sw;
auto m = Message(...);
if(obj.doSomethingElse(m)) return 0;
break sw;
}
}
```


What's a good approach to DRY with the block code of a case-statement?

2021-04-26 Thread Jack via Digitalmars-d-learn
I have a block of code that the only thing that change is the 
type passed in one of the template functions called so I'd like 
to make a DRY for this. But I'm not just replacing by a function 
due to control-flow, for example, there are if-statements where 
one just break and the other return 0. I think I could do 
something with mixin() that would kinda mimic C's macro but I 
still find it messy. Any alternatives?


```d
static int doSomething()
{
switch(val)
{
case VAL_FOO:
auto obj = getObject!MyType(someData); // this is the 
type

   // that changes
if(obj.shouldExit()) break;

auto m = Message(...);
if(obj.doSomethingElse(m)) return 0;
break;

   // ...

   default:
}

return doSomethingY();
}
```

Maybe my least resort, if I went to replace by a function, I 
could do something like this:


```d
enum OP { BREAK, RETURN }
pragma(inline, true):
OP foo(T)()
{   
auto obj = getObject!T(someData); // this is the type

   // that changes
if(obj.shouldExit()) return OP.BREAK;

auto m = Message(...);
if(obj.doSomethingElse(m)) return OP.RETURN;

return OP.BREAK;
}
```

then:

```d
static int doSomething()
{
switch(val)
{
case VAL_FOO:
auto r = foo!MyType();
if(r == OP.BREAK) break;
if(r == OP.RETURN0) return 0;
break;

   // ...

   default:
}

return doSomethingY();
}
```

I still find this not much elegant. If anyone knows a better way 
to do this, help are very welcome


Re: .d files without a module statement? Required to be absent?

2020-11-14 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Nov 14, 2020 at 05:55:13PM +, WhatMeWorry via Digitalmars-d-learn 
wrote:
> 
> I was poking around the dmd code just to "learn from the best"

IMNSHO, Phobos is more representative of typical D code than dmd; dmd
code was automatically translated from C++, so a lot of it may still
have a lot of C++-isms that wouldn't be in "native" D code.


> and I came across some files that ended with the .d extension which
> did not have the module statement. (I was under the naive impression
> that all .d files must have a module statement)

No, if there is no module declaration, the module name will be inferred
from the filename.


T

-- 
"You know, maybe we don't *need* enemies." "Yeah, best friends are about all I 
can take." -- Calvin & Hobbes


Re: .d files without a module statement? Required to be absent?

2020-11-14 Thread Paul Backus via Digitalmars-d-learn

On Saturday, 14 November 2020 at 17:55:13 UTC, WhatMeWorry wrote:


I was poking around the dmd code just to "learn from the best" 
and I came across some files that ended with the .d extension 
which did not have the module statement. (I was under the naive 
impression that all .d files must have a module statement)


If a .d file does not have a module statement, the compiler will 
infer the name of the module from the path of the file. So, the 
file `foo/bar.d` will have its module name inferred as `foo.bar`.


There is one exception to this: the file `foo/package.d` will 
have its module name inferred as `foo`, not `foo.package`.


.d files without a module statement? Required to be absent?

2020-11-14 Thread WhatMeWorry via Digitalmars-d-learn



I was poking around the dmd code just to "learn from the best" 
and I came across some files that ended with the .d extension 
which did not have the module statement. (I was under the naive 
impression that all .d files must have a module statement)


However, in the directory:

https://github.com/dlang/dmd/blob/master/samples

I can see many examples where this is not the case. Most of them 
have things like Windows or C structures or calls, etc.


In stark difference, there is

https://github.com/dlang/dmd/tree/master/src/dmd/backend

where all its files seem to have file name = module name strictly 
enforced.


So I guess my question is when is the module statement required?  
Are they recommended but not essential?  Maybe some "Best 
Practices" notation?


the spec sasy "Modules automatically provide a namespace scope 
for their contents..." so maybe my question becomes, when are 
namespace scopes required to be present or required to be absent?





Re: can't access an alias created inside an if statement

2020-08-05 Thread Flade via Digitalmars-d-learn

On Wednesday, 5 August 2020 at 09:39:47 UTC, Simen Kjærås wrote:

On Wednesday, 5 August 2020 at 09:32:58 UTC, Flade wrote:
Thanks! You see it should work but the thing is. I'm using it 
inside a function. I'm checking for one of the function's 
parameter (if parameter == false) and it says that "the 
variable `parameter` cannot be read at compile time. Do you 
know if there is a way to fix this?


As the error message says, the value must be known at compile 
time. Most likely, you can simply pass it as a template 
parameter:


void fun(bool parameter)(int arg1, string arg2) {
static if (parameter) {
}
}

void main() {
fun!true(1, "foo");
fun!false(19, "bar");
}

--
  Simen


Thanks man! Works as expected! Have a great day!


Re: can't access an alias created inside an if statement

2020-08-05 Thread Simen Kjærås via Digitalmars-d-learn

On Wednesday, 5 August 2020 at 09:32:58 UTC, Flade wrote:
Thanks! You see it should work but the thing is. I'm using it 
inside a function. I'm checking for one of the function's 
parameter (if parameter == false) and it says that "the 
variable `parameter` cannot be read at compile time. Do you 
know if there is a way to fix this?


As the error message says, the value must be known at compile 
time. Most likely, you can simply pass it as a template parameter:


void fun(bool parameter)(int arg1, string arg2) {
static if (parameter) {
}
}

void main() {
fun!true(1, "foo");
fun!false(19, "bar");
}

--
  Simen


Re: can't access an alias created inside an if statement

2020-08-05 Thread Flade via Digitalmars-d-learn

On Wednesday, 5 August 2020 at 09:25:23 UTC, Simen Kjærås wrote:

On Wednesday, 5 August 2020 at 09:05:36 UTC, Flade wrote:
I have used an if-else statement to create an alias to avoid 
code duplication but it doesn't let me access it outside the 
if statement. Is there a way to solve this?


You're probably looking for static if:

static if (useAlias) {
alias myAlias = getAlias!();
}

myAlias foo = getFoo();


What happens is a regular if statement introduces a scope, so 
anything declared inside it is unavailable outside. static if 
does not introduce a new scope, and so its contents can be 
accessed.


static if only works with compile-time constant conditions, but 
aliases are also compile-time constructs, so this should not 
pose a problem.


--
  Simen


Thanks! You see it should work but the thing is. I'm using it 
inside a function. I'm checking for one of the function's 
parameter (if parameter == false) and it says that "the variable 
`parameter` cannot be read at compile time. Do you know if there 
is a way to fix this?


Re: can't access an alias created inside an if statement

2020-08-05 Thread Simen Kjærås via Digitalmars-d-learn

On Wednesday, 5 August 2020 at 09:05:36 UTC, Flade wrote:
I have used an if-else statement to create an alias to avoid 
code duplication but it doesn't let me access it outside the if 
statement. Is there a way to solve this?


You're probably looking for static if:

static if (useAlias) {
alias myAlias = getAlias!();
}

myAlias foo = getFoo();


What happens is a regular if statement introduces a scope, so 
anything declared inside it is unavailable outside. static if 
does not introduce a new scope, and so its contents can be 
accessed.


static if only works with compile-time constant conditions, but 
aliases are also compile-time constructs, so this should not pose 
a problem.


--
  Simen


can't access an alias created inside an if statement

2020-08-05 Thread Flade via Digitalmars-d-learn
I have used an if-else statement to create an alias to avoid code 
duplication but it doesn't let me access it outside the if 
statement. Is there a way to solve this?


Re: Unable to access a variable declared inside an if statement (Error: is shadowing variable)

2020-05-27 Thread BoQsc via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 11:13:09 UTC, Simen Kjærås wrote:

On Wednesday, 27 May 2020 at 11:03:51 UTC, BoQsc wrote:
I'm lacking knowledge on how to achieve what I want and 
getting an error.
What is the correct way to do what I tried to achieve in this 
code?
Everything was intuitive until I started to add notice 
variable to the writeln. Rdmd says  variable `notice` is 
shadowing variable.



if (driveLetter.exists){
auto directory = "/Backup";
if ((driveLetter ~ directory).exists){
auto notice = "Backup directory exists.";

}
writeln(driveLetter, notice);
}


Variables only live in a specified scope, starting from where 
they are declared, and ending when they reach the '}' 
indicating the end of said scope.


In you case, 'notice' only lives inside the if ((driveLetter ~ 
directory).exists) scope, and doesn't exist outside. In order 
to fix this, you will need to declare it outside:


if (driveLetter.exists) {
auto directory = "/Backup";
auto notice = "Backup directory does not exist.";
if ((driveLetter ~ directory).exists) {
notice = "Backup directory exists.";
}
writeln(driveLetter, notice);
}

This also makes it clearer what value 'notice' will have when 
the backup directory doesn't exist - in your case you haven't 
assigned it any value in that case.


--
  Simen


That's correct. Thanks Simen.


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

auto drivesLetters = [
"A:", "I:", "Q:", "Y:",
"B:", "J:", "R:", "Z:",
"C:", "K:", "S:", "D:", "L:", "T:",
"E:", "M:", "U:",
"F:", "N:", "V:",
"G:", "O:", "W:",
"H:", "P:", "X:",
];

foreach (string driveLetter; drivesLetters) {
if (driveLetter.exists) {
auto notice = "";
if ((driveLetter ~ "/Boot").exists) {
notice ~= "\\Boot directory exists";
notice ~= " ";
}
if ((driveLetter ~ "/Windows").exists) {
notice ~= "\\Windows folder exists";
notice ~= " ";
}
writeln(driveLetter, notice);
}

}


}


Re: Unable to access a variable declared inside an if statement (Error: is shadowing variable)

2020-05-27 Thread Simen Kjærås via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 11:03:51 UTC, BoQsc wrote:
I'm lacking knowledge on how to achieve what I want and getting 
an error.
What is the correct way to do what I tried to achieve in this 
code?
Everything was intuitive until I started to add notice variable 
to the writeln. Rdmd says  variable `notice` is shadowing 
variable.



if (driveLetter.exists){
auto directory = "/Backup";
if ((driveLetter ~ directory).exists){
auto notice = "Backup directory exists.";

}
writeln(driveLetter, notice);
}


Variables only live in a specified scope, starting from where 
they are declared, and ending when they reach the '}' indicating 
the end of said scope.


In you case, 'notice' only lives inside the if ((driveLetter ~ 
directory).exists) scope, and doesn't exist outside. In order to 
fix this, you will need to declare it outside:


if (driveLetter.exists) {
auto directory = "/Backup";
auto notice = "Backup directory does not exist.";
if ((driveLetter ~ directory).exists) {
notice = "Backup directory exists.";
}
writeln(driveLetter, notice);
}

This also makes it clearer what value 'notice' will have when the 
backup directory doesn't exist - in your case you haven't 
assigned it any value in that case.


--
  Simen


Unable to access a variable declared inside an if statement (Error: is shadowing variable)

2020-05-27 Thread BoQsc via Digitalmars-d-learn
I'm lacking knowledge on how to achieve what I want and getting 
an error.
What is the correct way to do what I tried to achieve in this 
code?
Everything was intuitive until I started to add notice variable 
to the writeln. Rdmd says  variable `notice` is shadowing 
variable.


rdmd output:

C:\Users\vaida\Desktop>rdmd searchDirectory.d
searchDirectory.d(21): Error: variable `notice` is shadowing 
variable `searchDirectory.main.notice`
Failed: ["C:\\D\\dmd2\\windows\\bin\\dmd.exe", "-v", "-o-", 
"searchDirectory.d", "-I."]


searchDirectory.d

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

auto drivesLetters = [
"A:", "I:", "Q:", "Y:",
"B:", "J:", "R:", "Z:",
"C:", "K:", "S:", "D:", "L:", "T:",
"E:", "M:", "U:",
"F:", "N:", "V:",
"G:", "O:", "W:",
"H:", "P:", "X:",
];

foreach (string driveLetter; drivesLetters) {
string notice;
if (driveLetter.exists){
auto directory = "/Backup";
if ((driveLetter ~ directory).exists){
auto notice = "Backup directory exists.";

}
writeln(driveLetter, notice);
}

}


}




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

2019-11-25 Thread Robert Schadek via Digitalmars-d-learn
But be aware, even though the bool is returned from a 
synchronized block,

its actual value has no meaning at all.

All the meaning you get out of that bool is that the MessageBox 
was closed

when you called that function.
If there is a function in MessageBox that can reopen the instance,
you can not assume that the MessageBox is still closed when you
read the bool.
Assuming your program has more than one thread touching that 
instance of

the MessageBox.

Consider

```
auto mb = new MessageBox();
bool c = mb.isClosed();
// this thread gets preempted, and another thread
// does something with mb that changes its state

if(!c) { // the value of c might not what you expected
   // start rockets
}
```

This problem, at least partly, spawn concepts like Monitors,
the Rendezvous concept, Message Passing, and others.


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

2019-11-25 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/25/19 3:22 AM, Andrej Mitrovic wrote:
From: 
https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/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?


Locks ensure the CPU and compiler use the correct memory model. It's 
complicated, but necessary. Look up Herb Sutter's atomic weapons talk. 
The key takeaway is that the "gurus" who make compilers and cpus have 
the rule "If you use mutex locks, the code will behave like you wrote it 
for all observations". With out the locks, crazy things can happen.


Note also, that even though x86 CPUs are atomic for single values 
without locks, not all CPUs are. However, I think a bool is likely 
always atomic. But that doesn't mean the compiler or CPU will not 
reorder your instructions. The locks keep it consistent.


-Steve


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

2019-11-25 Thread angel via Digitalmars-d-learn
On Monday, 25 November 2019 at 08:22:17 UTC, Andrej Mitrovic 
wrote:
From: 
https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/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?


I think this code can be rewritten as
---
final @property bool isClosed() @safe @nogc pure
{
bool ret;

synchronized (m_lock)
{
ret = m_closed;
}

return ret;
}
---

Normally, if the memory location of m_closed is aligned, the 
assignment to 'ret' should be atomic, however if you cannot make 
assumptions about alignment, the access should be protected.


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: What is the point of a synchronized lock on a single return statement?

2019-11-25 Thread Jonathan M Davis via Digitalmars-d-learn
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





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

2019-11-25 Thread Andrej Mitrovic via Digitalmars-d-learn
From: 
https://github.com/dlang/phobos/blob/10b9174ddcadac52f6a1ea532deab3310d3a8c03/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?


Re: "if" statement

2019-03-25 Thread Michelle Long via Digitalmars-d-learn

On Sunday, 24 March 2019 at 12:45:13 UTC, Francesco Mecca wrote:

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

```
alias Alg = Algebraic!(int, string);

void main()
{
int n = 2;
Alg value;

value = n == 2 ? 2 : "string";
}
```

The original code used SumType but the effect is the same.

I suppose that I could write the following:

```
if(n == 2) value = 2;
else value = "string";
```

Is there a workaround for this that maintains a similar 
syntactic structure?
is this behaviour accepted or should the compiler translate the 
first case in the second?


You could make a Choose function:

auto Ch(A,B)(bool c, A a, B b);

Then

value = Ch(n == 2, n, "string");

Not much different than

value = (n == 2) ? Alg(2) : Alg("string");

except you don't have to write Alg all the time.

The compiler should translate the first but that requires 
implicit conversion of any of the types T... to Algebraic!T... . 
Of course, that should be possible but is it?











Re: "if" statement

2019-03-25 Thread Benjamin Schaaf via Digitalmars-d-learn

On Sunday, 24 March 2019 at 12:45:13 UTC, Francesco Mecca wrote:

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

```
alias Alg = Algebraic!(int, string);

void main()
{
int n = 2;
Alg value;

value = n == 2 ? 2 : "string";
}
```

The original code used SumType but the effect is the same.

I suppose that I could write the following:

```
if(n == 2) value = 2;
else value = "string";
```

Is there a workaround for this that maintains a similar 
syntactic structure?
is this behaviour accepted or should the compiler translate the 
first case in the second?


You can achieve the same thing by just constructing your 
algebraic type earlier:


  value = n == 2 ? Alg(2) : Alg("string");


Re: "if" statement

2019-03-24 Thread ag0aep6g via Digitalmars-d-learn

On 24.03.19 13:45, Francesco Mecca wrote:

```
alias Alg = Algebraic!(int, string);

void main()
{
 int n = 2;
     Alg value;

     value = n == 2 ? 2 : "string";
}
```

The original code used SumType but the effect is the same.

I suppose that I could write the following:

```
     if(n == 2) value = 2;
     else value = "string";
```

Is there a workaround for this that maintains a similar syntactic 
structure?


value = n == 2 ? Alg(2) : Alg("string");


is this behaviour accepted


Yes.

or should the compiler translate the first 
case in the second?


No.


"if" statement

2019-03-24 Thread Francesco Mecca via Digitalmars-d-learn

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

```
alias Alg = Algebraic!(int, string);

void main()
{
int n = 2;
Alg value;

value = n == 2 ? 2 : "string";
}
```

The original code used SumType but the effect is the same.

I suppose that I could write the following:

```
if(n == 2) value = 2;
else value = "string";
```

Is there a workaround for this that maintains a similar syntactic 
structure?
is this behaviour accepted or should the compiler translate the 
first case in the second?


Re: why mixin template can not inclulde statement;

2018-08-10 Thread Kagamin via Digitalmars-d-learn

try this:

mixin template test(A...){
__gshared int a = A[0];
int dummy = (){
a++;
return 0;
}();
}

import core.stdc.stdio;
int main(){
mixin test!1;
printf("a=%d\n", a);
return 0;
}


Re: why mixin template can not inclulde statement;

2018-08-10 Thread learnfirst1 via Digitalmars-d-learn

On Friday, 10 August 2018 at 13:17:13 UTC, learnfirst1 wrote:
this work,  it report no error but give  a link problem.  (this 
could be a bug ?)


mixin template test(A...){
__gshared int a = A[0];
pragma(inline, true) // remove this will work
static extern(C) int test(){
a++;
return 0;
}
int dummy = test();
}

import core.stdc.stdio;
extern(C) void main(){
mixin test!1;
printf("a=%d\n", a);
}

---
Undefined symbols for architecture x86_64:
  "__D4test4mainUZ8__mixin1QvUNbNiZi", referenced from:
  _main in test.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)

Error: linker exited with status 1


Re: why mixin template can not inclulde statement;

2018-08-10 Thread learnfirst1 via Digitalmars-d-learn

On Friday, 10 August 2018 at 13:10:57 UTC, Kagamin wrote:

On Friday, 10 August 2018 at 13:01:21 UTC, learnfirst1 wrote:
Looks like some problem with tuple, try __gshared a = A[0];


this work,  it report no error but give  a link problem.  (this 
could be a bug ?)


Re: why mixin template can not inclulde statement;

2018-08-10 Thread learnfirst1 via Digitalmars-d-learn

On Friday, 10 August 2018 at 13:05:24 UTC, Kagamin wrote:
Mixim template can only introduce declarations, not statements, 
a workaround is a lambda called in place.


mixin template test(A...){
__gshared a = A;
int dummy = (){ a++; return 0; }();
}

extern(C) void main(){
mixin test!123;
}


Thanks, this work for me.   my second example should be a dmd bug 
? (ldc work)




Re: why mixin template can not inclulde statement;

2018-08-10 Thread Radu via Digitalmars-d-learn

On Friday, 10 August 2018 at 13:05:24 UTC, Kagamin wrote:
Mixim template can only introduce declarations, not statements, 
a workaround is a lambda called in place.


mixin template test(A...){
__gshared a = A;
int dummy = (){ a++; return 0; }();
}

extern(C) void main(){
mixin test!123;
}


Except that you can't use tuples for that, a working sample:

mixin template test(alias A){
__gshared a = A;
int dummy = (){ a++; return 0; }();
}

extern(C) void main(){
mixin test!123;

import core.stdc.stdio;
printf("%d", a);
}


Re: why mixin template can not inclulde statement;

2018-08-10 Thread Kagamin via Digitalmars-d-learn

On Friday, 10 August 2018 at 13:01:21 UTC, learnfirst1 wrote:

duplicate symbol __D4test4mainUZ8__mixin111__a_field_0i in:
test.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)

Error: linker exited with status 1


this really make no sense,  what is wrong with it?(same 
code build with ldc2)


Looks like some problem with tuple, try __gshared a = A[0];


Re: why mixin template can not inclulde statement;

2018-08-10 Thread Kagamin via Digitalmars-d-learn
Mixim template can only introduce declarations, not statements, a 
workaround is a lambda called in place.


mixin template test(A...){
__gshared a = A;
int dummy = (){ a++; return 0; }();
}

extern(C) void main(){
mixin test!123;
}


Re: why mixin template can not inclulde statement;

2018-08-10 Thread learnfirst1 via Digitalmars-d-learn

On Friday, 10 August 2018 at 12:38:55 UTC, learnfirst1 wrote:

mixin template test(A...){



mixin template test(A...){
__gshared a = A;
}

extern(C) void main(){
mixin test!123;
}

---

duplicate symbol __D4test4mainUZ8__mixin111__a_field_0i in:
test.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)

Error: linker exited with status 1


this really make no sense,  what is wrong with it?(same code 
build with ldc2)


why mixin template can not inclulde statement;

2018-08-10 Thread learnfirst1 via Digitalmars-d-learn

mixin template test(A...){
__gshared a = A;
a++;
}

extern(C) void main(){
mixin test!123;
}

-

I dont want to use string mixin to intro a lot un want symbol,  
try with mixin template find this not work.


I know if mixin test on global it should not working, but why not 
make the limit for function scope ?



I try use D for a WASM project then find so much limitation with 
no good reason.  or I missing some thing here ?





Re: Equivalent to Python with Statement

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

On Thursday, 1 March 2018 at 07:34:38 UTC, Cym13 wrote:

On Wednesday, 28 February 2018 at 22:55:19 UTC, Seb wrote:

On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:

[...]


I know that I am repeating myself, but manually closing the 
file isn't needed in D. It's refCounted and will be closed 
automatically once the scope is left. That's why 
`with(File("AAA","w"))` works in D.


As stated, yes that's an accurate answer to that particular 
problem and it's well understood, I'm just giving a more 
general answer that will work for every python context manager 
and not only on the  specific case of closing files.


http://phongkhamdakhoathegioi.vn/u-nang-buong-trung-dang-nuoc.html


Re: Unexpected behaviour of foreach statement

2018-03-02 Thread Arredondo via Digitalmars-d-learn

On Friday, 2 March 2018 at 10:32:08 UTC, Jonathan M Davis wrote:
foreach does not support indices for ranges, only arrays. When 
you have


foreach(e; range)

it gets lowered to

foreach(auto __range = range; !__range.empty; 
__range.popFront())

{
auto e = __range.front;
}

There are no indices involved there, and if a range isn't a 
random-access range, it doesn't support any kind of indices 
anyway. The compiler would have to add a variable to count the 
elements, and it doesn't support that.


I understand. I guess I was expecting the compiler to 
automatically do something along the lines of what enumerate 
does. Although, a nicer error message would have saved the day 
just as well.


Arredondo


Re: Unexpected behaviour of foreach statement

2018-03-02 Thread Arredondo via Digitalmars-d-learn

On Friday, 2 March 2018 at 10:34:31 UTC, bauss wrote:

You can also call "array" from "std.array".

auto range = iota(5).array;

foreach (i, el; range) {
writeln(i, ": ", el);
}


Thank you. That's how I had it in my original code, I was just 
trying to avoid gratuitous memory allocation.


Arredondo


Re: Unexpected behaviour of foreach statement

2018-03-02 Thread Arredondo via Digitalmars-d-learn

On Friday, 2 March 2018 at 10:27:27 UTC, Nicholas Wilson wrote:

try
https://dlang.org/phobos/std_range.html#enumerate


This worked. Thank you!


Re: Unexpected behaviour of foreach statement

2018-03-02 Thread bauss via Digitalmars-d-learn

On Friday, 2 March 2018 at 10:21:39 UTC, Arredondo wrote:

Hi,

The following works as expected:

auto range = [1, 2, 3, 4, 5];
foreach (i, el; range) {
writeln(i, ": ", el);
}

but this slight modification doesn't:

auto range = iota(5);
foreach (i, el; range) {
writeln(i, ": ", el);
}

DMD 2.078.3 says:
Error: cannot infer argument types, expected 1 argument, not 2

The error message is not helpful either, because indicating the 
types, as in:


foreach (int i, int el; range) { ... }

throws the same error.
What's going on here?

Arredondo


What you want to do is call "enumerate" from "std.range".

auto range = iota(5).enumerate;

foreach (i, el; range) {
writeln(i, ": ", el);
}

You can also call "array" from "std.array".

auto range = iota(5).array;

foreach (i, el; range) {
writeln(i, ": ", el);
}



Re: Unexpected behaviour of foreach statement

2018-03-02 Thread Jonathan M Davis via Digitalmars-d-learn
On Friday, March 02, 2018 10:21:39 Arredondo via Digitalmars-d-learn wrote:
> Hi,
>
> The following works as expected:
>
> auto range = [1, 2, 3, 4, 5];
> foreach (i, el; range) {
>   writeln(i, ": ", el);
> }
>
> but this slight modification doesn't:
>
> auto range = iota(5);
> foreach (i, el; range) {
>   writeln(i, ": ", el);
> }
>
> DMD 2.078.3 says:
> Error: cannot infer argument types, expected 1 argument, not 2
>
> The error message is not helpful either, because indicating the
> types, as in:
>
> foreach (int i, int el; range) { ... }
>
> throws the same error.
> What's going on here?

foreach does not support indices for ranges, only arrays. When you have

foreach(e; range)

it gets lowered to

foreach(auto __range = range; !__range.empty; __range.popFront())
{
auto e = __range.front;
}

There are no indices involved there, and if a range isn't a random-access
range, it doesn't support any kind of indices anyway. The compiler would
have to add a variable to count the elements, and it doesn't support that.

Your best options are either lockstep with iota or enumerate:

https://dlang.org/phobos/std_range.html#lockstep
https://dlang.org/phobos/std_range.html#enumerate

- Jonathan M Davis



Re: Unexpected behaviour of foreach statement

2018-03-02 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 2 March 2018 at 10:21:39 UTC, Arredondo wrote:

Hi,

The following works as expected:

auto range = [1, 2, 3, 4, 5];
foreach (i, el; range) {
writeln(i, ": ", el);
}

but this slight modification doesn't:

auto range = iota(5);
foreach (i, el; range) {
writeln(i, ": ", el);
}

DMD 2.078.3 says:
Error: cannot infer argument types, expected 1 argument, not 2

The error message is not helpful either, because indicating the 
types, as in:


foreach (int i, int el; range) { ... }

throws the same error.
What's going on here?

Arredondo


try
https://dlang.org/phobos/std_range.html#enumerate


foreach (i, el; enumerate(range)) {
writeln(i, ": ", el);
}




Unexpected behaviour of foreach statement

2018-03-02 Thread Arredondo via Digitalmars-d-learn

Hi,

The following works as expected:

auto range = [1, 2, 3, 4, 5];
foreach (i, el; range) {
writeln(i, ": ", el);
}

but this slight modification doesn't:

auto range = iota(5);
foreach (i, el; range) {
writeln(i, ": ", el);
}

DMD 2.078.3 says:
Error: cannot infer argument types, expected 1 argument, not 2

The error message is not helpful either, because indicating the 
types, as in:


foreach (int i, int el; range) { ... }

throws the same error.
What's going on here?

Arredondo


Re: Unexpected behaviour of foreach statement

2018-03-02 Thread rikki cattermole via Digitalmars-d-learn

On 02/03/2018 11:21 PM, Arredondo wrote:

Hi,

The following works as expected:

auto range = [1, 2, 3, 4, 5];
foreach (i, el; range) {
 writeln(i, ": ", el);
}


s/range/array/

Arrays have a different foreach syntax than ranges do.


Re: Equivalent to Python with Statement

2018-02-28 Thread Cym13 via Digitalmars-d-learn

On Wednesday, 28 February 2018 at 22:55:19 UTC, Seb wrote:

On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


Others have discussed that particular case at length, but to 
provide a more generic answer the correct way to translate a 
python context manager is to use scope(out):


{ // Scope restriction similar to with's block
auto f = File("x.txt");
scope(out) f.close();   // closes f on scope exit no 
matter what


/* do stuff with f */
}

This accurately reproduces the behaviour of python's with 
although it's less automatic.


I know that I am repeating myself, but manually closing the 
file isn't needed in D. It's refCounted and will be closed 
automatically once the scope is left. That's why 
`with(File("AAA","w"))` works in D.


As stated, yes that's an accurate answer to that particular 
problem and it's well understood, I'm just giving a more general 
answer that will work for every python context manager and not 
only on the  specific case of closing files.


Re: Equivalent to Python with Statement

2018-02-28 Thread Seb via Digitalmars-d-learn

On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


Others have discussed that particular case at length, but to 
provide a more generic answer the correct way to translate a 
python context manager is to use scope(out):


{ // Scope restriction similar to with's block
auto f = File("x.txt");
scope(out) f.close();   // closes f on scope exit no 
matter what


/* do stuff with f */
}

This accurately reproduces the behaviour of python's with 
although it's less automatic.


I know that I am repeating myself, but manually closing the file 
isn't needed in D. It's refCounted and will be closed 
automatically once the scope is left. That's why 
`with(File("AAA","w"))` works in D.


Re: Equivalent to Python with Statement

2018-02-28 Thread meppl via Digitalmars-d-learn

On Wednesday, 28 February 2018 at 22:00:11 UTC, meppl wrote:

On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:

[...]


Others have discussed that particular case at length, but to 
provide a more generic answer the correct way to translate a 
python context manager is to use scope(out):


{ // Scope restriction similar to with's block
auto f = File("x.txt");
scope(out) f.close();   // closes f on scope exit no 
matter what


/* do stuff with f */
}

This accurately reproduces the behaviour of python's with 
although it's less automatic.


what is `scope(out)`? I only know these  
file:///usr/share/dmd-doc/html/d/spec/statement.html#ScopeGuardStatement


sorry, my question was not good. I thought there is an 
undocumented feature, never mind ;)


Re: Equivalent to Python with Statement

2018-02-28 Thread meppl via Digitalmars-d-learn

On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:

[...]


Others have discussed that particular case at length, but to 
provide a more generic answer the correct way to translate a 
python context manager is to use scope(out):


{ // Scope restriction similar to with's block
auto f = File("x.txt");
scope(out) f.close();   // closes f on scope exit no 
matter what


/* do stuff with f */
}

This accurately reproduces the behaviour of python's with 
although it's less automatic.


what is `scope(out)`? I only know these  
file:///usr/share/dmd-doc/html/d/spec/statement.html#ScopeGuardStatement


Re: Equivalent to Python with Statement

2018-02-28 Thread Cym13 via Digitalmars-d-learn

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


Others have discussed that particular case at length, but to 
provide a more generic answer the correct way to translate a 
python context manager is to use scope(out):


{ // Scope restriction similar to with's block
auto f = File("x.txt");
scope(out) f.close();   // closes f on scope exit no 
matter what


/* do stuff with f */
}

This accurately reproduces the behaviour of python's with 
although it's less automatic.


Re: Equivalent to Python with Statement

2018-02-27 Thread Seb via Digitalmars-d-learn

On Tuesday, 27 February 2018 at 16:18:43 UTC, Stefan Koch wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


In this case with(File("bla"))
will do the same.


FWIW std.stdio.File is refcounted and will be automatically 
closed at the end of the scope. So typically you don't even need 
`with` ;-)
@Jonathan: have a look at these two examples to see what DMD does 
under the hood:



https://run.dlang.io/is/89NBxI
https://run.dlang.io/is/eXC7ZV


Re: Equivalent to Python with Statement

2018-02-27 Thread Daniel Kozak via Digitalmars-d-learn
yes, for classes you can use scoped:

import std.stdio;
import std.typecons : scoped;
class A
{
void saySomething()
{
writeln("Hi from A");
}
~this()
{
writeln("Destruct A");
}
}

void main()
{
with(scoped!A())
{
saySomething();
writeln("something");
}
writeln("Hello D");
}

On Tue, Feb 27, 2018 at 5:25 PM, Jonathan via Digitalmars-d-learn <
digitalmars-d-learn@puremagic.com> wrote:

> On Tuesday, 27 February 2018 at 16:18:43 UTC, Stefan Koch wrote:
>
>> On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
>>
>>> I know Python's `with` statement can be used to have an automatic close
>>> action:
>>> ```
>>> with open("x.txt") as file:
>>>     #do something with file
>>> #`file.close()` called automatically
>>> ```
>>>
>>> I know D's `with` statement does something different but is there some
>>> sort of equivalent?
>>>
>>
>> In this case with(File("bla"))
>> will do the same.
>>
>
> Oh really, cool.
>
> Is this just because the scope of the file variable will end and thus its
> `~this`?
>
>


Re: Equivalent to Python with Statement

2018-02-27 Thread Jonathan via Digitalmars-d-learn

On Tuesday, 27 February 2018 at 16:18:43 UTC, Stefan Koch wrote:

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


In this case with(File("bla"))
will do the same.


Oh really, cool.

Is this just because the scope of the file variable will end and 
thus its `~this`?




Equivalent to Python with Statement

2018-02-27 Thread Jonathan via Digitalmars-d-learn
I know Python's `with` statement can be used to have an automatic 
close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is there 
some sort of equivalent?


Re: Equivalent to Python with Statement

2018-02-27 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


In this case with(File("bla"))
will do the same.


Re: Sort in return statement

2017-12-09 Thread codephantom via Digitalmars-d-learn

On Saturday, 9 December 2017 at 14:49:28 UTC, Seb wrote:


randomSample doesn't sort its returned range


Not by design, however, because it samples in the order that the 
elements appear, *if* those elements are already sorted (whether 
by design or explicately sorted), then the results of the 
randomsample are also implicitly already sorted ;-)




Re: Sort in return statement

2017-12-09 Thread Seb via Digitalmars-d-learn

On Saturday, 9 December 2017 at 14:42:44 UTC, codephantom wrote:
After lots of reading, and testing, I managed to get a simple, 
one liner ;-)

(doesn't seem like .release is needed though.)


FYI .release is only possible on a SortedRange and then yields 
the underlying range. randomSample doesn't sort its returned 
range, but I am glad to hear this worked for you.


Re: Sort in return statement

2017-12-09 Thread codephantom via Digitalmars-d-learn

On Saturday, 9 December 2017 at 14:18:00 UTC, Seb wrote:


Yeah, you are very welcome. It's a bit hidden in the docs:



Yes. Thanks for that.

After lots of reading, and testing, I managed to get a simple, 
one liner ;-)

(doesn't seem like .release is needed though.)

// ---
auto draw8Numbers()
{
import std.meta : aliasSeqOf;
import std.range : iota;
import std.random : randomSample;

return randomSample([ aliasSeqOf!(iota(1,46)) ], 8);
}
// ---




Re: Sort in return statement

2017-12-09 Thread Seb via Digitalmars-d-learn

On Saturday, 9 December 2017 at 14:05:36 UTC, rjframe wrote:

On Sat, 09 Dec 2017 07:32:42 +, Seb wrote:



Use .release to obtain the underlying array. No need to do 
another allocation!


```
numbers.take(8).sort.release;
```


I did not realize that was there; thanks.


Yeah, you are very welcome. It's a bit hidden in the docs:

https://dlang.org/phobos/std_range.html#SortedRange


Re: Sort in return statement

2017-12-09 Thread rjframe via Digitalmars-d-learn
On Sat, 09 Dec 2017 07:32:42 +, Seb wrote:

> 
> Use .release to obtain the underlying array. No need to do another
> allocation!
> 
> ```
> numbers.take(8).sort.release;
> ```

I did not realize that was there; thanks.


Re: Sort in return statement

2017-12-08 Thread Seb via Digitalmars-d-learn

On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote:

On Sat, 09 Dec 2017 02:34:29 +, codephantom wrote:


Anyone got ideas on how to get sort() working in the *return*
statement?

//

ushort[] draw8Numbers()
{
 import std.meta : aliasSeqOf;
 import std.range : iota;
 ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ];

 import std.random : randomShuffle;
 randomShuffle(numbers);

 import std.range : take;
 import std.algorithm.sorting : sort;
 return numbers.take(8); /* ok */
 //return sort(numbers.take(8)); /* I want this, but it 
won't

work. */

}

// -



`sort` returns a SortedRange of ushorts, not an array of 
ushorts. Make it:


```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan



Use .release to obtain the underlying array. No need to do 
another allocation!


```
numbers.take(8).sort.release;
```



Re: Sort in return statement

2017-12-08 Thread user1234 via Digitalmars-d-learn

On Saturday, 9 December 2017 at 03:24:52 UTC, codephantom wrote:

On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote:


`sort` returns a SortedRange of ushorts, not an array of 
ushorts. Make it:


```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan


That's it!

Thanks Ryan.


You can also return a lazy range:

```
auto draw8Numbers()
{
 import std.meta : aliasSeqOf;
 import std.range : iota, take;
 ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ];
 import std.random : randomShuffle;
 randomShuffle(numbers);
 import std.algorithm.sorting : sort;
 return sort(numbers[].take(8));
}

void main()
{
import std.array;
ushort[] nbrs = draw8Numbers.array; // evaluated after 
return, during assingment

}
```


Re: Sort in return statement

2017-12-08 Thread codephantom via Digitalmars-d-learn

On Saturday, 9 December 2017 at 04:31:33 UTC, SimonN wrote:


Yes, this works, and your algorithm would even accept arbitary 
random-access ranges, not merely arrays.




Would be nice if I could do it all as a 'one liner':

// 
int[] draw8Numbers()
{
import std.algorithm.sorting : sort;
import std.random : randomShuffle;
import std.meta : aliasSeqOf;
import std.range : iota;
import std.range : take;
import std.array : array;

// return a sorted array of 8 random numbers, between 1..45 
inclusive.
return sort(randomShuffle([ aliasSeqOf!(iota(1,46)) 
]).take(8)).array;

}

// ---


Re: Sort in return statement

2017-12-08 Thread SimonN via Digitalmars-d-learn

On Saturday, 9 December 2017 at 03:24:52 UTC, codephantom wrote:

On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote:


`sort` returns a SortedRange of ushorts, not an array of 
ushorts. Make it:


```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan


That's it!

Thanks Ryan.


Yes, this works, and your algorithm would even accept arbitary 
random-access ranges, not merely arrays.


But since we start explicitly with a ushort[] that this function 
has allocated just for this algorithm, we could save the extra 
allocation by the final call to array().


// ushort[] numbers = ...
randomShuffle(numbers);

import std.algorithm.sorting : sort;
numbers = numbers[0 .. 8];
sort(numbers);
return numbers;

sort(numbers) does two things: (1) affect the underlying data, 
(2) return an input range with extra information that this 
returned range is sorted. But in our example, we don't need to 
allocate a fresh array from (2). We can return the sorted data 
from (1), this is already in array-form.


-- Simon


Re: Sort in return statement

2017-12-08 Thread codephantom via Digitalmars-d-learn

On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote:


`sort` returns a SortedRange of ushorts, not an array of 
ushorts. Make it:


```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan


That's it!

Thanks Ryan.




Re: Sort in return statement

2017-12-08 Thread rjframe via Digitalmars-d-learn
On Sat, 09 Dec 2017 02:34:29 +, codephantom wrote:

> Anyone got ideas on how to get sort() working in the *return*
> statement?
> 
> //
> 
> ushort[] draw8Numbers()
> {
>  import std.meta : aliasSeqOf;
>  import std.range : iota;
>  ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ];
> 
>  import std.random : randomShuffle;
>  randomShuffle(numbers);
> 
>  import std.range : take;
>  import std.algorithm.sorting : sort;
>  return numbers.take(8); /* ok */
>  //return sort(numbers.take(8)); /* I want this, but it won't
> work. */
> 
> }
> 
> // -


`sort` returns a SortedRange of ushorts, not an array of ushorts. Make it:

```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan


Sort in return statement

2017-12-08 Thread codephantom via Digitalmars-d-learn
Anyone got ideas on how to get sort() working in the *return* 
statement?


//

ushort[] draw8Numbers()
{
import std.meta : aliasSeqOf;
import std.range : iota;
ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ];

import std.random : randomShuffle;
randomShuffle(numbers);

import std.range : take;
import std.algorithm.sorting : sort;
return numbers.take(8); /* ok */
//return sort(numbers.take(8)); /* I want this, but it won't 
work. */


}

// -



Re: Solution to "statement is not reachable" depending on template variables?

2017-06-18 Thread Steven Schveighoffer via Digitalmars-d-learn

On Sunday, 18 June 2017 at 11:11:59 UTC, Johan Engelen wrote:
On Sunday, 18 June 2017 at 09:56:50 UTC, Steven Schveighoffer 
wrote:

On Sunday, 18 June 2017 at 09:28:57 UTC, Johan Engelen wrote:
Reviving this thread to see whether anything has changed on 
the topic.




If Timon gets static for each into the language, it can look a 
little better.


Can you help me understand what you mean? How will it improve 
things? (static foreach would disable the "statement not 
reachable" analysis?)


-Johan


On my phone so can't be too detailed, but you could do:

static foreach(i; 0..seq.length+1)
  static if(seq.length == i)
return true;
  else static if(is(seq[i] == bool))
return false;

Maybe looks a little better than the first workaround.

-Steve


Re: Solution to "statement is not reachable" depending on template variables?

2017-06-18 Thread Moritz Maxeiner via Digitalmars-d-learn

On Sunday, 18 June 2017 at 11:11:59 UTC, Johan Engelen wrote:
On Sunday, 18 June 2017 at 09:56:50 UTC, Steven Schveighoffer 
wrote:

On Sunday, 18 June 2017 at 09:28:57 UTC, Johan Engelen wrote:
Reviving this thread to see whether anything has changed on 
the topic.




If Timon gets static for each into the language, it can look a 
little better.


Can you help me understand what you mean? How will it improve 
things? (static foreach would disable the "statement not 
reachable" analysis?)


The new static foreach is AFAIK supposed to execute the loop 
instead of unrolling it, i.e. the expansion of


---
foreach (i, U; T) {
static if (is(U == bool)) {
return false;
}
}
return true;
---

to

---
static if (is(U1 == bool)) {
return false;
}
static if (is(U2 == bool)) {
return false;
}
...
return true;
---

, which triggers that "statement is not reachable"  if at least 
one of U1,U2,... = T is bool, will not occur if you instead use 
`static foreach (i, U; T)`.


Re: Solution to "statement is not reachable" depending on template variables?

2017-06-18 Thread Johan Engelen via Digitalmars-d-learn
On Sunday, 18 June 2017 at 09:56:50 UTC, Steven Schveighoffer 
wrote:

On Sunday, 18 June 2017 at 09:28:57 UTC, Johan Engelen wrote:
Reviving this thread to see whether anything has changed on 
the topic.




If Timon gets static for each into the language, it can look a 
little better.


Can you help me understand what you mean? How will it improve 
things? (static foreach would disable the "statement not 
reachable" analysis?)


-Johan



Re: Solution to "statement is not reachable" depending on template variables?

2017-06-18 Thread Steven Schveighoffer via Digitalmars-d-learn

On Sunday, 18 June 2017 at 09:28:57 UTC, Johan Engelen wrote:
Reviving this thread to see whether anything has changed on the 
topic.




If Timon gets static for each into the language, it can look a 
little better.


-Steve




Re: Solution to "statement is not reachable" depending on template variables?

2017-06-18 Thread Johan Engelen via Digitalmars-d-learn
Reviving this thread to see whether anything has changed on the 
topic.


I now have this monster:
```
struct FMT {
  // has immutable members. FMT cannot be assigned to.
}

FMT monsterThatCompilerAccepts(T)(){
alias TP = Tuple!(__traits(getAttributes, T));
foreach(i, att; TP){
static if( ... ) {
return FMT( ... );
}

// Make sure we return a default value in the last 
iteration.
// Prevents "statement not reachable" warning when placed 
here instead of outside the foreach.

else static if (i + 1 == TP.length) {
return FMT( ... );
}
}
static if (TP.length == 0) {
return FMT( ... );
}
}

FMT codeThatIsUnderstandableButNotAccepted(T)(){
alias TP = Tuple!(__traits(getAttributes, T));
foreach(i, att; TP){
static if( ... ) {
return FMT( ... );
}
}
return FMT( ... );
}
```

Thanks,
  Johan


Re: import statement placement

2017-06-08 Thread Russel Winder via Digitalmars-d-learn
On Wed, 2017-06-07 at 10:08 -0700, H. S. Teoh via Digitalmars-d-learn
wrote:
> On Wed, Jun 07, 2017 at 01:17:39PM +, Nicholas Wilson via
> Digitalmars-d-learn wrote:
> > On Wednesday, 7 June 2017 at 12:39:07 UTC, Russel Winder wrote:
> > > Are there any idiom rules as to where to put import statements in
> > > D?
> > > 
> > > In Python they can go anywhere but PEP-8 suggests they should all
> > > go
> > > at the top of a file, just after the module documentation string.
> > 
> > Well for ones that aren't scoped (i.e. used pervasively throughout
> > the
> > module) I always put them after the module declaration (if not the
> > file containing main) and doc comment.

I am also tending to import individual symbols from modules rather than
whole modules. In Python this can sometime be the wrong thing to do,
but then the scope rules are different to D. The D import scope rules
seem to be equivalent to Python star imports, which is a nightmare.

> > For scoped imports they go either on the line after the opening
> > brace
> > of the enclosing scope, or the line before the (selectively)
> > imported
> > symbol is used (if there is a reasonable amount of code preceding
> > the
> > opening brace).

I hadn't got into scoped imports. I suspect I am now going to become a
fan of them.

> I follow the same convention.
> 
> Though lately, I've been finding myself moving away more and more
> from
> global imports, and moving imports into the scope in which they're
> actually used.  While that sometimes necessitates more typing, I find
> that it also improves code readability and movability: having scoped
> imports in the block in which the symbol is used means reducing the
> likelihood of overload conflicts with unfortunately-named symbols
> (there
> are a few of these in Phobos). And I can easily move that code into a
> different source file and have it Just Work, instead of having to
> twiddle with the import statements at the top of the file (and
> inadvertently leave useless imports in the original file where they
> are
> no longer needed).
> 
> Nowadays I generally only use module-level import for things that are
> truly used pervasively, like std.range.primitives, and std.stdio in
> the
> module where main() is defined.  I try to avoid importing std.stdio
> anywhere else, unless that module is directly concerned with I/O, and
> force myself to structure the code such that such a dependency is not
> needed in the first place -- e.g., write generic range-based
> algorithms
> instead of code sprinkled with calls writeln.  I found that this has
> helped improve my code quality significantly, and my code has become
> much more reusable.
> 

OK, I am now convinced.

This still leaves the question of "whole module imports" vs "symbols
from modules". Because D imports are equivalent to Python or Java star
imports, which are anathema, I am thinking "symbols from modules"
remains the best strategy even with scoping.


> T
> 
-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

signature.asc
Description: This is a digitally signed message part


Re: import statement placement

2017-06-07 Thread H. S. Teoh via Digitalmars-d-learn
On Wed, Jun 07, 2017 at 01:17:39PM +, Nicholas Wilson via 
Digitalmars-d-learn wrote:
> On Wednesday, 7 June 2017 at 12:39:07 UTC, Russel Winder wrote:
> > Are there any idiom rules as to where to put import statements in D?
> > 
> > In Python they can go anywhere but PEP-8 suggests they should all go
> > at the top of a file, just after the module documentation string.
> 
> Well for ones that aren't scoped (i.e. used pervasively throughout the
> module) I always put them after the module declaration (if not the
> file containing main) and doc comment.
> 
> For scoped imports they go either on the line after the opening brace
> of the enclosing scope, or the line before the (selectively) imported
> symbol is used (if there is a reasonable amount of code preceding the
> opening brace).
[...]

I follow the same convention.

Though lately, I've been finding myself moving away more and more from
global imports, and moving imports into the scope in which they're
actually used.  While that sometimes necessitates more typing, I find
that it also improves code readability and movability: having scoped
imports in the block in which the symbol is used means reducing the
likelihood of overload conflicts with unfortunately-named symbols (there
are a few of these in Phobos). And I can easily move that code into a
different source file and have it Just Work, instead of having to
twiddle with the import statements at the top of the file (and
inadvertently leave useless imports in the original file where they are
no longer needed).

Nowadays I generally only use module-level import for things that are
truly used pervasively, like std.range.primitives, and std.stdio in the
module where main() is defined.  I try to avoid importing std.stdio
anywhere else, unless that module is directly concerned with I/O, and
force myself to structure the code such that such a dependency is not
needed in the first place -- e.g., write generic range-based algorithms
instead of code sprinkled with calls writeln.  I found that this has
helped improve my code quality significantly, and my code has become
much more reusable.


T

-- 
The best compiler is between your ears. -- Michael Abrash


Re: import statement placement

2017-06-07 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 7 June 2017 at 12:39:07 UTC, Russel Winder wrote:
Are there any idiom rules as to where to put import statements 
in D?


In Python they can go anywhere but PEP-8 suggests they should 
all go at the top of a file, just after the module 
documentation string.


Well for ones that aren't scoped (i.e. used pervasively 
throughout the module) I always put them after the module 
declaration (if not the file containing main) and doc comment.


For scoped imports they go either on the line after the opening 
brace of the enclosing scope, or the line before the 
(selectively) imported symbol is used (if there is a reasonable 
amount of code preceding the opening brace).


Perhaps the https://dlang.org/dstyle.html imports section should 
be expanded.


Re: import statement placement

2017-06-07 Thread Biotronic via Digitalmars-d-learn

On Wednesday, 7 June 2017 at 12:39:07 UTC, Russel Winder wrote:
Are there any idiom rules as to where to put import statements 
in D?


In Python they can go anywhere but PEP-8 suggests they should 
all go at the top of a file, just after the module 
documentation string.


I don't know if there is any official dogma on how to use 
imports, but given that local imports inside templates are only 
loaded if the template is instantiated, there are benefits to 
using local imports in those cases.


Another use for local imports is in unittests - any import that 
is only used in unittests may benefit from being moved from 
module scope to inside the unittests themselves, or for an import 
used by many tests, a version (unittest) block.


In my own code, I use very loose guidelines but prefer to put any 
imports that are used only in one or two functions, inside those 
functions. Imports that are used by multiple functions are placed 
at the top of the file, just below the module declaration (if 
any).


Similarly, I try to use selective imports when only a few symbols 
from a module are used in my module, but find that this becomes 
unwieldy past 3-5 symbols.


--
  Biotronic


import statement placement

2017-06-07 Thread Russel Winder via Digitalmars-d-learn
Are there any idiom rules as to where to put import statements in D?

In Python they can go anywhere but PEP-8 suggests they should all go at
the top of a file, just after the module documentation string.

-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

signature.asc
Description: This is a digitally signed message part


Re: Cconditional expression in return statement. Bug?

2017-03-08 Thread Jack Applegame via Digitalmars-d-learn

On Tuesday, 7 March 2017 at 16:00:54 UTC, kinke wrote:
Definitely a very bad bug. It works too if you mark `fun()` as 
nothrow. Please file a DMD issue.

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


Re: Cconditional expression in return statement. Bug?

2017-03-07 Thread kinke via Digitalmars-d-learn

On Tuesday, 7 March 2017 at 14:26:18 UTC, Jack Applegame wrote:
I'm pretty sure this is a bug. And very bad bug. I spent 
several hours looking for it.

What do you think?


Definitely a very bad bug. It works too if you mark `fun()` as 
nothrow. Please file a DMD issue.


Cconditional expression in return statement. Bug?

2017-03-07 Thread Jack Applegame via Digitalmars-d-learn

Code (https://dpaste.dzfl.pl/8e7a9c380e99):

import std.stdio;
struct Foo {
int val;
this(int val) {
writefln("%s.this(int)", val);
this.val = val;
}
this(this) {
writefln("%s.this(this)", val);
this.val = val;
}
~this() {
writefln("%s.~this()", val);
this.val = val;
}
}
struct Bar {
Foo foo;
this(Foo foo, bool) { this.foo = foo; }
}

bool fun(bool val) { return !val; }

auto genBar(bool flag) {
return flag ? Bar() : Bar(Foo(10), fun(!flag));
}

void main(string[] args) {
auto bar = genBar(args.length == 0);
}

Compiler generates extra destructor call:

10.this(int)
10.this(this)
10.~this()
10.~this()
10.~this()

If we slightly change function genBar:
auto genBar(bool flag) {
auto a = flag ? Bar() : Bar(Foo(10), fun(!flag));
return a;
}

or

auto genBar(bool flag) {
return flag ? Bar() : Bar(Foo(10), false);
}

then output looks as expected:

10.this(int)
10.this(this)
10.~this()
10.~this()

I'm pretty sure this is a bug. And very bad bug. I spent several 
hours looking for it.

What do you think?


Re: switch statement with variable branches

2017-01-19 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 19 January 2017 at 01:22:56 UTC, Yuxuan Shui wrote:
Somehow I can't use ubyte variables behind 'case', but ulong 
works fine. Why is that?


void main() {
alias TestType = ulong; // won't compile if = ubyte
import std.stdio;
TestType a,b,c;
readf("%s %s %s ", , , );
switch(c){
case a: writeln("a");break;
case b: writeln("b");break;
default: assert(false);
}
}


It is a bug that this code compiled.
Case Variables can only be used on const values, to prevent 
mutation of them inside the switch itself.


try to make the type a const ubyte.


Re: switch statement with variable branches

2017-01-18 Thread Yuxuan Shui via Digitalmars-d-learn

On Thursday, 19 January 2017 at 02:00:10 UTC, Ali Çehreli wrote:

On 01/18/2017 05:22 PM, Yuxuan Shui wrote:
Somehow I can't use ubyte variables behind 'case', but ulong 
works fine.

Why is that?



case expressions must be constants:

  "The case expressions must all evaluate to a constant value or
   array, or a runtime initialized const or immutable variable 
of

   integral type."

  https://dlang.org/spec/statement.html#SwitchStatement

The fact that it compiles for ulong looks like a bug to me. It 
compiles probably because switch is most likely implemented in 
terms of a chained if-else-if statements by the compiler and it 
just works because there is no explicit check whether they are 
constant or not.


Ali


If you try:

void main() {
alias TestType = ulong; // won't compile if = ubyte
import std.stdio;
TestType a,b,c;
readf("%s %s %s ", , , );
final switch(c){
case a: writeln("a");break;
case b: writeln("b");break;
default: assert(false);
}
}

Then the error message:

test.d(7): Error: case variables not allowed in final switch 
statements
test.d(8): Error: case variables not allowed in final switch 
statements


Makes it looks like that "case variable" is an intended feature.



Re: switch statement with variable branches

2017-01-18 Thread Ali Çehreli via Digitalmars-d-learn

On 01/18/2017 05:22 PM, Yuxuan Shui wrote:

Somehow I can't use ubyte variables behind 'case', but ulong works fine.
Why is that?

void main() {
alias TestType = ulong; // won't compile if = ubyte
import std.stdio;
TestType a,b,c;
readf("%s %s %s ", , , );
switch(c){
case a: writeln("a");break;
case b: writeln("b");break;
default: assert(false);
}
}


case expressions must be constants:

  "The case expressions must all evaluate to a constant value or
   array, or a runtime initialized const or immutable variable of
   integral type."

  https://dlang.org/spec/statement.html#SwitchStatement

The fact that it compiles for ulong looks like a bug to me. It compiles 
probably because switch is most likely implemented in terms of a chained 
if-else-if statements by the compiler and it just works because there is 
no explicit check whether they are constant or not.


Ali



switch statement with variable branches

2017-01-18 Thread Yuxuan Shui via Digitalmars-d-learn
Somehow I can't use ubyte variables behind 'case', but ulong 
works fine. Why is that?


void main() {
alias TestType = ulong; // won't compile if = ubyte
import std.stdio;
TestType a,b,c;
readf("%s %s %s ", , , );
switch(c){
case a: writeln("a");break;
case b: writeln("b");break;
default: assert(false);
}
}


Re: using assignment statement as conditional in a where

2016-12-03 Thread rikki cattermole via Digitalmars-d-learn

On 04/12/2016 7:26 AM, dan wrote:

On Saturday, 3 December 2016 at 09:03:25 UTC, rikki cattermole wrote:

On 03/12/2016 9:55 PM, dan wrote:

[...]


If you can use another compiler do so, gdc is on an old
frontend/Phobos now. I recommend ldc or you know the reference
compiler dmd if performance/platform isn't an issue (not that dmd
can't produce decent codegen).

This does compile:

int func() {
return 0;
}

void main() {
int x;
while((x = func()) != 0) {

}
}


Thanks Rikki, that works great and is nearly ideal (doesn't seem to
allow 'auto' but probably that's some scoping issue).

I do prefer gdc because it is gpl'ed, but appreciate any suggestions.

Thanks again for your help!

dan


The only thing in gdc that is GPL is the backend and glue layer.
The frontend is the same one in ldc and dmd.


Re: using assignment statement as conditional in a where

2016-12-03 Thread dan via Digitalmars-d-learn
On Saturday, 3 December 2016 at 09:03:25 UTC, rikki cattermole 
wrote:

On 03/12/2016 9:55 PM, dan wrote:

[...]


If you can use another compiler do so, gdc is on an old 
frontend/Phobos now. I recommend ldc or you know the reference 
compiler dmd if performance/platform isn't an issue (not that 
dmd can't produce decent codegen).


This does compile:

int func() {
return 0;   
}

void main() {
int x;
while((x = func()) != 0) {

}
}


Thanks Rikki, that works great and is nearly ideal (doesn't seem 
to allow 'auto' but probably that's some scoping issue).


I do prefer gdc because it is gpl'ed, but appreciate any 
suggestions.


Thanks again for your help!

dan


Re: using assignment statement as conditional in a where

2016-12-03 Thread rikki cattermole via Digitalmars-d-learn

On 03/12/2016 9:55 PM, dan wrote:

In c, you can have code like this:

static void wtest( void ) {
  int f;
  while ( ( f = some_val( ) ) ) {
printf(" our value is now: %d\n", f );
  }
}

gcc compiles this without warning or error (at least if you use the
double parentheses to assure the compiler that you realize you are
testing an assignment, not a comparison).

I would like to do the same thing in d, something like this:

private void wtest( ) {
  int f;
  while ( ( f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

or even better:

private void wtest( ) {
  while ( ( auto f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

This however does not work, and the gdc compiler says "assignment cannot
be used as a condition, perhaps == was meant?"

I don't absolutely have to do it this way, as i guess i could do 'while
(true) {...' and then break if the assignment returns zero.

But i really, really would like to use the idiom of assigning a value
from inside a while condition.

Is it possible to do this?  Perhaps with extra braces or something, like
while ( {something here} ) {  } ?

TIA for any pointers or advice.

dan


If you can use another compiler do so, gdc is on an old frontend/Phobos 
now. I recommend ldc or you know the reference compiler dmd if 
performance/platform isn't an issue (not that dmd can't produce decent 
codegen).


This does compile:

int func() {
return 0;   
}

void main() {
int x;
while((x = func()) != 0) {

}
}



using assignment statement as conditional in a where

2016-12-03 Thread dan via Digitalmars-d-learn

In c, you can have code like this:

static void wtest( void ) {
  int f;
  while ( ( f = some_val( ) ) ) {
printf(" our value is now: %d\n", f );
  }
}

gcc compiles this without warning or error (at least if you use 
the double parentheses to assure the compiler that you realize 
you are testing an assignment, not a comparison).


I would like to do the same thing in d, something like this:

private void wtest( ) {
  int f;
  while ( ( f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

or even better:

private void wtest( ) {
  while ( ( auto f = some_val( ) ) ) {
writeln(" our value is now: ", f );
  }
}

This however does not work, and the gdc compiler says "assignment 
cannot be used as a condition, perhaps == was meant?"


I don't absolutely have to do it this way, as i guess i could do 
'while (true) {...' and then break if the assignment returns zero.


But i really, really would like to use the idiom of assigning a 
value from inside a while condition.


Is it possible to do this?  Perhaps with extra braces or 
something, like while ( {something here} ) {  } ?


TIA for any pointers or advice.

dan


Re: Solution to "statement is not reachable" depending on template variables?

2016-04-01 Thread ZombineDev via Digitalmars-d-learn

On Friday, 1 April 2016 at 01:21:32 UTC, Walter Bright wrote:

On 3/16/2016 4:18 AM, Johan Engelen wrote:
   I've found discussions, but not an actual "recommended" 
solution for the
problem of "statement is not reachable" warnings in templates 
with early

returns, e.g.:
```
bool nobool(T...)() {
 foreach (i, U; T) {
 static if (is(U == bool)) {
 return false;
 }
 }
 return true;  // emits "Warning: statement is not 
reachable"

}



bool nobool(T...)() {
 bool result = true;
 foreach (i, U; T) {
 static if (is(U == bool)) {
 result = false;
 break;
 }
 else
 {
 ...
 }
 }
 return result;  // emits "Warning: statement is not 
reachable"

}

Note that the optimizer will remove the dead loads.


Actually, I would expect every call of this fuction to be 
replaced by a boolean constant, since the result depends only on 
compile-time information.


What happened to "obvious code should be correct"? Can we try to 
find a solution that doesn't look like a hack? I don't think that 
we should ask users of the language to uglify their code just to 
workaround a deficiency in the compiler. Instead, we should 
improve the lowering of the static foreach construct so the 
information that it is syntactically a loop is preserved after 
loop unrolling.


Re: Solution to "statement is not reachable" depending on template variables?

2016-04-01 Thread Johan Engelen via Digitalmars-d-learn

On Friday, 1 April 2016 at 01:21:32 UTC, Walter Bright wrote:

On 3/16/2016 4:18 AM, Johan Engelen wrote:
   I've found discussions, but not an actual "recommended" 
solution for the
problem of "statement is not reachable" warnings in templates 
with early

returns, e.g.:
```
bool nobool(T...)() {
 foreach (i, U; T) {
 static if (is(U == bool)) {
 return false;
 }
 }
 return true;  // emits "Warning: statement is not 
reachable"

}



bool nobool(T...)() {
 bool result = true;
 foreach (i, U; T) {
 static if (is(U == bool)) {
 result = false;
 break;
 }
 else
 {
 ...
 }
 }
 return result;  // emits "Warning: statement is not 
reachable"

}


As you can see from my first post, that is the solution I used 
first  (without the "break;" addition), but it works until...



Note that the optimizer will remove the dead loads.


... until someone adds a (imho useful) diagnostic of dead 
stores/loads. :-)
In that case, I guess inverting all bools and then inverting the 
return value at the end will work (using default initialization 
of result); but this is not possible in a slightly more 
complicated case with non-bool return types.


In another piece of code, the return type is a struct with an 
immutable member. That's when I gave up on working around the 
warning and just disabled it.

Simplified, something like this:

struct IMM {
immutable bool result;
}
IMM immut(T...)() {
IMM retval = IMM(true);
foreach (i, U; T) {
static if (is(U == bool)) {
retval = IMM(false);  //  "Error: cannot modify 
struct retval IMM with immutable member".

}
}
return retval;
}




Re: Solution to "statement is not reachable" depending on template variables?

2016-03-31 Thread Walter Bright via Digitalmars-d-learn

On 3/16/2016 4:18 AM, Johan Engelen wrote:

   I've found discussions, but not an actual "recommended" solution for the
problem of "statement is not reachable" warnings in templates with early
returns, e.g.:
```
bool nobool(T...)() {
 foreach (i, U; T) {
 static if (is(U == bool)) {
 return false;
 }
 }
 return true;  // emits "Warning: statement is not reachable"
}



bool nobool(T...)() {
 bool result = true;
 foreach (i, U; T) {
 static if (is(U == bool)) {
 result = false;
 break;
 }
 else
 {
 ...
 }
 }
 return result;  // emits "Warning: statement is not reachable"
}

Note that the optimizer will remove the dead loads.


Solution to "statement is not reachable" depending on template variables?

2016-03-20 Thread Johan Engelen via Digitalmars-d-learn

Hi all,
  I've found discussions, but not an actual "recommended" 
solution for the problem of "statement is not reachable" warnings 
in templates with early returns, e.g.:

```
bool nobool(T...)() {
foreach (i, U; T) {
static if (is(U == bool)) {
return false;
}
}
return true;  // emits "Warning: statement is not reachable"
}

bool nobool_nowarning(T...)() {
bool retval = true;
foreach (i, U; T) {
static if (is(U == bool)) {
retval = false;
}
}
return retval;
}

void main() {
static assert ( nobool_nowarning!(int,bool)() == false );
static assert ( nobool_nowarning!(int,int)() == true );

static assert ( nobool!(int,bool)() == false );
static assert ( nobool!(int,int)() == true );
}
```
(I have heavily simplified the real-world code, please don't 
discuss alternative solutions to the "is(U==bool)" in particular. 
For sake of argument, assume that the predicate is a complicated 
beast.)


The `nobool` template prevents compilation with `-w`. Is 
`nobool_nowarning`, with the early return eradicated, the only 
acceptable solution? (with the hope that there will not be a 
"dead store" warning in the future...)

What if early returns cannot be avoided?

Thanks,
  Johan



Re: Solution to "statement is not reachable" depending on template variables?

2016-03-20 Thread Steven Schveighoffer via Digitalmars-d-learn

On 3/16/16 7:18 AM, Johan Engelen wrote:

Hi all,
   I've found discussions, but not an actual "recommended" solution for
the problem of "statement is not reachable" warnings in templates with
early returns, e.g.:
```
bool nobool(T...)() {
 foreach (i, U; T) {
 static if (is(U == bool)) {
 return false;
 }
 }
 return true;  // emits "Warning: statement is not reachable"
}


Instead of foreach, you could use recursive mechanism. Not ideal, but it 
would work.


Another possibility:

foreach(i, U; T) {
   static if(is(U == bool)) {
   return false;
   } else static if(i + 1 == T.length) {
   return true;
   }
}

-Steve


Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread Steven Schveighoffer via Digitalmars-d-learn

On 3/16/16 9:48 PM, tsbockman wrote:

On Wednesday, 16 March 2016 at 11:22:02 UTC, rikki cattermole wrote:

Change those static if's to just plain old ifs.


This only works (sometimes) because D's value range propagation doesn't
understand comparisons or normal if statements very well. This will
hopefully be fixed sooner or later:
 https://github.com/D-Programming-Language/dmd/pull/1913
 https://github.com/D-Programming-Language/dmd/pull/5229

The only future-proof way to fix the "statement is not reachable"
warning, is to guard the potentially unreachable code with a `static if`
whose predicate precisely describes the circumstances in which it
becomes unreachable...

Which itself is a terrible solution that doesn't scale well at all
to complex generic code and violates the "DRY" principle.

We really ought to just remove the warning. It just doesn't mesh well
with D's super-powered meta-programming features.


Yes. I agree. The way I look at it is that the code *is* reached in some 
cases, so it should compile (and just remove that section in that instance).


IMO any time a template value is used for branching, it should turn that 
warning off.


-Steve


Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread tsbockman via Digitalmars-d-learn
On Thursday, 17 March 2016 at 17:12:07 UTC, Steven Schveighoffer 
wrote:
Yes. I agree. The way I look at it is that the code *is* 
reached in some cases, so it should compile (and just remove 
that section in that instance).


IMO any time a template value is used for branching, it should 
turn that warning off.


-Steve


That's what I think it should do, also. However, when we 
discussed it before, Daniel Murphy pretty much told me there is 
no practical way to actually implement that behavior in the 
compiler.


So, the next best thing is to just remove the warning entirely.


Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread QAston via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote:

Hi all,
  I've found discussions, but not an actual "recommended" 
solution for the problem of "statement is not reachable" 
warnings in templates with early returns, e.g.:

```
bool nobool(T...)() {
foreach (i, U; T) {
static if (is(U == bool)) {
return false;
}
}
return true;  // emits "Warning: statement is not reachable"
}

[...]


On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote:
import std.meta;
template isBool(U)() = is(U == bool);
static if (!allSatisfy!(isBool, T)) {
return true;  // no longer emits a warning
}

Something like this should work.


Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread Johan Engelen via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 11:47:35 UTC, QAston wrote:


import std.meta;
template isBool(U)() = is(U == bool);
static if (!allSatisfy!(isBool, T)) {
return true;  // no longer emits a warning
}

Something like this should work.


Thanks, but:

On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote:
(I have heavily simplified the real-world code, please don't 
discuss alternative solutions to the "is(U==bool)" in 
particular. For sake of argument, assume that the predicate is 
a complicated beast.)




Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread rikki cattermole via Digitalmars-d-learn

On 17/03/16 5:05 AM, Johan Engelen wrote:

On Wednesday, 16 March 2016 at 11:22:02 UTC, rikki cattermole wrote:


Change those static if's to just plain old ifs.


But then this wouldn't compile, would it?
```
static if(__traits(compiles, __traits(getMember, a, "b"))) {
return a.b;
}
```
(real code, I am not making this up)


Hmm no.
If that's in a foreach as well, you'll need to solve it some other way.

---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus



Re: Solution to "statement is not reachable" depending on template variables?

2016-03-19 Thread QAston via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 17:08:20 UTC, Johan Engelen wrote:

On Wednesday, 16 March 2016 at 11:47:35 UTC, QAston wrote:


import std.meta;
template isBool(U)() = is(U == bool);
static if (!allSatisfy!(isBool, T)) {
return true;  // no longer emits a warning
}

Something like this should work.


Thanks, but:

On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen 
wrote:
(I have heavily simplified the real-world code, please don't 
discuss alternative solutions to the "is(U==bool)" in 
particular. For sake of argument, assume that the predicate is 
a complicated beast.)


This method will work regarless of the predicate, just check if 
the predicate isn't matched for the whole array using 
allSatisfy/anySatisfy.


  1   2   3   4   >