Modern For Loop question lazarus / 61-Beginners ---------------------------------------------------------------------- Peter H · 2021-01-25 21:47 Shouldnt this compile? I get "illegal assignement" at line 14 (FPC 3.3.1) Ok, I am aware, I did something wrong probably, but I dont know, how to do it right. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure MultiThread(FromIndex, ToIndex: Integer; Proc: DoProcProcedure; ThreadCount: Integer = 8);var  Workers: array of TMyWorkerThread;  I: integer;  t: TMyWorkerThread;  begin  SetLength(Workers, ThreadCount);  CurrentIndex := FromIndex;  MaxIndex := ToIndex; // for I := 0 to ThreadCount - 1 do //      Workers[I] := TMyWorkerThread.Create(Proc);  for t in workers do       t := t.Create(Proc);   // <-- Error: illegal assignement  while CurrentIndex < MaxIndex do    sleep(100); end; ---------------------------------------------------------------------- Kays · 2021-01-25 22:00 Quote from: Peter H on January 25, 2021, 10:47:05 pm[…] Ok, I am aware, I did something wrong probably, but I dont know, how to do it right. […]The iterator variable is immutable, thus it cannot appear on the LHS of an assignment. The code above you commented out looks alright though. Slight improvement: Use high for the upper limit. ---------------------------------------------------------------------- Peter H · 2021-01-25 22:05 Yes, the commented code is alright. I wanted to write this more modern and elegant. My thought was: t is not an iterator, it is what an immutable hidden iterator points to, therefore I can modify it. Possibly I understand this wrong. ---------------------------------------------------------------------- howardpc · 2021-01-25 22:06 for x in somearray do is syntax sugar, and you have to regard the loop variable x as read- only from the programmer's point of view. As Kays writes, the classic syntax gives you more flexibility, though it is slightly more verbose. ---------------------------------------------------------------------- Peter H · 2021-01-25 22:16 Quote from: howardpc on January 25, 2021, 11:06:41 pmfor x in somearray do is syntax sugar, and you have to regard the loop variable x as read- only from the programmer's point of view. As Kays writes, the classic syntax gives you more flexibility, though it is slightly more verbose. Some say, it is sugar, others say, it is less fat, less writing means better readable and better maintenance and less errors.  It shouldnt be necessary to tell something to the compiler, when it already knows it. This is nothing to discuss. BTW, I have your book, it is excellent, no offence please. ---------------------------------------------------------------------- Peter H · 2021-01-25 22:27 I got now this, it compiles, but doesnt work at runtime: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure MultiThread(FromIndex, ToIndex: Integer; Proc: DoProcProcedure; ThreadCount: Integer = 8);var  Workers: array of TMyWorkerThread;  I: integer;  t: ^TMyWorkerThread;  begin  SetLength(Workers, ThreadCount);  CurrentIndex := FromIndex;  MaxIndex := ToIndex; // for I := 0 to ThreadCount - 1 do //      Workers[I] := TMyWorkerThread.Create(Proc);  for t^ in workers do      t^ := t^.Create(Proc);    while CurrentIndex < MaxIndex do    sleep(100); end; ---------------------------------------------------------------------- Peter H · 2021-01-25 23:15 This compiles AND works: Edit: If i initialyze "t" to Nil, it throws an exception. It doesnt work. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure MultiThread(FromIndex, ToIndex: Integer; Proc: DoProcProcedure; ThreadCount: Integer = 8);var  Workers: array of TMyWorkerThread;  I: integer;  t: ^TMyWorkerThread = Nil;  begin  SetLength(Workers, ThreadCount);  CurrentIndex := FromIndex;  MaxIndex := ToIndex; // for I := 0 to ThreadCount - 1 do //      Workers[I] := TMyWorkerThread.Create(Proc);  for t^ in workers do      t^ := TMyWorkerThread.Create(Proc);  while CurrentIndex < MaxIndex do    sleep(100); end; ---------------------------------------------------------------------- Kays · 2021-01-25 23:26 Quote from: Peter H on January 25, 2021, 11:05:43 pm[…] I wanted to write this more modern and elegant. […]You cannot use for … in … do for that. The problem is the loop body receives a copy of the array member’s value. In the loop body, the collection (the array) you specified between in … do, is not touched again. Only by using a for … to … do loop and writing myArray[myCountingVariable] you actually have access to the array and can manipulate it, its contents. Quote from: Peter H on January 26, 2021, 12:15:37 amThis compiles AND works:Yeah, OK, handling pointers to pointers. That’ll just circumvent the immutability requirement (as far as the compiler can detect it). What’s the gain, the advantage though? Frankly, it’s nice that it works, but I’d probably opt for the more intuitive/readable solution. ---------------------------------------------------------------------- Peter H · 2021-01-26 00:18 Yes, you are right. If I initialize t like this:  var  t: ^TMyWorkerThread = Nil ,then I get an exception with both compiling examples. It was an accident, that example no. 3 did work, now it throws an exception. None of all these examples work. ---------------------------------------------------------------------- PascalDragon · 2021-01-26 08:17 Don't abuse the for … in … loop for something that it isn't intended for. Consider the loop variable as immutable. Period. Even if you should find a way that works for you now there is no guarantee that this will work in future versions or with improved optimizations. ---------------------------------------------------------------------- Peter H · 2021-01-26 08:26 Now I did not want to abuse it, I wanted to use it. But obviously I had a misunderstanding about it. I think I must have some educational reading how to use it. What would you recommend? I have 4 paid books about lazarus/freepascal, but none explains it in depth, e.g. "Getting started with Lazarus and Free Pascal" by "Menkaura Abiola-Ellison" has only a very short example how to process lists. ---------------------------------------------------------------------- egsuh · 2021-01-26 08:37 It seems that for...in AnArray returns the constant (as Kays already told), not variable, while AnArray[Index] is actually a pointer of a variable, which you can store values. ---------------------------------------------------------------------- kupferstecher · 2021-01-26 11:40 There were discussions about it before. I think the for..in construct is very useful to avoid boundary-mistakes. But because its not usable in the case you showed, and thats a frequent case, the usecases are too rare to consequently use it. And I don't like changing the complete loop structure, just because something in the inner of the loop changed. An assignable iterator should be allowed, imo. I understand, that the problem is the iterator implementation and not the loop implementation itself, that could be changed. And a construct like the below would be very helpful for save programming (Feature request ;-) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i for ii with someElement in SomeArraydo someElement.index:= ii; ---------------------------------------------------------------------- ASBzone · 2021-01-26 14:51 Quote from: kupferstecher on January 26, 2021, 12:40:28 pmThere were discussions about it before. I think the for..in construct is very useful to avoid boundary-mistakes. But because its not usable in the case you showed, and thats a frequent case, the usecases are too rare to consequently use it. And I don't like changing the complete loop structure, just because something in the inner of the loop changed. An assignable iterator should be allowed, imo. I understand, that the problem is the iterator implementation and not the loop implementation itself, that could be changed. And a construct like the below would be very helpful for save programming (Feature request ;-) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i for ii with someElement in SomeArraydo someElement.index:= ii; Can you provide a practical example of what you are sort of requesting here? I'm not seeing or understanding the desired use cases. ---------------------------------------------------------------------- Bart · 2021-01-26 15:32 Loop variables in a for loop are by design not assignable. This is Pascal after all. Bart ---------------------------------------------------------------------- lucamar · 2021-01-26 16:09 Quote from: Peter H on January 26, 2021, 04:50:50 pmBTW, this construct is not very useful, it can only count the number of matches but cannot retrieve a pointer to the location or an index or build a list. For simple types and complex algotihms it might not always be adecuate (depending on what you're doing) but I can assure you it's a gods-send when you're traversing lists of records or objects. For example, if you want to change some property of all components in a form, or modify strings in a StringList, or ... well, lots of things like that. Of course, if you really need the index then a standard for...to loop must be used but when you care only for the accessed element (and not its position), for...in is a jwell to have. And it happens quite a lot ... ---------------------------------------------------------------------- Peter H · 2021-01-26 16:15 I deleted my last post, it was wrong. Sorry. ---------------------------------------------------------------------- Peter H · 2021-01-26 16:33 This is, how it works: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i ........  ar: array [1 ..10] of char;  c: char= 'a';             // this initialization doesnt matter, it is overwrittenbegin  fillchar(ar,sizeof(ar),#0);  for c in ar do begin    // c is successively assigned each value of ar 10 times here    if c = #0 then {dosomething} ;  end;....... ---------------------------------------------------------------------- Thaddy · 2021-01-26 17:08 Quote from: Peter H on January 26, 2021, 05:33:20 pmThis is, how it works: https://forum.lazarus.freepascal.org/index.php/topic,53040.msg391909.h tml#msg391909 And you should Default() for ar. ---------------------------------------------------------------------- bytebites · 2021-01-26 17:11 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$mode delphi}type  tintarray=array of integer;   { tenum }   tenum=class    fa:tintarray;    fcurrent:integer;    constructor create(a:tintarray);    function movenext:boolean;    function getcurrent:PInteger;    property Current:PInteger read getcurrent;    function getenumerator:tenum;  end;   { tarrhlp }   tarrhlp = record helper for tintarray    function getenumerator:tenum;  end; { tarrhlp } function tarrhlp.getenumerator: tenum;begin  result:=tenum.create(self);end; { tenum } constructor tenum.create(a: tintarray);begin  fa:=a;  fcurrent:=-1;end; function tenum.movenext: boolean;begin  fcurrent:=fcurrent+1;  result:=fcurrentHigh(w) then begin result := false; exit; end;   inc(Fpos); inc(Fidx);   result := true;end;  procedure MultiThread(FromIndex, ToIndex: Integer; Proc: DoProcProcedure; ThreadCount: Integer = 8);var    p: pWorkerthread;  workers:TWorkers;begin  CurrentIndex := FromIndex;    MaxIndex :=  ToIndex;  workers :=      TWorkers.create(Threadcount);    for p in workers do    p^ := TMyWorkerthread.Create(Proc);   while CurrentIndex < MaxIndex do    sleep(100); end; BTW, this is not for practical use. Is just a programming exercise for me. Of course in this case it is overkill. ---------------------------------------------------------------------- ccrause · 2021-01-28 06:28 Quote from: Peter H on January 28, 2021, 02:32:51 amOk, I did my homework  One Question: This "inherited create" at line 18 is it necessary or not? It doesnt make a difference, when I test. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  pWorkerthread = ^TMyWorkerthread;   TWorkers = class  private    Fpos: pworkerthread;    Fidx:integer;  public    w: array of TMyWorkerThread;    constructor create(count:integer);    function GetEnumerator: TWorkers;    function MoveNext:Boolean;    property current: pWorkerThread read Fpos;  end; constructor TWorkers.create(count:integer);begin  //inherited create;  SetLength(w,count);  Fpos := @w[0]; Fidx := 0;end; function TWorkers.GetEnumerator:TWorkers;   begin result := self; end; function TWorkers.MoveNext:boolean; begin   if Fidx>High(w) then begin result := false; exit; end;   inc(Fpos); inc(Fidx);   result := true;end;  procedure MultiThread(FromIndex, ToIndex: Integer; Proc: DoProcProcedure; ThreadCount: Integer = 8);var    p: pWorkerthread;  workers:TWorkers;begin  CurrentIndex := FromIndex;    MaxIndex :=     ToIndex;  workers :=      TWorkers.create(Threadcount);    for p in workers do    p^ := TMyWorkerthread.Create(Proc);   while CurrentIndex < MaxIndex do    sleep(100); end; Your TWorkers class is effectively at the base of the class hierarchy and derives from TObject, which doesn't implement anything in Create.  In Lazarus you can right click on inherited (or the create following inherited) and click on Find declaration...) to view the inherited method. ---------------------------------------------------------------------- Peter H · 2021-01-28 10:42 Quote from: ccrause on January 28, 2021, 07:28:22 amYour TWorkers class is effectively at the base of the class hierarchy and derives from TObject, which doesn't implement anything in Create.  In Lazarus you can right click on inherited (or the create following inherited) and click on Find declaration...) to view the inherited method. Thank you. Couldnt it be that "Create" does some magic stuff under the hood, e.g. setting up VMT's? In this case I would get problems as soon as I use a virtual method, e.g. "Destroy". This is empty too, but maybe it removes the VMT under the hood? Do I get a memory leak, if I dont explicitely call the destructor of TObject ? There must be a reason why it is there, this is what I suspect. Its just a question, simply spoken, I dont know it but want to know. ---------------------------------------------------------------------- PascalDragon · 2021-01-28 12:32 The "magic stuff" is done thanks to you declaring it as constructor. The compiler does the necessary initialization before it calls your constructor and after it returns. The call to the inherited constructor is just a plain method call. Analogous for calling the inherited destructor by the way. ---------------------------------------------------------------------- Peter H · 2021-01-28 13:15 Thank you very much it is clear now. As for the compiler and For x in ... loop, I have a proposal: If  "x" is a pointer to the array element or whatever it could return a pointer automatically. This would be very useful, because this gives write access to the individual elements and avoids a copy. example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i ............var s: string[10]; p: ^char; begin for p in s do   p^ := #32;............  Because the pointer itself cannot be written inside the loop, this is secure. ---------------------------------------------------------------------- Peter H · 2021-01-28 15:45 I tested, if this might work and got errormessages The error messages are not correct. (Lazarus 2.1.0 r64417 FPC 3.3.1 x86_64-win64-win32/win64) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1;type    Ts = array of char;    Tp = ^char; var s:   array of char = Nil;    p:   ^char;    s2:  Ts;   // Initialisation to Nil results in compile error here    p2:  Tp; begin for p in s do;   //project1.lpr(13,5) Error: Incompatible types: got "Char" expected "^Char" for p2 in s2 do; //project1.lpr(15,5) Error: Incompatible types: got "Char" expected "Tp"                 // Note these error messages refer to pos5 in the line, this means to p and p2end.  I registered at mantis and posted it: https://bugs.freepascal.org/view.php?id=38416 ---------------------------------------------------------------------- lucamar · 2021-01-28 17:17 How are they incorrect? You're trying to use a pointer as if it were a char, so it complains, logically enough, about that situation. The "index" of a for...in must match the type it's expecting to receive: in this case, since you're traversing an array of char it must be a char! ---------------------------------------------------------------------- Peter H · 2021-01-28 18:07 Quote from: lucamar on January 26, 2021, 05:09:13 pmQuote from: Peter H on January 26, 2021, 04:50:50 pmBTW, this construct is not very useful, it can only count the number of matches but cannot retrieve a pointer to the location or an index or build a list. For simple types and complex algotihms it might not always be adecuate (depending on what you're doing) but I can assure you it's a gods-send when you're traversing lists of records or objects. For example, if you want to change some property of all components in a form, or modify strings in a StringList, or ... well, lots of things like that. Of course, if you really need the index then a standard for...to loop must be used but when you care only for the accessed element (and not its position), for...in is a jwell to have. And it happens quite a lot ... The problem is, you can modify an object, but not the object variable, because an object variable is implicitly a reference variable. You cannot Create it, because for this you need to assign a new value to the object variable. If an array or vector contains only plain records or plain datatypes, you get a copy of the element and not a reference to it. In this case you cannot even modify it, because you will modify a temporary copy instead. BTW, sorry if i often edit my posts, my english is not so good and almost always I see room for improvements later ---------------------------------------------------------------------- Peter H · 2021-01-28 18:19 Quote from: lucamar on January 28, 2021, 06:17:18 pmHow are they incorrect? You're trying to use a pointer as if it were a char, so it complains, logically enough, about that situation. The "index" of a for...in must match the type it's expecting to receive: in this case, since you're traversing an array of char it must be a char! p and p2 are pointers to char. I hoped the "for p in s..." loop would assign the adress of the items to p, but obviously such a feature is not implemented. The error message is wrong, because it says: "expected a pointer and got a char". The correct error message would be: "expected a char and got a pointer" For clarification see the last loop (I added this now) which tries to get a boolean out of a char array and the corresponding error message: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1;program Project1;uses gvector;type    Ts = array of char;    Tp = ^char; var s:   array of char = Nil;    p:   ^char;    s2:  Ts; // Initialisation to Nil results in compile error here    p2:  Tp;    b:   boolean;begin for p in s do;   //project1.lpr(13,5) Error: Incompatible types: got "Char" expected "^Char"if p in s then; for p2 in s2 do; //project1.lpr(15,5) Error: Incompatible types: got "Char" expected "Tp"                 // Note these error message refers to pos5 in the line, this means to p and p2 for b in s do;   //project1.lpr(20,5) Error: Incompatible types: got "Char" expected "Boolean"end. ---------------------------------------------------------------------- ccrause · 2021-01-28 19:14 Quote from: Peter H on January 28, 2021, 07:19:34 pmThe error message is wrong, because it says: "expected a pointer and got a char". The error refers to the variable p as indicated by the column number. p is a pointer type, but the in s enumeration returns a char type. ---------------------------------------------------------------------- Peter H · 2021-01-28 19:29 Quote from: ccrause on January 28, 2021, 08:14:08 pmQuote from: Peter H on January 28, 2021, 07:19:34 pmThe error message is wrong, because it says: "expected a pointer and got a char". The error refers to the variable p as indicated by the column number. p is a pointer type, but the in s enumeration returns a char type. Exactly. Before the compiler can expect any type, it must evaluate the enumeration. This is, where the value comes from. Therefore it expects a char as assignement target, but it got a pointer, and therefore the message is not correct. Or: It gets a pointer and then evaluates the enumeration and gets a char but expected a pointer. Then the message is correct. Maybe its not wrong, but unclear or not properly explained somewhere.  Ok, I got it. the compiler obviously evaluates values strictly from left to right in the lexical analysis of the expression. This is the opposite flow of execution and I think in the flow of execution. I am not a lexical analyzer.  In this case the message is correct and I am wrong. ---------------------------------------------------------------------- ccrause · 2021-01-28 20:49 Quote from: Peter H on January 28, 2021, 08:29:42 pmOk, I got it. the compiler obviously evaluates values strictly from left to right in the lexical analysis of the expression. This is the opposite flow of execution and I think in the flow of execution. I am not a lexical analyzer.  In this case the message is correct and I am wrong. My view is that the logical error the compiler encountered is an incompatibility between the left and right sides of an assignment.  Whether the left side is wrong, or the right side, is not clear from the evaluation of this specific expression.  So in my opinion there are three potential error messages that are equivalent in reporting the error: 1. The whole expression is an error (for..in expression cannot generate an assignable value for p from s) 2. The left is incompatible with the right (p is not assignable from s) 3. The right is incompatible with the left (s is not assignable to p) The compiler just need to identify which version it picked for reporting the error, in your example the text position flagged indicate that the error message is type 3. ---------------------------------------------------------------------- bytebites · 2021-01-28 20:55 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i s2:  Ts;   // Initialisation to Nil results in compile error hereDoes not, it works correctly. ---------------------------------------------------------------------- Peter H · 2021-01-28 22:47 Quote from: bytebites on January 28, 2021, 09:55:03 pmCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i s2:  Ts;   // Initialisation to Nil results in compile error hereDoes not, it works correctly. Yes I had a typo, now this works. However the error message is still rather dubios. It says: "Expected Boolean got Char" and the cursor is at pos 5 where a boolean is. Should the specialists decide, if this is intentional and correct. Normally the cursor should be at the error position. Then my way to read is correct, if there is type inference. I removed delphi, so I cant test it, but in Delphi this should be possible: for var c in arr do; and the type of c is automatically determined, and if they do it really clever, c is an implicit reference variable. ---------------------------------------------------------------------- kupferstecher · 2021-01-28 23:14 Quote from: ASBzone on January 26, 2021, 03:51:13 pmQuote from: kupferstecher on January 26, 2021, 12:40:28 pmAnd a construct like the below would be very helpful for save programming (Feature request ;-) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i for ii with someElement in SomeArraydo someElement.index:= ii; Can you provide a practical example of what you are sort of requesting here? I'm not seeing or understanding the desired use cases. The integer variable would automatically run from zero until the loop is through, so this would be especially for arrays and lists. I just looked through my sources, there are not many examples when I need the iterator while looping through an array/list and these are not very significant examples. But still sometimes I need it. An example would be printing a list with line numbers. (Perhaps still not very convincing:) Instead of Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i for ii:= 0 to SomeList.Count-1 dodo  Writeln(IntToStr(ii)+TListItem(SomeList[ii]).name); it would be Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i for ii with Pointer(ListItem) in SomeListdo Writeln(IntToStr(ii)+ListItem.name); Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  ii: Integer;  SomeList:TList; //Contains elements of TListItem  ListItem: TListItem; Note, this is not about reduced writing, but to avoid loop bound mistakes. Anyways, I remember there was an other reason why I stopped using for..in. In a multithreading application looping through a list in the standard way is thread save for read operations, with for..in it isn't any more, as the iterator is actually part of the list (At least I understand it like this). I know, an unprotected read access is something that shouldn't be done anyways, but I had some bad trouble with threads before, so I don't want to risk anything, there.