Completing C code with D style

forkit forkit at gmail.com
Mon Nov 8 12:04:26 UTC 2021


On Tuesday, 2 November 2021 at 23:45:39 UTC, pascal111 wrote:
> Next code originally was a classic C code I've written, it's 
> pure vertical thinking, now, I converted it successfully to D 
> code, but I think I made no much changes to make it has more 
> horizontal thinking style that it seems D programmers care in 
> horizontal thinking style. Is there any additions I can make in 
> the code to make it suitable with D style or it's fine?
>

Oh man! some of those answers... whoooooohah....

Here's mine, with a little of that horizontal thinking ;-)

// =============================================

module test;

import std.stdio : write, writeln, writefln, readf;
import std.algorithm : filter, sort;
import std.array: array;

void main()
{
     // NOTE: 0 is neither positive or negative, but is considered 
to be even

     int[] numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26, 0];
     int[] result;

     char answer1;
     write("Would you like in list (n=negatives, p=positives, 
b=both)? ");
     readf(" %c", answer1);
     debug { writeln("You selected ", answer1); }
     switch(answer1)
     {
         case 'n' :
             result = numbers.filter!(a => (a < 0)).array;
             break;
         case 'p' :
             result = numbers.filter!(a => (a > 0)).array;
             break;
         case 'b' :
             result = numbers;
             break;
         default :
             writefln("Invalid answer." );
             throw new Exception("Bad input!!"); // don't waste my 
time!
     }


     char answer2;
     write("Would you like in list (e=evens, o=odds, b=both)? ");
     readf(" %c", answer2);
     debug { writeln("You selected ", answer2); }
     switch(answer2)
     {
         case 'e' :
             result = result.filter!(a => (a % 2 == 0)).array;
             break;
         case 'o' :
             result = result.filter!(a => (a % 2 == 1)).array;
             break;
         case 'b' :
             break;
         default :
             writefln("Invalid answer." );
         throw new Exception("Bad input!!"); // don't waste my 
time!
     }


     writeln(result.sort());

}

// =============================================



More information about the Digitalmars-d-learn mailing list