Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default String conversion method in Chapel?

Tags:

chapel

Is there a default method that gets called when I try to cast an object into a string? (E.g. toString in Java or __str__ in Python.) I want to be able to do the following with an array of Objects, but some of them might be nil:

for item in array {
    writeln(item : string);
}
like image 620
Kyle Avatar asked Jul 30 '26 06:07

Kyle


1 Answers

First of all, casting nil to string isn't necessarily a problem:

class C {
  var x:int;
}

var array = [ new C(1), nil:C, new C(2) ];

for item in array {
  writeln( item : string ); 
}

outputs

{x = 1}
nil
{x = 2}

Secondly, if you did want to customize the output of your class C, you'd write a writeThis method (or a readWriteThis method). See The readThis(), writeThis(), and readWriteThis() Methods. The writeThis method will be called both for cast to string and also for normal I/O. For example:

class C {
  var x:int;
  proc writeThis(writer) {
    writer.writef("{%010i}", x);
  }
}

var array = [ new C(1), nil:C, new C(2) ];

for item in array {
  writeln( "writing item : string  ", item : string ); 
  writeln( "writing item           ", item);
}

outputs

writing item : string  {0000000001}
writing item           {0000000001}
writing item : string  nil
writing item           nil
writing item : string  {0000000002}
writing item           {0000000002}

There is more I could say about why it works this way, what it might do in the future, and the limitations of the current strategy... but a mailing list would be a better place for such discussion if you'd like to have it.

like image 184
mppf Avatar answered Aug 02 '26 07:08

mppf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!