Jump to page: 1 25  
Page
Thread overview
Completing C code with D style
Nov 02, 2021
pascal111
Nov 03, 2021
Siarhei Siamashka
Nov 03, 2021
pascal111
Nov 03, 2021
Ali Çehreli
Nov 03, 2021
pascal111
Nov 03, 2021
pascal111
Nov 03, 2021
Stanislav Blinov
Nov 03, 2021
russhy
Nov 03, 2021
Salih Dincer
Nov 04, 2021
jfondren
Nov 06, 2021
kdevel
Nov 06, 2021
jfondren
Nov 06, 2021
kdevel
Nov 03, 2021
Ali Çehreli
Nov 08, 2021
forkit
Nov 08, 2021
forkit
Nov 09, 2021
forkit
Nov 10, 2021
Stanislav Blinov
Nov 10, 2021
forkit
Nov 10, 2021
Stanislav Blinov
Nov 10, 2021
russhy
Nov 10, 2021
H. S. Teoh
Nov 10, 2021
Ali Çehreli
Nov 10, 2021
H. S. Teoh
Nov 10, 2021
forkit
Nov 11, 2021
H. S. Teoh
Nov 11, 2021
forkit
Nov 11, 2021
H. S. Teoh
Nov 11, 2021
Stanislav Blinov
Nov 11, 2021
forkit
Nov 12, 2021
Stanislav Blinov
Nov 12, 2021
foxit
Nov 12, 2021
forkit
Nov 10, 2021
forkit
Nov 11, 2021
Stanislav Blinov
Nov 11, 2021
Ali Çehreli
Nov 12, 2021
Stanislav Blinov
Nov 12, 2021
forkit
Nov 10, 2021
forkit
Nov 11, 2021
forkit
Nov 11, 2021
kdevel
Nov 12, 2021
foxit
Nov 13, 2021
pascal111
Nov 14, 2021
forkit
Nov 16, 2021
pascal111
November 02, 2021

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?

// D programming language

import std.stdio;

int main()
{

int numbers[10]=[-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
char negativity,
      even;

write("Would you like in list (n=negatives, p=positives, b=both)? ");
readf(" %c", &negativity);

write("Would you like in list (e=evens, o=odds, b=both)? ");
readf(" %c", &even);

for(int i=0; i<10; ++i)
	{
	 if(negativity=='n')
	 	{
	 	if(numbers[i]>0)
	 		continue;
	 	}
	 else{
	  if(negativity=='p')
	  	if(numbers[i]<0)
	  		continue;
	  }
	
	  if(even=='e')
	 	{
	 	if(numbers[i]%2)
	 		continue;
	 	}
	 else{
	  if(even=='o')
	  	if(!(numbers[i]%2))
	  		continue;
	  }		
	 writefln("%d",numbers[i]);
	}
	
	
return 0;
}
November 03, 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?

By "vertical" vs. "horizontal" thinking, do you mean imperative vs. functional style?
https://en.wikipedia.org/wiki/Functional_programming#Imperative_vs._functional_programming

It's supported in many modern programming languages and it's not a unique feature of the D language alone. Your code can be changed to something like this:

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

void main()
{
  auto numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
  char negativity, even;

  write("Would you like in list (n=negatives, p=positives, b=both)? ");
  readf(" %c", &negativity);

  write("Would you like in list (e=evens, o=odds, b=both)? ");
  readf(" %c", &even);

  numbers.filter!(x => !((negativity == 'n' && x > 0) ||
                         (negativity == 'p' && x < 0)))
         .filter!(x => !((even == 'e' && (x % 2)) ||
                         (even == 'o' && !(x % 2))))
         .map!text.join("\n").writeln;
}
November 03, 2021

On Wednesday, 3 November 2021 at 00:50:51 UTC, Siarhei Siamashka wrote:

>

On Tuesday, 2 November 2021 at 23:45:39 UTC, pascal111 wrote:

>

It's supported in many modern programming languages and it's not a unique feature of the D language alone. Your code can be changed to something like this:

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

void main()
{
  auto numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
  char negativity, even;

  write("Would you like in list (n=negatives, p=positives, b=both)? ");
  readf(" %c", &negativity);

  write("Would you like in list (e=evens, o=odds, b=both)? ");
  readf(" %c", &even);

  numbers.filter!(x => !((negativity == 'n' && x > 0) ||
                         (negativity == 'p' && x < 0)))
         .filter!(x => !((even == 'e' && (x % 2)) ||
                         (even == 'o' && !(x % 2))))
         .map!text.join("\n").writeln;
}

Wow! your code seem so nice, I like it although I don't know how exactly it works. For now I'll keep learning traditional imperative programming style then after that I'll look in the functional one, it's new to me.

November 02, 2021
On 11/2/21 5:50 PM, Siarhei Siamashka wrote:
> Your code can be changed to something like this:

And I over-engineered it. :)

import std.stdio;
import std.algorithm;
import std.range;
import std.exception;
import std.format;

// A readable name; corresponds to C's typedef
alias FilterFunction = bool function(int);

// These are our filters; they will be initialized not right
// where they are defined but in a following 'shared static
// this()'. (This is a current D implementation issue.)
immutable FilterFunction[string] negativityFilters;
immutable FilterFunction[string] evennessFilters;

// 'shared static this()' blocks are executed before main()
// is executed.
shared static this() {
  const matchAll = (int _) { return true; };

  negativityFilters = [
    "negatives" : (int i) { return i <= 0; },
    "positives" : (int i) { return i >= 0; },
    "both" : matchAll,
  ];

  evennessFilters = [
    "evens" : (int i) { return (i % 2) == 0; },
    "odds" : (int i) { return (i % 2) == 1; },
    "both" : matchAll,
  ];
}

// Picks the filter that corresponds to user input
FilterFunction pickFilter(const(FilterFunction[string]) filters) {
  // The full names of filters e.g. [ "evens", "odds", "both" ]
  auto fulls = filters.byKey.array.sort;

  // The first letters of the names e.g. [ 'b', 'e', 'o' ]
  auto shorts = fulls.map!(key => key.front);

  // A mapping from short to full name e.g. 'b' -> "both"
  auto shortToFull = assocArray(shorts, fulls);

  // Prompt the user by combining the short and full names
  writef!"Would you like in list (%-(%s, %))? "(
    zip(shorts, fulls).map!(z => format!"%s=%s"(z[0], z[1])));

  char c;
  readf(" %c", &c);
  enforce(c in shortToFull, format!"'%s' is not a valid option"(c));

  const full = shortToFull[c];
  return filters[full];
}

// Picks filters according to user input
FilterFunction[] pickFilters() {
  return [ negativityFilters, evennessFilters ].map!pickFilter.array;
}

// The main logic of the program
void run() {
  auto numbers = [ -3, 14, 47, -49, -30, 15, 4, -82, 99, 26 ];

  auto filters = pickFilters();
  auto selection = numbers.filter!(n => filters.all!(f => f(n)));

  writefln!"%-(%s\n%)"(selection);
}

int main() {
  try {
    run();
    return 0;

  } catch (Exception e) {
    stderr.writefln!"ERROR: %s"(e.msg);
    return 1;
  }
}

Ali
November 03, 2021

On Wednesday, 3 November 2021 at 00:50:51 UTC, Siarhei Siamashka wrote:

>

On Tuesday, 2 November 2021 at 23:45:39 UTC, pascal111 wrote:

>

By "vertical" vs. "horizontal" thinking, do you mean imperative vs. functional style?
https://en.wikipedia.org/wiki/Functional_programming#Imperative_vs._functional_programming

Maybe you are right, I think that, but I don't know the exact English terms.

November 03, 2021
On Wednesday, 3 November 2021 at 00:57:38 UTC, Ali Çehreli wrote:
> On 11/2/21 5:50 PM, Siarhei Siamashka wrote:
>> Your code can be changed to something like this:
>
> And I over-engineered it. :)
>
> import std.stdio;
> import std.algorithm;
> import std.range;
> import std.exception;
> import std.format;
.
.
.
> Ali

I think I costed you much efforts. Thank you, it's a great version.

November 03, 2021

On Wednesday, 3 November 2021 at 00:50:51 UTC, Siarhei Siamashka wrote:

>
!text.join("\n").writeln;

Ahem... You've turned a program that does not allocate to a program that allocates who knows how much memory?

And Ali... associative arrays? For this? What are you trying to teach the good beginner here? :D

import std.stdio, std.algorithm;

void main()
{
  auto numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
  char negativity, even;

  write("Would you like in list (n=negatives, p=positives, b=both)? ");
  readf(" %c", &negativity);

  write("Would you like in list (e=evens, o=odds, b=both)? ");
  readf(" %c", &even);

  if ((negativity == 'b') && (even == 'b'))
  {
      // don't do any unnecessary work
      numbers.each!writeln;
  }
  else
  {
      numbers.filter!(x => !((negativity == 'n' && x > 0) ||
                             (negativity == 'p' && x < 0)))
             .filter!(x => !((even == 'e' && (x % 2)) ||
                             (even == 'o' && !(x % 2))))
             .each!writeln;
  }
}
November 03, 2021

The code "as is" is perfectly fine

I don't understand why you guys offer OP such complicate/bloated examples, it'll only make things confusing and slow down compilation time with templates and imports, this is not needed at all

One change, use .length property instead of the hardcoded value

Keeping things simple helps debugging!

int main() {

  int numbers[10] = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
  char negativity, even;
  write("Would you like in list (n=negatives, p=positives, b=both)? ");
  readf(" %c", & negativity);

  write("Would you like in list (e=evens, o=odds, b=both)? ");
  readf(" %c", & even);

  // you can access .length property of slices/arrays/static_arrays in D
  for (int i = 0; i < numbers.length; ++i) {
    if (negativity == 'n') {
      if (numbers[i] > 0)
        continue;
    } else {
      if (negativity == 'p')
        if (numbers[i] < 0)
          continue;
    }

    if (even == 'e') {
      if (numbers[i] % 2)
        continue;
    } else {
      if (even == 'o')
        if (!(numbers[i] % 2))
          continue;
    }
    writefln("%d", numbers[i]);
  }

  return 0;
}
November 03, 2021

On Wednesday, 3 November 2021 at 20:36:08 UTC, russhy wrote:

>

I don't understand why you guys offer OP such complicate/bloated examples, it'll only make things confusing and slow down compilation time with templates and imports, this is not needed at all

I don't like complicated things either. Additional facilities are interminable in D :)

For example:

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

int main() {
	auto numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
	char negativity, even;

Start:
	bool error;

 	enum sign { negatives = 'n', positives = 'p', both = 'b' }
	write("Would you like in list (n=negatives, p=positives, b=both)? ");
	readf(" %c", &negativity);

	switch (negativity) with(sign) {
		case negatives:
			numbers = filter!("a < 0")(numbers).array;
			break;
		case positives:
			numbers = filter!("a > 0")(numbers).array;
			break;
		case both:
		break;
		default:
			error = true;
			goto Error;
	}
	
	enum type { evens = 'e', odds = 'o', both = 'b' }
	write("Would you like in list (e=evens, o=odds, b=both)? ");
	readf(" %c", &even);

	switch (even) with(type) {
		case evens:
			numbers = filter!("!(a % 2)")(numbers).array;
			break;
		case odds:
			numbers = filter!("a & 1")(numbers).array;
			break;
		case both:
		break;
		default:
			error = true;
	}

Error:
	if(error) {
		"Error...".writeln;
		goto Start;
	} else writef("%(%s\n%)", numbers);

	return 0;
}

Please try to use auto...

November 03, 2021
On 11/3/21 11:41 AM, Stanislav Blinov wrote:

> And Ali... associative arrays? For this? What are you trying to teach
> the good beginner here? :D

Obviously, we're all enjoying this thread but once the OP made it clear that they wanted a C-like solution, I took some liberty with alternative solutions. :)

I think even in production code I would implement something similar at least to keep selection characters like 'n' together with their long forms like "negative".

I might use linear searching instead of an assoiative array (or store the assoiative arrays for later use, which I did think about before posting it). But, considering they are generated when interacting with stdin, likely fed by a human, the time loss there is zero. :)

Ali

« First   ‹ Prev
1 2 3 4 5