Recent

Author Topic: Automatic conversion to string  (Read 1254 times)

Curt Carpenter

  • Hero Member
  • *****
  • Posts: 598
Automatic conversion to string
« on: February 01, 2025, 10:32:14 pm »
Suppose I have a number of values v1,v2,...,vN that I want to format into a string S -- say a comma-separated string.  I can do this  in many cases like this:

Code: Pascal  [Select][+][-]
  1.     S := v1.ToString+','+v2.ToString+','+...+','+vN.ToString;

How hard would it be though to make the compiler, knowing that S is a string variable on the left of the assignment, automatically try to ensure that everything on the right (v1,v2,...,vN) is converted into string form, or issue an exception if such a conversion were not possible?

Not advocating for this, just curious what the downside would be to having the compiler do such a thing.

Wilko500

  • Full Member
  • ***
  • Posts: 125
Re: Automatic conversion to string
« Reply #1 on: February 01, 2025, 10:46:06 pm »
I don't have the answer but I have often wondered why ShowMessage can only take strings but WriteLn can take strings and integers and do thenevessary conversions.
MacBook Pro mid 2015 with OS Monterey 12.7.6
FPC 3.2.3 Lazarus 3.7
FPC 3.2.2 Lazarus 3.4

TRon

  • Hero Member
  • *****
  • Posts: 4003
Re: Automatic conversion to string
« Reply #2 on: February 01, 2025, 11:02:42 pm »
Use WriteStr or Format otherwise you would have to dig into operator overloading (in case possible).

I don't have the answer but I have often wondered why ShowMessage can only take strings but WriteLn can take strings and integers and do thenevessary conversions.
Because Write is an internal compiler function.
« Last Edit: February 01, 2025, 11:38:19 pm by TRon »
I do not have to remember anything anymore thanks to total-recall.

dseligo

  • Hero Member
  • *****
  • Posts: 1462
Re: Automatic conversion to string
« Reply #3 on: February 01, 2025, 11:06:58 pm »
Suppose I have a number of values v1,v2,...,vN that I want to format into a string S -- say a comma-separated string.  I can do this  in many cases like this:

Code: Pascal  [Select][+][-]
  1.     S := v1.ToString+','+v2.ToString+','+...+','+vN.ToString;

How hard would it be though to make the compiler, knowing that S is a string variable on the left of the assignment, automatically try to ensure that everything on the right (v1,v2,...,vN) is converted into string form, or issue an exception if such a conversion were not possible?

Not advocating for this, just curious what the downside would be to having the compiler do such a thing.

Maybe you can use WriteStr (https://www.freepascal.org/docs-html/rtl/system/writestr.html).

TBMan

  • Jr. Member
  • **
  • Posts: 50
Re: Automatic conversion to string
« Reply #4 on: February 02, 2025, 02:27:54 am »
The writestr looks interesting. I'm old school and I should look into the newer stuff. That beats doing a series of str() and using multiple variables to make one string.

egsuh

  • Hero Member
  • *****
  • Posts: 1534
Re: Automatic conversion to string
« Reply #5 on: February 02, 2025, 09:49:28 am »
Well, Pascal is type-strict language. I have written following function, and this works.


Code: Pascal  [Select][+][-]
  1. function CommaStr(Args: array of const): string;
  2. var
  3.    arg: TVarRec;
  4. begin
  5.    Result := '';
  6.    for arg in Args do begin
  7.       case arg.VType of
  8.          vtInteger: Result += IntToStr(arg.VInteger);
  9.          vtString: Result += arg.VString^;
  10.          vtAnsiString: Result += string(arg.VAnsiString);
  11.       end;
  12.       Result += ',';
  13.    end;
  14.    RemovePadChars(Result, [',']);
  15. end;
             

paweld

  • Hero Member
  • *****
  • Posts: 1298
Re: Automatic conversion to string
« Reply #6 on: February 02, 2025, 10:04:18 am »
Code: Pascal  [Select][+][-]
  1. S := Format('%d,%d,...,%d', [v1, v2, ..., vN]);
more info: https://lazarus-ccr.sourceforge.io/docs/rtl/sysutils/format.html
Best regards / Pozdrawiam
paweld

Thaddy

  • Hero Member
  • *****
  • Posts: 16580
  • Kallstadt seems a good place to evict Trump to.
Re: Automatic conversion to string
« Reply #7 on: February 02, 2025, 11:43:56 am »
The writestr looks interesting. I'm old school and I should look into the newer stuff. That beats doing a series of str() and using multiple variables to make one string.
yes, writestr is often a good option:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2. var
  3.    V1:double = 12.34;
  4.    V2:integer = 10; // optionally formats with a double':'
  5.    V3:string = 'Hello';  // optionally formats length with a single ':'
  6.    S:string;
  7. begin
  8.    writestr(S, V1:4:4,V2:4, V3:6);
  9.    writeln(s);
  10. end.
It has some limitations over the formatxxx functions, but it does not need sysutils.
Errror checking can best be done in {$I-} state and examining IOResult.
Writestr is not new - actually very old - but was only specified in the ISO Extended Pascal standard. In Freepascal it is available in all modes.
 
« Last Edit: February 02, 2025, 11:48:15 am by Thaddy »
But I am sure they don't want the Trumps back...

Curt Carpenter

  • Hero Member
  • *****
  • Posts: 598
Re: Automatic conversion to string
« Reply #8 on: February 02, 2025, 04:06:12 pm »
Appreciate all the approaches, but my curiosity was really about why the compiler couldn't do the conversion of the elements on the right of the assignment .ToString  automatically (or throw an exception if one of the elements is not convertable).  Strictly curiosity -- suspect there's a problem with the idea.

Thaddy

  • Hero Member
  • *****
  • Posts: 16580
  • Kallstadt seems a good place to evict Trump to.
Re: Automatic conversion to string
« Reply #9 on: February 02, 2025, 04:23:47 pm »
Well, the compiler can, or better the rtl can.
You just need to include the sysutils unit for a wealth of conversions.
Note that from a compiler point of view, you can not expect type inference for everything, but there are some tricks in fpc - not delphi - that I will add here later.
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2. uses
  3.   sysutils;
  4. // assign a string to an integer. string must be valid integer representation
  5. operator := (const b:string):integer;inline;
  6. begin
  7.   result := b.tointeger;
  8. end;
  9.  
  10. // assign an integer to a string
  11. operator := (const b:integer):string;inline;
  12. begin
  13.   result := b.tostring;
  14. end;
  15.  
  16. begin
  17.   writeln('100'.ToInteger);
  18.   writeln(100.ToString);
  19. end.
As long as the string can be represented as an integer it becomes an integer on assignment
The integer will be simply represented as a string on assignment.

This can be done for almost all and any types.

So, yes, as the example proves, Freepascal supports type inference, but not all conversions are out of the box. You have to put in some work for now.
« Last Edit: February 02, 2025, 06:10:06 pm by Thaddy »
But I am sure they don't want the Trumps back...

PascalDragon

  • Hero Member
  • *****
  • Posts: 5870
  • Compiler Developer
Re: Automatic conversion to string
« Reply #10 on: February 02, 2025, 08:42:21 pm »
How hard would it be though to make the compiler, knowing that S is a string variable on the left of the assignment, automatically try to ensure that everything on the right (v1,v2,...,vN) is converted into string form, or issue an exception if such a conversion were not possible?

The result of an expression in Pascal does NOT depend on what its assigned to. Unless you have a single element assignment which results in the invocation of an assignment operator or the assignment of an overloaded method/function to a method/function variable the right side of an assignment has no knowledge about what the left side.

You can only do this by using a "seed element" (which triggers a conversion to the correct type while parsing from left to right) and assigment and addition operator overloads:

Code: Pascal  [Select][+][-]
  1. program topovld;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   SysUtils;
  7.  
  8. operator := (aArg: LongInt): String;
  9. begin
  10.   Result := IntToStr(aArg);
  11. end;
  12.  
  13. operator + (const aLeft: String; aRight: LongInt): String;
  14. begin
  15.   Result := aLeft + ' ' + IntToStr(aRight);
  16. end;
  17.  
  18. var
  19.   s: String;
  20.   v1, v2, v3: LongInt;
  21. begin
  22.   v1 := 42;
  23.   v2 := 21;
  24.   v3 := 84;
  25.  
  26.   s := '' + v1 + v2 + v3;
  27.   Writeln(s);
  28. end.

n7800

  • Full Member
  • ***
  • Posts: 238
Re: Automatic conversion to string
« Reply #11 on: February 02, 2025, 09:23:54 pm »
It is worth remembering that Format and WriteStr calls are very slow, since they perform parameter parsing.

So calling Str directly (which is called by IntToStr (which is called by Integer.ToString)) will be the fastest:
Code: Pascal  [Select][+][-]
  1. Function TORDINALHELPER.ToString: string; overload; inline;
  2. begin
  3.   Result:=IntToStr(Self);
  4. end;
  5. ...
  6. function IntToStr(Value: QWord): string;
  7. begin
  8.   System.Str(Value, result);
  9. end ;
  10.  

This is very noticeable if you generate, for example, a large CSV file.

Curt Carpenter

  • Hero Member
  • *****
  • Posts: 598
Re: Automatic conversion to string
« Reply #12 on: February 02, 2025, 11:08:59 pm »
The result of an expression in Pascal does NOT depend on what its assigned to.

I understand "does not" but wonder if there is good reasons why it "could not" or "should not."   Just curious.  I am imagining a "compiler" that, rather than telling me I've made an error and inviting me to correct it, might ask me what I meant in certain circumstances, as in assigning a number to a string. 





PascalDragon

  • Hero Member
  • *****
  • Posts: 5870
  • Compiler Developer
Re: Automatic conversion to string
« Reply #13 on: February 04, 2025, 10:08:03 pm »
The result of an expression in Pascal does NOT depend on what its assigned to.

I understand "does not" but wonder if there is good reasons why it "could not" or "should not."

Because then it's not Pascal.

 

TinyPortal © 2005-2018