Improper display of Cyrillic in `pragma (msg, ...)` on Windows

2016-08-05 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,

To view Cyrillic CMD on Windows can be used 
`std.process.executeShell("chcp 65001 ");` and it works.


What should I use to change the encoding to UTF-8 to the compiler 
messages in `pragma(msg, ...)` on Visual D?


//
import std.stdio, std.process;

void main() {

executeShell("chcp 65001");
writeln("Привет, мир!"); // Привет, мир! -> OK

pragma(msg, "Привет, мир!"); // Привет, РјРёСЂ! -> wrong

}
//

PS C++ supports the following directive in Visual Studio:
https://msdn.microsoft.com/en-us/library/mt708823.aspx


Re: to auto or not to auto ( in foreach )

2016-07-16 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 16 July 2016 at 14:00:56 UTC, dom wrote:

foreach(auto v; msg)
  writeln(v);

gives an error that a basic type is expected

foreach(v; msg)
  writeln(v);

works

.. but why?



`Note: The ForeachTypeAttribute is implicit, and when a type is 
not specified, it is inferred. In that case, auto is implied, and 
it is not necessary (and actually forbidden) to use it.`

http://dlang.org/spec/statement.html#ForeachStatement


Re: fast way to insert element at index 0

2015-06-22 Thread Dennis Ritchie via Digitalmars-d-learn

On Tuesday, 23 June 2015 at 05:16:23 UTC, Assembly wrote:
What's a fast way to insert an element at index 0 of array? now 
that the code is working I want to clean this:


void push(T val)
{
T[] t = new T[buffer.length + 1];
t[0] = val;
t[1 .. $] = buffer;
buffer = t;
}

I did this because I didn't find any suble built-in data 
structure that let me insert an item into a specific index at 
first search. Slist does have insertFron(), exactly what I'm 
looking for it's a linked list.


I think you want to do something like this:

void main() {

import std.algorithm;

auto a = [1, 2, 3];

int val = 5;

a = val ~ a; // vector.pushFront();

assert(equal(a[], [5, 1, 2, 3]));
}


Re: Higher Order Range Pattern

2015-06-22 Thread Dennis Ritchie via Digitalmars-d-learn
On Monday, 22 June 2015 at 15:25:12 UTC, Steven Schveighoffer 
wrote:

On 6/22/15 11:04 AM, Dennis Ritchie wrote:

Hi,
I recently came across the following code:
http://wiki.dlang.org/Higher_Order_Range_Pattern


I can't understand why the properties and methods of the 
structure are

called in the correct order.
Why are the property `back()` and the method `popBack()` are 
not called

even once?


Because std.algorithm.equal does not use back or popBack.


In general, please explain how it all works.


I have a feeling you are not understanding something. This code 
is pretty straightforward, I don't know what else to explain 
about it.


-Steve


Thanks. I understand everything, just std.algorithm.equal 
introduced me to the great confusion :)

Now everything fell into place.


Higher Order Range Pattern

2015-06-22 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,
I recently came across the following code:
http://wiki.dlang.org/Higher_Order_Range_Pattern


I can't understand why the properties and methods of the 
structure are called in the correct order.
Why are the property `back()` and the method `popBack()` are not 
called even once?

In general, please explain how it all works.

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

struct Retro(Range)
{
@property
{
auto ref front() { debug writeln("back"); return 
range_.back;  }
auto ref back()  { debug writeln("front"); return 
range_.front; }
bool empty() { debug writeln("empty"); return 
range_.empty; }

}

void popFront() { debug writeln("popBack"); range_.popBack(); 
}
void popBack()  { debug writeln("popFront"); 
range_.popFront(); }


Range range_;
}

auto retro(Range)(Range range)
{
return Retro!Range(range);
}

void main()
{
import std.algorithm;

auto arr = [1, 2, 3, 4, 5];
assert(equal(retro(arr), [5, 4, 3, 2, 1]));
}
```
http://rextester.com/FMPGS76502


Re: How to avoid multiple spelling `import`

2015-06-16 Thread Dennis Ritchie via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:41:14 UTC, Daniel Kozák wrote:


On Tue, 16 Jun 2015 11:45:22 +
Dennis Ritchie via Digitalmars-d-learn
 wrote:

I just want to import individual features of these modules.


mixin template include(w...)
{
mixin _include!(w.length - 1, w);
}

mixin template _include(long N, i...)
{

mixin("import " ~ i[N] ~ ";");
mixin _include!(N - 1, i);
}

mixin template _include(long N : 0, i...)
{

mixin("import " ~ i[N] ~ ";");
}

mixin include!(
"std.stdio : writeln, write",
"std.conv : to"
);

void main() {
writeln(to!string(7));
}


Thanks. Maybe I'll use this code in your own programs.

I still believe that this design deserves existence in D:
https://issues.dlang.org/show_bug.cgi?id=14704


Re: How to avoid multiple spelling `import`

2015-06-16 Thread Dennis Ritchie via Digitalmars-d-learn
Maybe not everyone needs these features. But, unfortunately, I 
often use a lot of imported modules. And use every time the word 
`import` very bad.


version (none) {
import std.math,
   std.conv,
   std.stdio,
   std.ascii,
   std.range,
   std.array,
   std.regex,
   std.format,
   std.bigint,
   std.traits,
   std.random,
   std.string,
   std.numeric,
   std.variant,
   std.typecons,
   std.container,
   std.algorithm,
   std.typetuple,
   std.exception,
   core.checkedint;
}

I just want to import individual features of these modules.


Re: How to avoid multiple spelling `import`

2015-06-16 Thread Dennis Ritchie via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 11:16:32 UTC, Idan Arye wrote:
There is no problem to be solved here. Having to type `import` 
for each imported module is not big enough a burden to justify 
this additional syntax.


No, I think it is a holdover from C++-times — to write `import` 
for each new header file.


For example, this feature is implemented Go:

import (
"os"
"bufio"
"strings"
"fmt"
)


How to avoid multiple spelling `import`

2015-06-16 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,

I can write this:

import std.range : chain, split;

But I can not write this:

import std.range : chain, split, std.algorithm : map, each;

We have several times to write the word `import`:

import std.range : chain, split;
import std.algorithm : map, each;

Does D something to solve this problem? Maybe there is something 
like:


import std.range{chain, split}, std.algorithm{map, each};

import std.range(chain, split), std.algorithm(map, each);

import {
std.range : chain, split;
std.algorithm : map, each;
}


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 18:15:30 UTC, Dennis Ritchie wrote:
Actually, I will file issue `std.conv` in Phobos to add such 
specifications. It will suit me.


*specializations


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 17:39:25 UTC, Kagamin wrote:
Type is probably possible, though conversion method will be 
simpler. You can even try to write a specialization of `to` for 
multidimentional arrays if it doesn't work.


It appears the problem can be solved by creating specifications 
.to!strArray, which will determine the dimension of the array and 
convert it to char[][][][]...


Actually, I will file issue `std.conv` in Phobos to add such 
specifications. It will suit me.


Thanks to all. I just didn't know that such a conversion is 
running.


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 17:37:31 UTC, anonymous wrote:

Please show how it is not. Seems to work just fine.


OK. Still, this method works:

char[][][][][][] strArr = ["foo", "baz"], ["bar", 
"tor".to!(char[][][][][])];


But I don't want to write this `.to!(char[][][][][])`.

On Saturday, 13 June 2015 at 17:37:31 UTC, anonymous wrote:
Your definitions of "something like that" and "other ways" are 
unreasonably narrow, in my opinion. Typing out ".dup" is D's 
way to do mutable strings. You just don't like it.


Yes, I don't like it.


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 16:20:46 UTC, anonymous wrote:

Do you like to write?
char[][] strArray = ["foo".dup, "bar".dup, "baz".dup];


Ok. That's all you're on about? Basically you'd like this:
char[] s = "foo";
and this:
char[][] a = [["foo"]];
etc.


Yes. That's right, and not otherwise :)

Yeah, that would be neat. But typing out ".dup" isn't that bad, 
and converting a `string[]` to a `char[][]` is simple:

import std.conv: to;
auto a = ["foo"].to!(char[][]);


Yes, but it is not suitable for multidimensional array of strings.


I suggest that such an option:
str[] strArray = ["foo", "bar", "baz"];


I don't see how adding a new builtin type `str` would solve 
anything.


And why in C++ is running `std::vector` ?
Really in D can not do something like that?

Maybe a new type will not solve anything, but there should be 
other ways to do in D analogue strings of C++.


On Saturday, 13 June 2015 at 16:22:44 UTC, anonymous wrote:

I don't understand what you're trying to say with that quote.


I would not say `simpler`, and `basic`. I just forgot the right 
word, because my English is not good enough.


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote:
Huh? You mean with string literals? That would be a rather 
silly reason to avoid `char[]`. Please show an example of .dup 
you'd like to avoid.


Yes, string literals.

I understand that the type of `string[]` to D is a simple data 
type than `char[][]`,


Are you saying that `string[]` is simpler than `char[][]`? 
That's not true: `string` is an alias for `immutable(char)[]`, 
so `string[]` is the same as `immutable(char)[][]`.


On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer 
wrote:
But really, a string is immutable. There's not a way around 
that. A string is the most basic level of array primitive, not 
even mutable arrays of non-char types have that, and it's an 
annoyance. From there, you have to build the data out of ROM 
into the heap.

http://forum.dlang.org/post/mjctql$j19$1...@digitalmars.com


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote:

Please show an example of .dup you'd like to avoid.


For example, if you need to create a five-dimensional array of 
strings :)


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 15:45:34 UTC, anonymous wrote:
Before jumping to a solution, please elaborate on the perceived 
problem. I have a feeling that there is none.


Do you like to write?
char[][] strArray = ["foo".dup, "bar".dup, "baz".dup];

I suggest that such an option:
str[] strArray = ["foo", "bar", "baz"];

On Saturday, 13 June 2015 at 15:38:31 UTC, Dennis Ritchie wrote:
Ie str, wstr, dstr be mutable counterparts immutable strings 
respectively str (mutable(char[])), wstr (mutable(wchar[])), 
dstr (mutable(dchar[])). In C++:

std::vector


std::string in C++.


str[], wstr[], dstr[] in C++:
std::vector >


std::vector in C++.


Re: char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 15:21:19 UTC, Dennis Ritchie wrote:
I wish to propose the creation of new types of data D: str, 
wstr, dstr, which will be the analogs of C++ 
`std::vector`.


Ie str, wstr, dstr be mutable counterparts immutable strings 
respectively str (mutable(char[])), wstr (mutable(wchar[])), dstr 
(mutable(dchar[])). In C++:

std::vector

str[], wstr[], dstr[] in C++:
std::vector >


char[][] to std::vector - DIP or dmd-issue?

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

Hello, everyone!

I like to work with arrays of strings like `string[] strArray`, 
but unfortunately, they are immutable.


I do not like to work with arrays of strings such as `char[][] 
strArray`, because it is necessary to apply the method .dup each 
substring to make them work :)


I understand that the type of `string[]` to D is a simple data 
type than `char[][]`, but it seems to me that the problem is 
solved in C++:

std::vector stdArray;

I wish to propose the creation of new types of data D: str, wstr, 
dstr, which will be the analogs of C++ `std::vector`.


I do not know whether it is possible to create in the D, but I 
want to know where I write a sentence?
Can I file a dmd-issue, or should I create a DIP, because it is 
too big improvement?


Re: appender!(dchar[]) put fail

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 13:32:19 UTC, kerdemdemir wrote:
One more question I am asking those kind of questions to 
understand and not ask same stuff over and over, :


auto totalStr = chain(stringB.replicate(bCount), 
stringC.replicate(cCount));

writeln(typeof(totalStr.array()).stringof);
>dchar[]

But
auto totalStr = chain(stringB.repeat(bCount), 
stringC.repeat(cCount));

writeln(typeof(totalStr.array()).stringof);
>dchar[][]

It seems to me a little inconsistent. range.repeat and 
array.replicate gives result in difference dimension.


Is there any explanation or logic that I am missing which 
results this behaviour?


std.range.repeat is a lazy version unlike std.array.replicate:

5.repeat(3).writeln; // a lazy version // [5, 5, 5]
[5].replicate(3).writeln; // [5, 5, 5]
// but
[5].repeat(3).writeln; // a lazy version // [[5], [5], [5]]


Re: appender!(dchar[]) put fail

2015-06-13 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 13 June 2015 at 13:01:29 UTC, kerdemdemir wrote:

Sorry to making the discussion longer and wasting your times.

But I am looking for a way without for loops. Also looping 
every element one by one does not seems very efficient to me. 
Any advices for that?


Maybe it fit?

auto stringB = readln.chomp.map!(to!dchar).array;
auto stringC = readln.chomp.map!(to!dchar).array;

auto charAppender = appender!(dchar[][]);

auto totalStr = stringB.repeat(3).chain(stringC.repeat(5));

charAppender.put(totalStr);

writeln(charAppender);

charAppender.put("c"d.dup);
charAppender.put("test"d.dup);

writeln(charAppender);


Re: Json

2015-06-11 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 12 June 2015 at 00:35:35 UTC, Cassio Butrico wrote:
Thank you for answering me so fast , where do I get the DUB for 
windows ?


http://code.dlang.org/download


Re: Json

2015-06-11 Thread Dennis Ritchie via Digitalmars-d-learn

On Thursday, 11 June 2015 at 23:58:33 UTC, Cassio Butrico wrote:

What does the .json file and how to use it?


In D a file with the extension *.json is used to describe packets 
that are included in your project, the dependency manager DUB.


For example, you can install Eclipse with DDT and create a 
project with DUB. The file dub.json write the following:

-
{
"name" : "myDupApp",
"description" : "Carbon - Test.",
"dependencies" : {
"carbon": "~>1.4.1"
}
}
-

Save the file (Ctrl + S). Then in your project with DUB 
downloaded package `carbon`:

http://code.dlang.org/packages/carbon

After that you can safely use the package `carbon`:
-
import std.stdio, carbon.linear;;

void main() {
auto m = matrix!(2, 3, (i, j) => i * 3 + j);
writeln(m); // [[0, 1, 2], [3, 4, 5]]
}


Re: Reading array of integers readln performance issues

2015-06-11 Thread Dennis Ritchie via Digitalmars-d-learn

On Thursday, 11 June 2015 at 19:56:00 UTC, kerdemdemir wrote:

Hi;

To learn D better and challanging myself I am tring code 
computation's with D.


There is a question which is about reading a line of integer 
which consist of 20 elements.


My solution fails because "Time limit exceeded", I thought it 
is because of my algorithm first. I realize time limit is 
exceeded even before my algorithm starts while reading line of 
integers. I understand this by giving a wrong answer to 
question after readln statement. I did that to get a "wrong 
answer error" but my code still get a "Time limit exceed" error 
because "readln" takes very long time.


Can I achieve something faster than code below?

auto peopleMoney = stdin.readln().split().map!(a => 
to!int(a)).array();

if (peopleMoney.length == 20)
 writeln(":(");

Regards
Erdem


Ps: I do not want to bore you with long code, but I am sending 
link to whole program anyway if anyone need.

 http://codeforces.com/contest/549/submission/11537206


Your algorithm works for about quadratic time. For N = 20 
your algorithm will work terribly long. The function `readln()` 
nothing to do with:

http://codeforces.com/contest/549/submission/11476513

A faster way of `scanf`, but it will not help you, because your 
algorithm is slow.


Re: Python's features, which requires D

2015-06-11 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 10:58:33 UTC, Kagamin wrote:

On Saturday, 23 May 2015 at 02:36:14 UTC, Dennis Ritchie wrote:

For example, the code in Python looks quite natural:

a = [[int(j) for j in input().split()] for i in range(n)]

About D-code, I can not say:


auto a = stdin
.byLine
.map!(l => l.splitter.map!(to!int).array)
.take(n);


Well, list comprehension is built into language in python (and 
not in D), such level of support is definitely more streamlined.


Yes, but D is also possible to create a strong inclusion of list 
comprehensions. Here's the proof:

https://github.com/pplantinga/delight

Probably the coolest feature in Delight is list comprehensions. 
Delight uses functions in std.algorithm to generate an iterable 
range. The syntax is similar to Python's. See the last two 
lines of the code above for an example.


print { i * 2 for i in 0 .. 5 where i ^ 2 less than 5 }
# prints [0, 2, 4]


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-10 Thread Dennis Ritchie via Digitalmars-d-learn

On Wednesday, 10 June 2015 at 17:43:36 UTC, Ali Çehreli wrote:
On the other hand, if it's a manifest constant (enum, const 
static, etc.) then by definition it cannot be mutated. If we 
allowed mutation of compile-time expressions, then we would 
have a complicated language.


Unfortunately, the halting problem says that the analyzer does 
not exist. Although I don't believe it!



enum i = 42;
enum j = foo(i);// Did foo() use 42 or 43?
i = 43;
enum k = foo(i);// Did foo() use 42 or 43?

How can an enum value be changed? I find the above confusing.


So in fact, if `int` is evaluated at compile time, then we won't 
need constants or enums. Because they almost would not make 
sense. Although the issues associated with immutability, complex, 
I think they can be solved differently.


The great thing about D's CTFE is that we can use arbitrarily 
complex expressions as long as they are available at compile 
time. For example, it is possible to make 'i' above a foreach 
loop variable and call foo() with different values.


There is nothing great. Everything is based on constexpr of C++. 
I want something more revolutionary :)


What is your use case? I feel like it can be solved by other 
means.


There is no precedent special :) I just want to know more about 
the possibilities of D and the possibility of its compiler. D 
made me a terrible interest in compilers :)


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-10 Thread Dennis Ritchie via Digitalmars-d-learn

On Wednesday, 10 June 2015 at 17:13:34 UTC, anonymous wrote:
On Wednesday, 10 June 2015 at 17:00:34 UTC, Dennis Ritchie 
wrote:
Isnt it possible to come up with the interpreter compile-time, 
which will determine the operating time of the program at 
runtime at compile time.


Sounds like the halting problem. So, no, generally this is not 
possible.


Thanks. I had never heard of the halting problem. This is exactly 
what I wanted to know.


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-10 Thread Dennis Ritchie via Digitalmars-d-learn

On Wednesday, 10 June 2015 at 07:15:26 UTC, Ali Çehreli wrote:
My phrasing was off: By definition, initialization happens 
once. :) What I meant is, once initialized, a compile-time 
variable cannot be reassigned. The reason is, to effect compile 
time evaluation, one needs to use 'enum' (or 'static const') 
but 'enum' is a literal, i.e. it cannot be modified.


As I've shown, it is possible to use an expression that will be 
used as the value of the compile-time variable. As long as it 
is evaluable at compile time, the expression can be arbitrarily 
complex.


I understand your phrase :) I don't understand why the variables 
at compile time cannot be reassigned. I.e. why can't we use `int` 
instead of `enum` or `immutable`? Isnt it possible to come up 
with the interpreter compile-time, which will determine the 
operating time of the program at runtime at compile time. And if 
this time is small, it is possible to reassign variables at 
compile time more than once. Maybe it's something out of science 
fiction, but still. Is it possible somehow to create a more 
complex compilation process, which can reassign variables more 
than once?


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-09 Thread Dennis Ritchie via Digitalmars-d-learn

On Wednesday, 10 June 2015 at 03:38:32 UTC, Ali Çehreli wrote:
The way I understand it and the way it makes sense to me, :) 
variables that are generated at compile time can be initialized 
only once. It is not possible after initialization. However, 
the initialization of the variable can be as complex as needed:


Thanks. It turns out I can do this:

import std.stdio;

auto merge(Hashes)(Hashes[] hashes...) {

int[][int][int] result;

foreach (hash; hashes) {
foreach (key, value; hash) {
result[key] = value;
}
}

return result;
}

enum firstPart = [1 : [ 1 : [1, 1] ] ];
enum secondPart = [2 : [ 2 : [2, 2] ] ];

int[][int][int] init_ctHash(int i) {

auto result = merge(firstPart, secondPart);

result[i] = [ i : [i, i] ];

return result;
}

void main() {

enum int[][int][int] ctHash = init_ctHash(5);

enum t = merge(ctHash, init_ctHash(6));

writeln(t);
}

But I can not do so:

enum int[][int][int] ctHash = init_ctHash(5);

ctHash = merge(ctHash, init_ctHash(6));

I have a question: why variables may not be initialized more than 
once? Why can't they to resave at compile time?


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-09 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 15:20:17 UTC, Ali Çehreli wrote:

/* Some function that generates an AA */


Thanks. Beautiful code, but I want a little more :)

/* Some function that generates an AA */
int[][int][int] initHash(int i)
{
	/* It is nice to see that this function is not called at run 
time */

if (!__ctfe) {
import std.stdio;
writefln("%s is called at run time", __FUNCTION__);
}

return [i : [ i : [i, i] ] ];
}

/* Question: Is there a function to merge two AAs? */
int[][int][int] merge(Hash)(Hash[] hashes...)
{
	/* It is nice to see that this function is not called at run 
time */

if (!__ctfe) {
import std.stdio;
writefln("%s is called at run time", __FUNCTION__);
}

int[][int][int] result;

foreach (hash; hashes) {
foreach (key, value; hash) {
result[key] = value;
}
}

return result;
}

/* These three are generated at compile time */
enum firstPart = initHash(1);
enum secondPart = initHash(2);
enum int[][int][int] ctHash = merge(firstPart, secondPart);

void main()
{
import std.stdio;

static if (!(4 in ctHash)) {{
// ...
}}

ctHash[4][4] ~= [4, 4]; // I want this to work at compile time :)
// Possible?

static if (!!(4 in ctHash)) {{
// ...
}}
}


Re: Consevutive calls to r.front

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 8 June 2015 at 01:29:19 UTC, Dennis Ritchie wrote:

Here is how it is implemented in the book of Andrew:


Sorry, *Andrei.


Re: Consevutive calls to r.front

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 8 June 2015 at 01:15:30 UTC, Mike Parker wrote:
I know how to use a range :) What I'm asking about is a 
requirement on implementing front on a custom range. Is there a 
rule that says when I implement my own range, consecutive calls 
to front must return the same value until popFront is called?


Example:
Is this a valid implementation of front?
auto front() { return _member++; }

Or must it be this:
auto front() { return _member; }
void popFront() { ++_member; }

My current understanding is that the former is incorrect, but 
I'm looking for confirmation of that. I can't find it written 
down anywhere.


Here is how it is implemented in the book of Andrew:

@property bool empty(T)(T[] a) { return a.length == 0; }
@property ref T front(T)(T[] a) { return a[0]; }
void popFront(T)(ref T[] a) { a = a[1 .. $]; }


Re: Consevutive calls to r.front

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

The foreach loop takes place in a for loop like this:

import std.range;

for (auto __c = 5.iota; !__c.empty; __c.popFront) {
auto elem = __c.front;
}


Re: Consevutive calls to r.front

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 8 June 2015 at 00:42:12 UTC, Mike Parker wrote:
When implementing a custom range, is it correct to say that 
consecutive calls to r.front with no intervening calls to 
popFront should return the same value?


Yes. For examle:

import std.stdio, std.range;

template foo(T) {
auto foo(R)(R range) {
while (!range.empty) {
writeln(range.front);
// .front --> the first element of the range
range.popFront;
// .popFront --> to extract the first element of the 
range

}
}
}

void main() {
foo!(int[])([1, 2, 3]);
}


Re: How to remove the key from the `redBlackTree` with comparator" a <= b "?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 19:11:25 UTC, anonymous wrote:

On Sunday, 7 June 2015 at 19:04:08 UTC, Dennis Ritchie wrote:

auto rbt = redBlackTree!("a <= b", int)(1, 2, 3, 4, 5);
writeln(rbt.upperBound(3)); // prints [3, 4, 5]

How do I do with the comparator "a < b" ?


Use equalRange to get the elements that equal 3, too:
writeln(std.range.chain(rbt.equalRange(3), rbt.upperBound(3)));


Thank you!


Re: How to remove the key from the `redBlackTree` with comparator" a <= b "?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 18:50:47 UTC, anonymous wrote:

On Sunday, 7 June 2015 at 18:42:58 UTC, Dennis Ritchie wrote:
How do I remove the key from the `redBlackTree` with 
comparator "a <= b" ?


Do not use '<=' as a comparison function with RedBlackTree. It 
doesn't meet the requirements.


Quoting the documentation [1]:
Note that less should produce a strict ordering. That is, for 
two unequal elements a and b, less(a, b) == !less(b, a). 
less(a, a) should always equal false.


This doesn't hold for '<='.


OK. But I want to return a `upperBound` segment with the included 
`key`. It does not suit me:


auto rbt = redBlackTree!("a < b", int)(1, 2, 3, 4, 5);
writeln(rbt.upperBound(3)); // prints [4, 5]

I want it to be so:

auto rbt = redBlackTree!("a <= b", int)(1, 2, 3, 4, 5);
writeln(rbt.upperBound(3)); // prints [3, 4, 5]

How do I do with the comparator "a < b" ?


How to remove the key from the `redBlackTree` with comparator" a <= b "?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn
I understand that `removeKey` works only with the comparator "a < 
b":

http://dlang.org/phobos/std_container_rbtree.html#.RedBlackTree.removeKey
Removes elements from the container that are equal to the given 
values according to the less comparator.


How do I remove the key from the `redBlackTree` with comparator 
"a <= b" ?


auto rbt = redBlackTree!("a <= b", int)(1, 2, 3, 4, 5, 6, 7);
rbt.removeKey(6);

foreach (key; rbt)
write(key);
// prints 1234567


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 12:43:17 UTC, Nicholas Wilson wrote:

or enum


I suspect that enum can not add elements to the array.


Re: Is it possible to add items to the arrays and hashes at compile time?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 12:42:12 UTC, Nicholas Wilson wrote:

On Sunday, 7 June 2015 at 12:30:12 UTC, Dennis Ritchie wrote:
try using a pure function + static e.g.

 int[][int][int] somePureDefaultHash() pure
{
... //initialise it here
}

...
static hash = somePureDefaultHash();


static int[][int][int] hash;

hash[4][6] ~= [34, 65];
static if (!!(4 in hash)) {}
// Error: static variable hash cannot be read at compile time


Is it possible to add items to the arrays and hashes at compile time?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn
Does D the ability to add items to arrays and hashes at compile 
time?


For example, how do I do it in compile time?:

int[][int][int] hash;

hash[4][6] ~= [34, 65];
hash[5][7] ~= [4, 78, 21];


Re: The problem with the value that is returned from the condition in `static if`. Bug or feature?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 11:33:56 UTC, Marc Schütz wrote:

Not true:

immutable y = 1;
enum x = &y;

You can even do pointer arithmetics:

auto foo() {
auto x = [1,2,3,4];
auto y = &x[1];
return y[2];
}
pragma(msg, foo());


Then I do not see any problems hindering satisfy my report :)


Re: C++ static-if; how is it so different?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 02:38:57 UTC, lobo wrote:
If anyone knows why the proposal claims to be so different from 
D's static-if (modulo the restrictions mentioned) I'd be 
interested to know why.


http://forum.dlang.org/post/mke22o$2l9i$1...@digitalmars.com


Re: The problem with the value that is returned from the condition in `static if`. Bug or feature?

2015-06-07 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 7 June 2015 at 03:04:38 UTC, lobo wrote:

On Sunday, 7 June 2015 at 03:01:15 UTC, lobo wrote:

On Saturday, 6 June 2015 at 17:06:37 UTC, Dennis Ritchie wrote:

[snip]


`static if(5 in hash) {}` will not work because (5 in hash) 
returns a pointer to the value or null if the key oesn't exist.


bye,
lobo


just to be clear, you cannot have a pointer to anything at 
compile time because it doesn't exist and IMO changing 'in' to 
behave differently for static-if compared  runtime if would be 
bad.


This, of course, it is logical, but it somehow works:

immutable hash = [1 : 3, 5 : 7];

static if (!!(5 in hash))
writeln("OK"); // prints OK


Re: The problem with the value that is returned from the condition in `static if`. Bug or feature?

2015-06-06 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 6 June 2015 at 18:16:28 UTC, sigod wrote:

On Saturday, 6 June 2015 at 17:06:37 UTC, Dennis Ritchie wrote:

Pulls whether this issue? Or is it normal?


http://dlang.org/version.html#staticif:


StaticIfCondition:
   static if ( AssignExpression )

AssignExpression is implicitly converted to a boolean type, 
and is evaluated at compile time. The condition is satisfied 
if it evaluates to true. It is not satisfied if it evaluates 
to false.


So, I suppose it's should work without casting to bool or `!is` 
operator.


I reported this:
https://issues.dlang.org/show_bug.cgi?id=14659


The problem with the value that is returned from the condition in `static if`. Bug or feature?

2015-06-06 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,

No wonder that it works, because it is the legacy C++ (and I like 
that everything is different from zero is true):


if (5)
writeln("OK"); // prints OK

In the `static if` this condition also works perfectly:

static if (5)
writeln("OK"); // prints OK

Here idiomatic version check in the hash key:

int[int] hash = [1 : 3, 5 : 7];

if (hash.get(5, false))
writeln("OK"); // prints OK

In the `static if` this condition also works perfectly:

immutable hash = [1 : 3, 5 : 7];

static if (hash.get(5, false))
writeln("OK"); // prints OK

It's not quite idiomatic version to check if a key in the hash:

int[int] hash = [1 : 3, 5 : 7];

if (5 in hash)
writeln("OK"); // prints OK

The problem is that the `static if` it does not work:

immutable hash = [1 : 3, 5 : 7];

static if (5 in hash)
writeln("OK");
// Error: expression &[1:3, 5:7][5]
// is not constant or does not evaluate to a bool

You have to write something like that :)

immutable hash = [1 : 3, 5 : 7];

static if (!!(5 in hash))
writeln("OK"); // prints OK

Pulls whether this issue? Or is it normal?


Re: Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn
On Friday, 5 June 2015 at 20:14:51 UTC, Steven Schveighoffer 
wrote:

On 6/5/15 4:03 PM, Dennis Ritchie wrote:
It would be very good, because many have long been trying to 
implement

this functionality handmade :)

http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/shfmt


Yes, unfortunately that version is BSD licensed, won't make it 
into phobos.


I think that the developers of D will be able to write better if 
they take it! :D


Re: Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn
On Friday, 5 June 2015 at 19:08:19 UTC, Steven Schveighoffer 
wrote:

It's just so I didn't have to escape the quotes :D

Otherwise it looks like this:

return "writefln(\"mode " ~ mode ~ ": %s\", " ~ value ~ ");"


But such an option is possible to do work? : D

return `writefln(q"["mode]" ` ~ mode ~ `q"[: %s"]", ` ~ value ~ 
`);`;


I think we can probably do a compile-time substitution 
processor like rust (and other languages, including php and 
ruby) which just uses the variable name inside a string with 
some escape around it. `~var~` is not very succinct, I like 
$var better.


It would be very good, because many have long been trying to 
implement this functionality handmade :)


http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/shfmt


Re: Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 5 June 2015 at 14:31:19 UTC, anonymous wrote:
You messed up the quotes. You might be mistaking backticks for 
something special, but they're basically just quotes.


Yes, the sample program really made me think that gravis 
(backticks) - is something special...


Re: Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn
On Friday, 5 June 2015 at 14:23:15 UTC, Steven Schveighoffer 
wrote:

On 6/5/15 10:15 AM, Dennis Ritchie wrote:


Thanks. It looks really simple, but I still do not understand 
the

concept of using mixins in full.

I do not understand why in this line:
return `writefln("mode ` ~ mode ~ `: %s", ` ~ value ~ `);`;

use the following syntax:
~ mode ~ , ~ value ~


Because what foo is constructing is a string that makes sense 
in the *caller*, not inside foo. What those statements do is 
concat the *value* of mode (i.e. "Y" or "X") and the *value* of 
value (i.e. "3" or "2") to the string.


It's equivalent to rust using the ${e} to do variable 
substitution.


Thank you. Now everything is clear. Syntax `${e}` in Rust simpler 
than D ` ~ substitute the value ~ ` :)


Re: Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn
On Friday, 5 June 2015 at 13:13:15 UTC, Steven Schveighoffer 
wrote:

string foo(string mode, string value)
{
   return `writefln("mode ` ~ mode ~ `: %s", ` ~ value ~ `);`;
}

void main()
{
   mixin(foo("Y", "3"));
   mixin(foo("X", "2"));
}


Thanks. It looks really simple, but I still do not understand the 
concept of using mixins in full.


I do not understand why in this line:
return `writefln("mode ` ~ mode ~ `: %s", ` ~ value ~ `);`;

use the following syntax:
~ mode ~ , ~ value ~

For example, why here I can simply write:

void main() {
int b = 5;
mixin(`int a = b;`);
assert(a == 5);
}

Why should not I write like this:

void main() {
int b = 5;
mixin(`"int a = " ` ~ b ~ ` ";"`);
assert(a == 5);
}


Emulation macros and pattern matching on D

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn
Macros and operation of pattern matching `=>` in Rust I can write 
something like this:


macro_rules!foo {
(x => $e:expr) => (println!("mode X: {}", $e));
(y => $e:expr) => (println!("mode Y: {}", $e));
}

fn main() {
foo!(y => 3); // mode Y: 3
foo!(x => 2); // mode X: 2
}

How is it possible to simulate in D?


Re: Length of Dimension in Multidimensional Array?

2015-06-05 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 5 June 2015 at 07:53:52 UTC, Ralf the Bat wrote:

Probably a stupid question, but how do I find the length of each
dimension in a multidimensional array?


I slightly modified the function deepDup, who came up Ali Çehreli 
:)

http://beta.forum.dlang.org/post/mihl6m$1che$1...@digitalmars.com

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

auto deepLen(A)(A arr)
if (isArray!A)
{
writefln("%s.len = %s", arr, arr.length);
static if (isArray!(ElementType!A)) {
return arr.map!(a => a.deepLen).array;
} else {
return arr;
}
}

void main() {
auto arr = [1, 2, 3, 4], [0]], [[4, 3], [5, 6, 7];
arr.deepLen;
}

[1, 2, 3, 4], [0]], [[4, 3], [5, 6, 7].len = 1
1, 2, 3, 4], [0]], [[4, 3], [5, 6, 7.len = 1
[[[1, 2, 3, 4], [0]], [[4, 3], [5, 6, 7]]].len = 2
[[1, 2, 3, 4], [0]].len = 2
[1, 2, 3, 4].len = 4
[0].len = 1
[[4, 3], [5, 6, 7]].len = 2
[4, 3].len = 2
[5, 6, 7].len = 3


Re: Array declaration warning

2015-06-02 Thread Dennis Ritchie via Digitalmars-d-learn
I used to not even notice that if D declare an array in C-style, 
and then indexing it will also in C-style :)
Actually, I have a small question. And what is the advantage of 
indexing arrays D-style in front of a C-style arrays? Because 
C-style indexing is much more familiar: first, we point line, and 
then the columns.


import std.algorithm;

void main() {

int cArr[2][4];
assert(equal(cArr[], [[0, 0, 0, 0],
  [0, 0, 0, 0]]));

int[2][4] dArr;
assert(equal(dArr[], [[0, 0],
  [0, 0],
  [0, 0],
  [0, 0]]));
}


Re: string to char array?

2015-06-02 Thread Dennis Ritchie via Digitalmars-d-learn

On Tuesday, 2 June 2015 at 15:53:33 UTC, Alex Parrill wrote:
A string is, by definition in D, a character array, 
specifically `immutable(char)[]`. It's not like, for example, 
Java in which it's a completely separate type; you can perform 
all the standard array operations on strings.


Yes, I believe that this is a problem in D, and because when you 
create a multidimensional array mutable strings having real 
troubles with .deepDup. I think that will solve the problem of a 
new string data type is a built-in D, and because writing .dup, 
to create a mutated string, - it's really funny! This is problem!


Re: string to char array?

2015-06-02 Thread Dennis Ritchie via Digitalmars-d-learn

On Tuesday, 2 June 2015 at 15:07:58 UTC, Kyoji Klyden wrote:
quick question: What is the most efficient way to covert a 
string to a char array?


string s = "str";
char[] strArr = s.dup;


Re: Splitting a range into a range of tuples

2015-06-01 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 1 June 2015 at 22:31:38 UTC, Adam wrote:

Hi,

I have a string of pairs of integers, where pairs are delimited 
from each other by commas, and members of the pair are 
delimited by a space. I'd like to end up with something like a 
range of 2-tuples


I can offer this option:

import std.stdio, std.algorithm, std.array, std.range, 
std.format, std.typecons;


void main() {

string s = "192 14, 301 3, 578 0, 0 17";

int[] arr; int tmp;
foreach (el; s.split) {
formattedRead(el, "%s", &tmp);
arr ~= tmp;
}

Tuple!(int, int)[] tup;
foreach (el; zip(arr.stride(2), arr.dropOne.stride(2))) {
tup ~= tuple(el[0], el[1]);
}

tup.sort!"a[0] > b[0]";

writeln(tup);
}

/*[Tuple!(int, int)(578, 0), Tuple!(int, int)(301, 3), 
Tuple!(int, int)(192, 14), Tuple!(int, int)(0, 17)]*/




Re: Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-31 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 31 May 2015 at 07:28:02 UTC, Ali Çehreli wrote:
So, you want to skip that extra func() call and have the code 
be "inlined". That's one of the things what any decent 
optimizing compiler does anyway.


Yes, I think that there is an extra function call, because DMD is 
based on Zortech C++ backend, so I figured ... :)


I hear great things especially about ldc and that gdc is just 
good enough. Of course, one needs to check the assembly output 
to be sure that there is no extra function calls.


Ali


And yet in DMD I'm not sure :)

import std.stdio, std.algorithm;

static int idx;

void walk(R)(R range) {
while (!range.empty) {
range.front;
range.popFront;
}
}

struct Tap(alias func, R)
{
R range;

alias range this;

@property auto front()
{
func(range.front);
return range.front;
}
}

auto tap(alias func, R)(R range)
{
writeln(__FUNCTION__); // ???
return Tap!(func, R)(range);
}

void main() {
[5, 6, 7]
.map!(a => [idx++, a])
.tap!((a) { writeln(a[1..$]); })
.walk;
}


Re: Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-30 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 31 May 2015 at 06:04:40 UTC, Dennis Ritchie wrote:

mixin(newStr[0 .. $ - 4] ~ `[idx,` ~ newStr[$ - 4 .. $]);


mixin(newStr[0 .. $ - 4] ~ `idx,` ~ newStr[$ - 4 .. $]);


Re: Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-30 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 30 May 2015 at 23:58:44 UTC, Ali Çehreli wrote:

On 05/30/2015 12:19 PM, Dennis Ritchie wrote:

First, unfortunately, I don't understand you completely. Sorry 
about that... :)


Nothing to worry about! Now you will understand me till the 
end... :)


Regarding that, the intermediate range.front is already 
available right before the .walk part. You can do anything at 
that point. There was some proposals about a 'tap' algorithm 
that could be used for debugging purposes. Here is a quick 
implementation:


Yes, it is an intermediate stage of code that will help me to 
explain what I want to get.



import std.stdio, std.algorithm;

static int idx;

void walk(R)(R range) {
while (!range.empty) {
range.front;
range.popFront;
}
}

struct Tap(alias func, R)
{
R range;

alias range this;

@property auto front()
{
  func(range.front); // It's a necessary part of the 
code! :)

return range.front;
}
}

auto tap(alias func, R)(R range)
{
return Tap!(func, R)(range);
}

void main() {
[5, 6, 7]
.map!(a => [idx++, a])
.tap!((a) { writeln(a[1..$]); })  /* <-- This can use 
the
   * lambda syntax as 
well but
   * note that the 
return
   * value of the 
lambda is
   * ignored. So I 
think this

   * syntax is more
   * helpful. */
.walk;
}

Ali


I don't know, maybe it's something out of science fiction, but 
here's what I want to do :)


struct Tap(alias func, R)
{
R range;

alias range this;

@property auto front()
{
immutable string myStr = `func(mixin("range.front"));`;
immutable string newStr = `mixin(myStr);`;
	writeln(newStr); // I want them to be printed here 
`writeln([5]);`
mixin(newStr[0 .. $ - 4] ~ `[idx,` ~ newStr[$ - 4 .. $]); 
// I want them to be printed here `[0, 5];`

return range.front;
}
}

Is it possible to do using mixins or through any other means? Ie 
I want to catch the moment when `func` is replaced by the 
invocation of `writeln` :)


Re: Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-30 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 30 May 2015 at 19:19:21 UTC, Dennis Ritchie wrote:
I want to access the intermediate generation `range.front`. Is 
it possible? :)


In other words, I want to expand the array to the application to 
him of 'writeln'!


Re: Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-30 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 30 May 2015 at 06:50:09 UTC, Ali Çehreli wrote:

On 05/29/2015 06:07 PM, Dennis Ritchie wrote:

> Hi,
> This code prints the arrays:
> [5]
> [6]
> [7]
>
> import std.stdio, std.algorithm;
>
> static int idx;

Do you want to share that for the first element of every 
two-element array or do you want to start from 0 for every 
range?


I want to share...


> void walk(R)(R range) {
>  while (!range.empty) {
>  range.front;
>  range.popFront;
>  ++idx;
>  }
> }

As a reminder, there is also the recent 'each', which is eager 
as well.


But I want to do this is to `map` :)


> void main() {
>  [5, 6, 7].map!(a => [a].writeln).walk;
> }
>
> How should I apply mixins to `range.front` to the program to
print the
> arrays:
> [0, 5]
> [1, 6]
> [2, 7]

Unless mixin required for another reason, there are other ways 
of achieving the same.


I just want to present the results of the intermediate 
performance (which I plan to reach through the mixin) 
`range.front` as a string, to then modify it with the help of 
mixin to get directly to the array.



> Ie I want to get something like this:
>
> void walk(R)(R range) {
>  while (!range.empty) {
>  // mixin(`[idx ~ "mixin("range.front")"[1 .. $]);`);
>  range.popFront;
>  ++idx;
>  }
> }
>
> Can I do this?
>
> -
> Thank you for the function `walk` Mark Isaacson of
presentation DConf 2015:
> http://dconf.org/2015/talks/isaacson.pdf

The following program produces the desired output twice. The 
first one starts from 0 for the index, the second one shares 
the index as in your code.


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

void main() {
zip(sequence!"n", [5, 6, 7])
.map!(a => [a.expand])
.each!writeln;

static int idx;

[5, 6, 7]
.map!(a => [idx++, a])
.each!writeln;
}


Thank you for your examples, but I want to do something else.

Ie I want to access the intermediate generation `range.front` 
with two mixins or by other means. `range` is of type 
`MapResult!(__lambda1, int[])([5, 6, 7], null)` — I want to get 
the generation of this intermediate, i.e. something like 
`range.front` --> `[5].writeln` and present `[5].writeln` as a 
string, to modify the line like so `[5].writeln` --> 
`[5].writeln`[1 .. $] --> `[idx ~ `[5].writeln`[1 .. $]` --> 
`[idx, 5].writeln` with the help of mixins. :)


I want to access the intermediate generation `range.front`. Is it 
possible? :)


Mixin - to get to the content-type `MapResult!(__lambda1, int[]).MapResult`

2015-05-29 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,
This code prints the arrays:
[5]
[6]
[7]

import std.stdio, std.algorithm;

static int idx;

void walk(R)(R range) {
while (!range.empty) {
range.front;
range.popFront;
++idx;
}
}

void main() {
[5, 6, 7].map!(a => [a].writeln).walk;
}

How should I apply mixins to `range.front` to the program to 
print the arrays:

[0, 5]
[1, 6]
[2, 7]

Ie I want to get something like this:

void walk(R)(R range) {
while (!range.empty) {
// mixin(`[idx ~ "mixin("range.front")"[1 .. $]);`);
range.popFront;
++idx;
}
}

Can I do this?

-
Thank you for the function `walk` Mark Isaacson of presentation 
DConf 2015:

http://dconf.org/2015/talks/isaacson.pdf


Re: Replacing nested loops foreach using map/each/etc

2015-05-25 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 25 May 2015 at 19:16:04 UTC, anonymous wrote:

On Monday, 25 May 2015 at 17:52:09 UTC, Dennis Ritchie wrote:

But why is the solution breaks down when `s = 1` ? :)

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

int c;
const x = 12, y = 65, z = 50, s = 10;


Which is it, now? 4 or 5 zeros?


No difference!


void solve(Range)(Range r) {
	cartesianProduct(r, r, r).filter!(i => i[0] * (y + 3 * z) + 
i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout;

}

void main() {

   auto a = iota(0, x + 1).array;

   solve(a);

   writefln(`%s total`, c);
}

void dout(Tuple)(Tuple idx) {
   ++c;
}
-
http://rextester.com/XGDL26042


What do you mean it "breaks down"? Your original code doesn't 
print anything for s = 10_000 or s = 100_000, either.


Excuse me, this is my blemish! I forgot that the constant `x` 
depends on `s`. Everything works correctly:


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

void solve(Range)(Range r) {
cartesianProduct(r, r, r).filter!(i => i[0] * (y + 3 * z) + 
i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout;

}

const y = 65, z = 50, s = 10;
const x = s / (y + z);

void main() {

auto a = iota(0, x + 1);

solve(a);
}

auto dout(Tuple)(Tuple idx) {
writefln(`%s apples`, idx[0] + idx[1] + idx[2]);
writefln(`%s gingerbread`, idx[0] * 3 + idx[1] * 2 + idx[2]);
writefln(`%s pharynx tea`, idx[0] * 3 + idx[1] * 2 + idx[2]);
writefln("Sour: %s; semi-acid: %s; sweet: %s.\n", idx[0], 
idx[1], idx[2]);

}
-
http://rextester.com/MMCI9993


Re: Replacing nested loops foreach using map/each/etc

2015-05-25 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 25 May 2015 at 17:19:27 UTC, Meta wrote:
`each` doesn't support braces. There are 4 ways to write a 
function/delegate literal in D (with a few minor variations):


Short form:
function(int i) => i;
(int i) => i
(i) => i
i => i

Long form:
function(int i) { return i; }
(int i) { return i; }
(i) { return i; }
{ return 0; }

http://dlang.org/expression.html#FunctionLiteral
function


Thanks.

But why is the solution breaks down when `s = 1` ? :)

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

int c;
const x = 12, y = 65, z = 50, s = 10;

void solve(Range)(Range r) {
	cartesianProduct(r, r, r).filter!(i => i[0] * (y + 3 * z) + i[1] 
* (y + 2 * z) + i[2] * (y + z) == s).each!dout;

}

void main() {

auto a = iota(0, x + 1).array;

solve(a);

writefln(`%s total`, c);
}

void dout(Tuple)(Tuple idx) {
++c;
}
-
http://rextester.com/XGDL26042


Re: Replacing nested loops foreach using map/each/etc

2015-05-25 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 25 May 2015 at 16:41:35 UTC, Meta wrote:

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

void main()
{
const x = 12, y = 65, z = 50, s = 1435;
auto a = iota(0, x + 1);
cartesianProduct(a, a, a)
.filter!(i => i[0] * (y + 3 * z)
+ i[1] * (y + 2 * z)
+ i[2] * (y + z)
== s)
.each!((idx)
  {
  writeln(idx[0] + idx[1] + idx[2]);
  writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
  writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
  writeln(idx[0], idx[1], idx[2]);
  });
}


Thanks. I do not even know what `each` support braces.


Re: Replacing nested loops foreach using map/each/etc

2015-05-25 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 25 May 2015 at 15:06:45 UTC, Alex Parrill wrote:
Hint: Use `cartesianProduct` [1] with three iota ranges to 
replace the foreachs, and `filter` to replace the if


[1] 
http://dlang.org/phobos/std_algorithm_setops.html#.cartesianProduct


Thank you. Is it possible to replace the loop `foreach` function 
`each` or `chunkBy` with the auxiliary functions?


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

void main() {

const x = 12, y = 65, z = 50, s = 1435;

auto a = iota(0, x + 1);

foreach (idx; cartesianProduct(a, a, a).filter!(i => i[0] * 
(y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s)) {

writeln(idx[0] + idx[1] + idx[2]);
writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
writeln(idx[0], idx[1], idx[2]);
}
}
-
http://rextester.com/HZP96719


Replacing nested loops foreach using map/each/etc

2015-05-25 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,
Is it possible to write such a construction that could push 
immediately to a conditional statement without using nested 
loops? Ie organize search directly in the iterator if provided by 
a map / each / iota and other support functions.

Ie I want to write this code shorter :)

import std.stdio;

void main() {

const x = 12, y = 65, z = 50, s = 1435;

foreach (i; 0 .. x + 1)
foreach (j; 0 .. x + 1)
foreach (k; 0 .. x + 1)
if (i * (y + 3 * z) + j * (y + 2 * z) + k * (y + 
z) == s) {

writeln(i + j + k);
writeln(i * 3 + j * 2 + k);
writeln(i * 3 + j * 2 + k);
writeln(i, j, k);
}
}
-
http://rextester.com/SJTU87854


Re: Python's features, which requires D

2015-05-24 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 24 May 2015 at 15:53:24 UTC, Idan Arye wrote:
But according to the Blub Paradox, your(Or mine. Or Paul 
Graham's) opinion on whether or not a stronger language than 
Lisp has appeared can not be trusted!


Based on an article Graham about Blub Paradox, I can conclude 
that Blub Paradox programmers only acts on a certain age. It is 
possible that this occurs after the age of 25 years. And since I 
am under 25 years old, I think I can be trusted completely :)

-
Paul Graham:
"This idea is rarely followed to its conclusion, though. After a 
certain age, programmers rarely switch languages voluntarily. 
Whatever language people happen to be used to, they tend to 
consider just good enough.

...
But I don't expect to convince anyone (over 25) to go out and 
learn Lisp."


Re: Python's features, which requires D

2015-05-24 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 24 May 2015 at 14:15:55 UTC, Idan Arye wrote:
This IS ironic, because Paul Graham claims lisp to be the most 
powerful, but if he have ever encounter a more powerful 
language he couldn't accept it is more powerful than lisp due 
to the very same "Blub Paradox" he describes himself.


Probably! But, in my opinion, it has not yet appeared stronger 
language Lisp, so "Blub Paradox" is not yet threatened with 
Graham :)


Re: Python's features, which requires D

2015-05-24 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 24 May 2015 at 02:43:47 UTC, Idan Arye wrote:
I'm a fan of lisp(Clojure being my favorite. Too bad it takes 
about a century just to load the runtime...), and yet I find it 
quite ironic that Paul Graham claims lisp to be the most 
powerful language right after claiming that programmers can't 
understand - and therefore disregard - the power of languages 
more powerful than the ones they use...


This is not ironic, because I did neglect the power of Lisp, 
because not quite understand it fully :) The power of Lisp - his 
worst enemy. Strange Lisp syntax allows you to write powerful 
macros, which is unique in other languages, but many programmers 
do not understand Lisp syntax (and therefore may find it funny).


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 21:32:51 UTC, anonymous wrote:

On Saturday, 23 May 2015 at 21:08:19 UTC, Dennis Ritchie wrote:
Perhaps that's not the site, and in Windows. That's what gives 
me in CMD:


456 4 4 8 99 456
[[456, 4, 4, 8, 99, 456]13 546
std.conv.ConvException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2013): 
Unexpected end of input when converting from type char[] to 
type int


That's a different issue. Works fine for me in wine.

You may be typing spaces before/after the numbers.


Yes, I think I scored one space after 546.


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 21:09:45 UTC, weaselcat wrote:
After another review, I think some of these conversions to D 
could be expressed much easier if the built-in slice had 
multidimensional slicing


It was added in 2.066* but I don't think there's any plans to 
add support for it to slices.


Actually not a bad idea: add to Phobos module std.multiarray.

* - you can see an example at 
http://denis-sh.bitbucket.org/unstandard/unstd.multidimarray.html


Embed multidimensional slices directly into the language is not
very good, but in a separate module, why not...


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 20:44:37 UTC, cym13 wrote:
Not sure what kind of meat you mean, but I really don't see 
much meat in ranges. Of course, this is 10 times better and 
easier to use than STL iterators C++. For me the most 
important feature D are mixins, which I, unfortunately, rarely 
use. I'm waiting for new features from D: for new designs, not 
simply the expansion of Phobos and fix bugs in DMD :) Should I 
wait for these new features? It seems to me that everyone is 
not enough to simply correct C++ — they all want a language in 
which many different sugar. In my opinion, sugar you can try 
to shake out of Lisp, if possible :)




I think you are mistaken. The hard part about growing a
programming language isn't adding features, it's finding the 
right

core of features that are stable yet generic enough to answer
everything in their own way.

This is why C still is such a popular language, it hardly 
evolvevd

since the begginning. It is also why Java in its time or Go know
are popular among companies: they are boring, just boring. But 
they

are stable. C++ wanted to address every problem, and look at it
know.

We have to develop a style, not more features. Python has its 
own
style but every new feature (and they are rare) is very 
diligently
examined. Most are refused. There is the python way. If python 
isn't

the right tool for the job, then the best thing to do is finding
another tool, not scotch an extension to the first one.

I like python. I like D. I like other languages. Of course 
sometimes
I'd like to have, say, UFCS in python or list comprehension in 
D.
But D isn't the best language to do python, python is. And as 
there

is a python way, there is a D way.

This is not to say that we should dismiss any good concept of 
other
languages, but those concepts fit in a philosophy, in an 
ecosystem.


You may find it nonsense, but Paul Graham says that each language 
has its own power. He believes that Lisp is the most powerful 
language, and programmers who write in other languages, he said 
Blub programmers. Learn more about "The Blub Paradox" can be read 
in the article Graham:

http://www.paulgraham.com/avg.html

What about increasing the number of features and stability, I 
agree. You may need more stability.


Based on the theory of Graham, I should point out that the level 
of power python clearly lower than D :)


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 20:57:10 UTC, anonymous wrote:

On Saturday, 23 May 2015 at 20:25:18 UTC, Dennis Ritchie wrote:

This does not work!

enum n1 = 5;
writeln(stdin.byLine
.map!(line => line.split(" ").map!(x => to!int(x)))
);
-
http://rextester.com/VGHZF81178


The code itself is ok.

That site has broken newlines. You can see here that 
std.ascii.newline is different from what the site actually 
feeds to the program: .


You can work around that by passing the correct line terminator 
to byLine: .


Perhaps that's not the site, and in Windows. That's what gives me 
in CMD:


456 4 4 8 99 456
[[456, 4, 4, 8, 99, 456]13 546
std.conv.ConvException@C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2013): 
Unexpected end of input when converting from type char[] to type 
int


0x0040FD10 in pure @safe int std.conv.parse!(int, 
char[]).parse(ref char[]) at 
C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2015)
0x00410C74 in pure @safe int std.conv.toImpl!(int, 
char[]).toImpl(char[]) at 
C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(1738)
0x0040FB92 in pure @safe int 
std.conv.to!(int).to!(char[]).to(char[]) at 
C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(296)
0x0040FB7E in pure @safe int 
acm.main().__lambda1!(char[]).__lambda1(char[]).__lambda2!(char[]).__lambda2(char[])
0x00410DA7 in pure @property @safe int 
std.algorithm.iteration.__T9MapResultS553acm4mainFZ17__T9__lambda1TAaZ9__lambda1MFAaZ9__lambda2TAAaZ.MapResult.front() 
at C:\D\dmd2\windows\bin\..\..\src\phobos\

std\algorithm\iteration.d(548)
0x004122D4 in 
D3std6format169__T11formatRangeTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration76A5C81813C007BD25AC82BE82F3551A66 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(240

9)
0x0041213F in 
D3std6format169__T11formatValueTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration768E862681E57D43E301EA954AAC63F894 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(311

2)
0x004120AA in 
D3std6format171__T13formatElementTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iterationC8BE2524D6E8B27505208FE77A7AABE7 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(261

9)
0x00411B89 in 
D3std6format172__T11formatRangeTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration7956A969C910F877511562257DEEBA50CE 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(241

0)
0x00411A27 in 
D3std6format172__T11formatValueTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iteration793B5F1700DB9877FAF5528C7A1A67E5DC 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(311

2)
0x00411991 in 
D3std6format174__T13formatGenericTS3std5stdio4File17LockingTextWriterTS3std9algorithm9iterationD44607637B1FEE3931BFD9A68911D4FE 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(345

1)
0x0041185C in 
D3std6format175__T14formattedWriteTS3std5stdio4File17LockingTextWriterTaTS3std9algorithm9iteratD57474F5CD8E0DF85B780AE37888E8BE 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\format.d(521

)
0x00411320 in 
D3std5stdio4File129__T5writeTS3std9algorithm9iteration79__T9MapResultS213acm4mainFZ9__lambda1TSD37A9C7F430415C668F40B8F70856955 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(1200

)
0x0041120A in 
D3std5stdio129__T7writelnTS3std9algorithm9iteration79__T9MapResultS213acm4mainFZ9__lambda1TS3stC41BC71D1E9C2BC78EB8446AC4667CCD 
at C:\D\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(2932

)
0x0040203D in _Dmain at 
C:\Users\REiS\Documents\Projects\acm\acm\acm.d(21)
0x00427E06 in 
D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
0x00427DDB in void rt.dmain2._d_run_main(int, char**, extern (C) 
int function(char[][])*).runAll()

0x00427CF3 in _d_run_main
0x00427884 in main
0x0043E701 in mainCRTStartup
0x76BB7C04 in BaseThreadInitThunk
0x775AAD1F in RtlInitializeExceptionChain
0x775AACEA in RtlInitializeExceptionChain


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 19:22:40 UTC, Alex Parrill wrote:
You seem to be focusing on D's arrays only, but the real meat 
is in ranges, which are more generic. Also note that the above 
solution doesn't allocate any of the ranges in the heap; 
they're all on the stack (as opposed to Python, where you have 
to allocate lists or use iterators+itertools).


Also present ranges from the time of D1 and Tango, because there 
is nothing surprising about them. Need new features!


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 19:22:40 UTC, Alex Parrill wrote:

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

void main() {
enum n1 = 5;
writeln(stdin.byLine
.map!(line => line.split(" ").map!(x => to!int(x)))
);

writeln("--");

enum n2 = 6;
writeln(iota(n2)
.map!(i => chain(
repeat("2", i),
only("1"),
repeat("0", n2 - i - 1),
only("\n")
).joiner(" ")).joiner
);
}


(I omitted evens/odds because it's been addressed and fizzbuzz 
because there's probably dozens of them floating around)


You seem to be focusing on D's arrays only, but the real meat 
is in ranges, which are more generic. Also note that the above 
solution doesn't allocate any of the ranges in the heap; 
they're all on the stack (as opposed to Python, where you have 
to allocate lists or use iterators+itertools).


This does not work!

enum n1 = 5;
writeln(stdin.byLine
.map!(line => line.split(" ").map!(x => to!int(x)))
);
-
http://rextester.com/VGHZF81178

Even if you wanted to write this:

enum n = 5;
writeln(stdin.byLine
.map!(line => line.split(" ").map!(x => to!int(x))).take(n)
);
-
http://rextester.com/COWE75794

That it's still not working. In my opinion, and should not work :)

You seem to be focusing on D's arrays only, but the real meat 
is in ranges, which are more generic.


Not sure what kind of meat you mean, but I really don't see much 
meat in ranges. Of course, this is 10 times better and easier to 
use than STL iterators C++. For me the most important feature D 
are mixins, which I, unfortunately, rarely use. I'm waiting for 
new features from D: for new designs, not simply the expansion of 
Phobos and fix bugs in DMD :) Should I wait for these new 
features? It seems to me that everyone is not enough to simply 
correct C++ — they all want a language in which many different 
sugar. In my opinion, sugar you can try to shake out of Lisp, if 
possible :)


Also note that the above solution doesn't allocate any of the 
ranges in the heap; they're all on the stack (as opposed to 
Python, where you have to allocate lists or use 
iterators+itertools).


And yet I do not like how the function byLine. It seems to me 
that we need analogues that will not work so damp as byLine.


All right. Next time I will try to combine features that are not 
available in D, and of the faster languages: Erlang, Perl, Lisp, 
Nim, Rust, Scala etc. :)


Re: Python's features, which requires D

2015-05-23 Thread Dennis Ritchie via Digitalmars-d-learn

On Saturday, 23 May 2015 at 10:58:33 UTC, Kagamin wrote:
Well, list comprehension is built into language in python (and 
not in D), such level of support is definitely more streamlined.


Well, what's to keep D more functions to work with slist and 
dlist ?

In my opinion, lists in D completely bald :)

After all, there is a module in Phobos std.array, so why not make 
the module std.list.

Do lists in D can be done as powerful as arrays?


Re: Python's features, which requires D

2015-05-22 Thread Dennis Ritchie via Digitalmars-d-learn

By the way, Python has deepDup :)

http://rextester.com/KBFA82886


Re: Python's features, which requires D

2015-05-22 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 22 May 2015 at 05:31:38 UTC, Ali Çehreli wrote:

Here is my attempt:

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

void main()
{
// Replace 'none' with 'all' to activate.
version (none) {
const n = 5;

auto a = stdin
 .byLine
 .map!(l => l.splitter.map!(to!int).array)
 .take(n);

writeln(a);
writeln("-");
}

{
const n = 6;

auto a = iota(n)
 .map!(i => chain([2].replicate(i),
  [1],
  [0].replicate(n - i - 1)));

writefln("%(%(%s %)\n%)", a);
writeln("-");
}

{
const x = [ 1, 2, 3, 4, 5, 6 ];

writeln(x.stride(2));
writeln(x.dropOne.stride(2));
writeln("-");
}

{
// The internet does not need another fizz buzz. :p
}
}

Ali


Yes, it looks pretty good :) Thanks. But...

It seems to me that D lacks features that allow you to write 
function readln/readln.strip/readln.split just inside the lambda. 
stdin.byLine is a good feature, but it captures the entire input 
stream, which I should handle all or take lambdas function 
take(n) n lines and then still handle all of these lines right 
away. Ie stdin.byline used everywhere is not always convenient!


For example, the code in Python looks quite natural:

a = [[int(j) for j in input().split()] for i in range(n)]

About D-code, I can not say:


auto a = stdin
 .byLine
 .map!(l => l.splitter.map!(to!int).array)
 .take(n);


I can call the map with the existing array:

import std.stdio, std.algorithm, std.conv, std.array;

void main()
{
auto a = [1, 2, 3];

auto b = a.map!(c => c ~ 
readln.split.map!(to!int).array).array;


writeln(b);
}
-
http://rextester.com/MBUMHI13858

But I can not call the readln n times without a map:

import std.stdio, std.conv, std.algorithm, std.array, std.range;

void main() {

auto a = [1, 2, 3];

auto b = [readln.split.map!(to!int).array].take(3);

writeln(b);
}
-
http://rextester.com/KCJ9346

Ie readln function cycle is needed for, another lambda or revised 
map! Is there a function in Phobos?


Re: Python's features, which requires D

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 22 May 2015 at 02:18:23 UTC, weaselcat wrote:

On Friday, 22 May 2015 at 01:52:30 UTC, Dennis Ritchie wrote:
off the top of my head, the last one can easily be done with 
std.range.stride


import std.stdio, std.range;

void main()
{
   int[] a = [ 1, 2, 3, 4, 5, 6 ];

   writeln(stride(a, 2)); // [1, 3, 5] #odd #print(x[::2]) #OK
   // [2, 4, 6] #even #print(x[1::2]) #no equivalent in D

writeln(stride(a[1..$], 2));


   auto x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
   // [2, 6, 10] #print(x[1::4]) #no equivalent in D

writeln(stride(a[1..$], 4));

}


Yes, this is what you need (I often forget that the functions can 
take ranges in D).


Maybe somewhere and nested loops "for" to fill the arrays lying 
around :)


Re: Python's features, which requires D

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

On Friday, 22 May 2015 at 01:17:17 UTC, weaselcat wrote:
D doesn't have list comprehensions, so it's difficult to 
directly port these.


I can not imagine how difficult it is to implement it in D, but 
I'm pretty sure that nested for loops to fill arrays (in D, you 
can call them differently, for example, force :)) will be very 
useful thing, because Python is a veryIt is often used.
Besides, I do not understand what could be the problem with 
nested loops in arrays, because std.algorithm.map works on the 
principle of nested loops. I think that the biggest problem in 
the implementation of this should not be. Excuse me if I'm wrong.


off the top of my head, the last one can easily be done with 
std.range.stride


import std.stdio, std.range;

void main()
{
int[] a = [ 1, 2, 3, 4, 5, 6 ];

writeln(stride(a, 2)); // [1, 3, 5] #odd #print(x[::2]) #OK
// [2, 4, 6] #even #print(x[1::2]) #no equivalent in D

auto x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
// [2, 6, 10] #print(x[1::4]) #no equivalent in D
}


Python's features, which requires D

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,
I've collected some of Python's features. It seems to me that 
they are not in the D!


Surely all this is in the D? :)
http://rextester.com/CNQQR


Re: Dual conditions in D and Python

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

On Thursday, 21 May 2015 at 21:35:22 UTC, Ali Çehreli wrote:

We're almost there. :)

bool is_between(T0, T1, T2)(T0 what, T1 min, T2 max)
{
return (what >= min) && (what <= max);
}

void main()
{
if (5.is_between(4, 6)) {
// ...
}
}

Ali


A condition is that if, for example, that? :)

if (5 > 2 > -9 > -13 < 10 == 10 < 21 != 45):
print("OK")
-
http://rextester.com/JSC75231

import std.stdio;

void main()
{
if (5 > 2 &&
2 > -9 &&
-9 > -13 &&
-13 < 10 &&
10 == 10 &&
10 < 21 &&
21 != 45)
writeln("OK");
}
-
http://rextester.com/AZFL70044


Re: Dual conditions in D and Python

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

Something I sometimes do for strictly personal projects:

import std.typecons : ω = tuple;
import std.typetuple : Ω = TypeTuple;

void main()
{
auto a = 1, b = 2;
Ω!(a, b) = ω(b, a);
assert(a==2 && b==1);
}


On Thursday, 21 May 2015 at 19:05:16 UTC, Steven Schveighoffer 
wrote:

On 5/21/15 12:57 PM, Dennis Ritchie wrote:

Hi,
In Python I can write this:

if (4 <= 5 <= 6):
print ("OK")
-
http://rextester.com/NNAM70713

In D, I can only write this:

import std.stdio;

void main() {

if (4 <= 5 && 5 <= 6)
puts("OK");
}
-
http://rextester.com/FICP83173

I wanted to ask what is the reason? Maybe the program on 
Python's slower

because of this? Or legacy C/C++ affected D?



There is this possibility:

switch(5){
   case 4: .. case 6:
}

You could also make some nifty abuse-of-syntax types:

struct Between(T)
{
   T low;
   T high;
   bool opBinaryRight!(op : "in")(T val) { return val >= low && 
val <= high;}

}

auto between(T)(T low, T high) { return Between!T(low, high); }

if(5 in between(4, 6))

:)

-Steve


All this, of course, looks good, but what about the principle of 
the ideal programming language :)


"In the end I want to focus on one philosophical principle, which 
lies at the basis of my ideas about the ideal programming 
language. Typically, during the discussion in the forums, when 
you start to talk in a language that is not X features Y, be sure 
there is someone who will say: Why, that's if you take the 
features A, B and C, and screw them crutches D, E, F, then we 
will get almost Y. Yes, it is. But I do not like this approach. 
One can imagine that such programmers want some complicated way 
through the maze. You can go through the maze, but the way the 
curve and non-obvious. I also want to be instead of the labyrinth 
has a large area, on which from any point to any other one would 
go in a straight line. Just a straight line."

-
The quotation is taken from the article:
http://habrahabr.ru/post/257875/


Re: Dual conditions in D and Python

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

On Thursday, 21 May 2015 at 17:43:25 UTC, Jonathan M Davis wrote:
No C-based language allows what python does, and based on 
operators work in
C-based languages, what python is doing simply doesn't fit or 
make sense.
What happens in C/C++/D/Java/C#/etc. land is that 4 <= 5 
results in a bool,
at which point you'd end up with a comparison between that bool 
and 6, which
is _not_ something that you want. But with other operators _is_ 
very much
what you'd want. Operator chaining works in the same way across 
all
operators in C-based languages, and trying to make 4 <= 5 <= 6 
be equivalent
to 4 <= 5 && 5 <= 6 would make it so that they weren't 
consistent. And it
wouldn't make the language any more powerful, because you can 
quite easily
just do 4 <= 5 && 5 <= 6 instead of 4 <= 5 <= 6. It only costs 
you a few
characters and results in the language being far more 
consistent. I'm
honestly quite surprised that python would allow such a thing, 
but they seem
to do a lot of stuff that most programmers from C-based 
languages

(especially C++) would think is crazy.

- Jonathan M Davis


Yes, of course, some of Python's design for C ++ - programmers 
will look crazy, but they are worth it :)


elif instead of else if:
http://rextester.com/WOSH30608

The parallel exchange values:
http://rextester.com/TPUD51604


Re: Dual conditions in D and Python

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

On Thursday, 21 May 2015 at 17:17:29 UTC, Alex Parrill wrote:

http://wiki.dlang.org/Language_Designs_Explained#Why_does_D_not_support_chaining_comparison_operators.3F


Backward compatibility with C is nice but on the other hand it is 
a road to nowhere!
Because of this compatibility, I'm compelled to write return 
instead of ret and else if instead of elif :)
I think to create a truly correct C++, it was necessary to 
completely abandon the backward compatibility with C.


Dual conditions in D and Python

2015-05-21 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,
In Python I can write this:

if (4 <= 5 <= 6):
print ("OK")
-
http://rextester.com/NNAM70713

In D, I can only write this:

import std.stdio;

void main() {

if (4 <= 5 && 5 <= 6)
puts("OK");
}
-
http://rextester.com/FICP83173

I wanted to ask what is the reason? Maybe the program on Python's 
slower because of this? Or legacy C/C++ affected D?


Re: The analogue of "fill-pointer" in D

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn
On Monday, 18 May 2015 at 17:14:46 UTC, Steven Schveighoffer 
wrote:
capacity is analogous to the number of elements in the vector 
(as returned by array-dimension according to 
https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node162.html).


arr.length is analogous to the fill pointer.

example:

int[] arr = new int[](5);
assert(arr.capacity > 5);
assert(arr.length == 5);

arr.reserve(100); // expand arr memory block to be able to hold 
*at least* 100 ints


assert(arr.capacity >= 100);
assert(arr.length == 5);

auto ptr = arr.ptr; // for later assert

arr ~= 1; // increment length by 1, 'fill in' tail of array 
with '1'


// this should demonstrate how it works
assert(arr.length == 6); // new fill pointer
assert(arr.capacity >= 100); // capacity unchanged
assert(arr.ptr is ptr); // array still lives in same memory 
block


Apologies for not translating to lisp, I don't know it.

-Steve


Thank you. This is what you need!


Re: How to create a mutable array of strings?

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn
On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer 
wrote:

It's annoying to have to dup each one.


Yes, it's really annoying. However, the problem can be solved as 
follows:

http://forum.dlang.org/thread/owxweucyzjwugpjwh...@forum.dlang.org?page=2#post-cqjevoldkqdkmdbenkul:40forum.dlang.org

On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer 
wrote:

But, you do have a couple other possibilities:

auto s = ["foo".dup, "bar".dup];

import std.algorithm : map;
import std.array : array;
auto s = map!(a => a.dup)(["foo", "bar"]).array; // this will 
needlessly allocate an array for the strings


Now imagine that you have a multi-dimensional array of strings. 
This will not work:


auto s = map!(a => a.dup)([["foo", "baz"], ["bar", 
"test"]]).array;


You have to apply to each line .dup :)

auto s = [["foo".dup, "baz".dup], ["bar".dup, "test".dup]];
s[1][0][1] = 't';

On Monday, 18 May 2015 at 13:14:38 UTC, Steven Schveighoffer 
wrote:
But really, a string is immutable. There's not a way around 
that. A string is the most basic level of array primitive, not 
even mutable arrays of non-char types have that, and it's an 
annoyance. From there, you have to build the data out of ROM 
into the heap.


Thank you. I do not know.
And yet, the problem is easily solved. You just have to add 
.deepDup Phobos:

http://forum.dlang.org/thread/owxweucyzjwugpjwh...@forum.dlang.org?page=2#post-cqjevoldkqdkmdbenkul:40forum.dlang.org


Re: The analogue of "fill-pointer" in D

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 18 May 2015 at 12:49:56 UTC, Kagamin wrote:
Filling a buffer is usually done this way: 
http://dlang.org/phobos/std_stdio.html#.File.rawRead


Here such example, the task. There is a flow stream, associated, 
for example, with any socket. It wrote several bytes at a time. 
To once again not to pull the socket, we start buffer as an array 
with Phill-pointer. Adding byte array - using the vector-push. 
When the buffer is stuffed, dump it into the stream and moves 
pointer to zero. How to do it with the help of readRaw or there 
writeRaw?


Re: How to create a mutable array of strings?

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn
On Monday, 18 May 2015 at 14:43:33 UTC, Steven Schveighoffer 
wrote:

Right, you'd apply the map/array combo to each element:


Yes, I knew it.


alias m = map!(a => a.dup); // too bad can't do array as well

auto s = [m(["foo", "baz"]).array, m(["bar", "test"]).array];

Or to get even more crazy:

auto s = map!(a => map!(a => a.dup)(a).array)(/* your input 
array */).array;


Imagine a five-dimensional array will be :)

But this means you are duping more of the array literal than 
you really should.


It's likely helpful to have somewhere in std.array a dupArray 
function that does map!(a => a.dup).array work in one go (and 
without making a temporary array):


auto s = [dupArray("foo", "baz"), dupArray("bar", "test")];


Yes, it would be nice. I believe that Phobos need such function.

deepDup would dup the whole thing. All you need to dup is the 
string literals, as array literals constructed at runtime are 
on the heap (and mutable) already. The literal already is 
wasted even in my original suggestion, but this is doubly 
wasteful.


Right.


Re: The analogue of "fill-pointer" in D

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn

On Monday, 18 May 2015 at 10:14:33 UTC, Kagamin wrote:

On Monday, 18 May 2015 at 08:21:38 UTC, Dennis Ritchie wrote:

Hi,

In Common Lisp, there is such a thing as a fill-pointer 
(Example 5):

http://www.tutorialspoint.com/lisp/lisp_arrays.htm

Does D some equivalent?


Data stored in the array is indicated by the array length 
property, use capacity to figure out extra available space: 
http://dlang.org/phobos/object.html#.capacity


No, afraid not. Function capacity is not an analogue of 
fill-pointers!


Lisp-programmer explains the usefulness of fill-pointers as 
follows:


"Fill pointer "cuts" the tail of the vector. For example, vector 
elements 100, but if you set the fill pointer equal to 3, the 
length of the array (returned by length) will be equal to 3. The 
remaining elements are not visible.


It seems to be nonsense. But this is nonsense, ideal for buffers. 
If the buffer is implemented as an array, then fill pointer just 
marks the boundary of the filled part of the buffer, and adding a 
buffer (moving away from the fill pointer-a) is carried out using 
the vector-push. Or a buffer can be filled with the format-a. If 
you work with the same buffer C, fill pointer simulates a pointer 
to the last completed item."


The analogue of "fill-pointer" in D

2015-05-18 Thread Dennis Ritchie via Digitalmars-d-learn

Hi,

In Common Lisp, there is such a thing as a fill-pointer (Example 
5):

http://www.tutorialspoint.com/lisp/lisp_arrays.htm

Does D some equivalent?


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 10:05:34 UTC, Daniel Kozak wrote:

Ouch ignore this one :D


Yes, it will not work with multidimensional arrays :)


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 09:37:56 UTC, Daniel Kozak wrote:

So maybe this one would be ok with you too :)

auto s = to!(char[][])(["foo", "bar"]);


Now it works :)


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 09:36:33 UTC, anonymous wrote:

On Sunday, 17 May 2015 at 09:26:15 UTC, Dennis Ritchie wrote:

And no crashes on Windows :)


Yeah, on windows it's even worse.

void main()
{
auto s = cast(char[][])["foo", "bar"];
s[1][1] = 't';
import std.stdio;
writeln("bar");
}


Yes exactly.


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

I remembered code Ali Çereli. It really helped:
http://forum.dlang.org/thread/ulhtlyxxclihaseef...@forum.dlang.org#post-mihl6m:241che:241:40digitalmars.com

-
import std.stdio, std.traits, std.range, std.algorithm;

auto deepDup(A)(A arr)
if (isArray!A)
{
static if (isArray!(ElementType!A)) {
return arr.map!(a => a.deepDup).array;

} else {
return arr.dup;
}
}

void main() {

auto s = ["foo", "bar"].deepDup;

s[1][1] = 't';

writeln(s);
}
-
http://rextester.com/QBFH12695

P.S. Need to enable deepDup in Phobos.


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 09:24:19 UTC, anonymous wrote:

On Sunday, 17 May 2015 at 09:20:17 UTC, Dennis Ritchie wrote:

On Sunday, 17 May 2015 at 09:18:15 UTC, Daniel Kozak wrote:

auto s = cast(char[][])["foo", "bar"];


Thanks. This version I was completely satisfied.


Remember that Daniel Kozak wrote "if you are sure thats what 
you really need". I'm confident that you're not sure it's what 
you need. For starters, this crashes on linux:



auto s = cast(char[][])["foo", "bar"];
s[1][1] = 't';



And no crashes on Windows :)


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 09:18:15 UTC, Daniel Kozak wrote:

auto s = cast(char[][])["foo", "bar"];


Thanks. This version I was completely satisfied.


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

This option is also a strange:

char[][] s = ["foo".dup, "bar".dup];
s[1][1] = 't';

In my opinion, you need to add to D keyword mutable.


Re: How to create a mutable array of strings?

2015-05-17 Thread Dennis Ritchie via Digitalmars-d-learn

On Sunday, 17 May 2015 at 09:06:40 UTC, Dennis Ritchie wrote:

Hi,
It seems to me, or D do not create mutable array of strings?

How to create a mutable equivalent of a string array?

-
string[] s = ["foo", "bar"];
// s[1][1] = 't'; // immutable expression s[1][1]


It's uncomfortable:
-
char[][] s = [['f', 'o', 'o'], ['b', 'a', 'r']];
s[1][1] = 't';


  1   2   3   >