Chaining std.algorithm

Ali Çehreli acehreli at yahoo.com
Sun Dec 15 22:06:59 PST 2013


On 12/15/2013 09:46 PM, Ali Çehreli wrote:

 > On 12/15/2013 08:42 PM, John Carter wrote:

 >  > Now I'm sure I can use std.algorithm map to convert say a string of
 >  > characters "IVXLCDM" into an array [1,5,10,50,100,500,1000]

The following program works. Note that 'result' is a lazy range. You can 
apply .array to it to convert it to an array eagerly.

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

struct romanSystemData {
    string digit;
    uint   value;
    ulong  regionIndex;
    ulong  previous;
};

immutable romanSystemData romanSystem[] = [
    {"" ,    0, 0, 0},//0
    {"I",    1, 0, 0},//1 8-7
    {"V",    5, 1, 1},//2 8-6
    {"X",   10, 1, 2},//3 8-5
    {"L",   50, 3, 3},//4 8-4
    {"C",  100, 3, 4},//5 8-3
    {"D",  500, 5, 5},//6 8-2
    {"M", 1000, 5, 6} //7 8-1
];

void main()
{
     auto result = "IVXLCDM"
                   .map!(a => romanSystem
                              .find!(data => data.digit.equal([ a ]))
                              .front.value);

     assert(result.equal([1, 5, 10, 50, 100, 500, 1000]));
}

The following code maintains the digits as chars (instead of strings), 
which simplified the code a little bit:

immutable romanSystemData romanSystem[] = [
    {'\0',   0, 0, 0},//0      // <-- digits are char
    {'I',    1, 0, 0},//1 8-7
    // ...
];

Simpler than data.digit.equal([ a ]):

     auto result = "IVXLCDM"
                   .map!(a => romanSystem
                              .find!(data => data.digit == a)
                              .front.value);

Ali



More information about the Digitalmars-d-learn mailing list