input range from stdin

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 18 11:22:00 PDT 2014


On 09/18/2014 02:21 AM, krzaq wrote:

 > That's not what I wanted. Maybe I should explain instead of expecting
 > you to divine my intentions, though :)

And quietly ignored some of the things you were doing. :)

For example, I did not think it was necessary to fill an existing array 
when the range object can produce the objects one by one lazily. If an 
actual array is needed, it is as simple as calling .array on the range.

An if the destination already exists, the array-wise operations can fill 
it anyway. So, actually fill is not needed in the original case:

     import std.array;
     import std.range;

     Data[5] existingArray;
     existingArray = data.takeExactly(5).array;

 > I am trying to rewrite the
 > following program in D--making it more elegant:
 > http://melpon.org/wandbox/permlink/ff42FoyKgqJK60sm

Here is my attempt:

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

auto secretWord(R)(R line)
{
     auto tokens = line.splitter;

     auto words = tokens
                  .takeExactly(5);

     // Question: Why do I need this?
     tokens.popFrontN(words.length);

     auto integers = tokens
                     .takeExactly(words.length)
                     .map!(to!size_t);

     return zip(words, integers).map!(t => t[0][t[1]]);
}

unittest
{
     assert(secretWord("cheap energy can cause problems 4 2 1 0 5")
            .equal("peace"));
}

void main()
{
     writeln(stdin.byLine.map!secretWord);
}

 > As you can see, I can have one input line consisting of n words and then
 > n integers and I can read from it easily. My question whether
 > stdin.byLine allows me to do this remains unanswered (or I failed to
 > understand the answer), although I am not hopeful.

byLine's purpose is to present the input line by line. Parsing the line 
should be the responsibility of something else. However, you are right 
that we don't have a generic formetted range reader yet.

There has been a number of talks about it but nobody has completed it yet.

 > I expected my D code to look more or less like the following:
 >
 > words.fill(stdin.by!string);
 > integers.fill(stdin.by!int);
 > zip(integers,words).map!(p => p[1][p[0]]).join.writeln;

I wrote my code without looking yours. :)

Ali



More information about the Digitalmars-d-learn mailing list