Post Reply 
INSERT doesn't insert
09-18-2019, 04:14 PM (This post was last modified: 09-19-2019 01:21 AM by toml_12953.)
Post: #2
RE: INSERT doesn't insert
(09-18-2019 02:13 PM)Cristóbal De Jesús Wrote:  
Code:
EXPORT STRINGIDS()
BEGIN

LOCAL STRGS := {}, STRGID:=0, STRG:="";

  FOR STRGID FROM 1 TO 100 DO
    STRG := STRINGFROMID(STRGID);
    INSERT(STRGS,1,STRG); // Misbehaving here!
  END;

RETURN STRGS;

I tried the INSERT command with lists, in the Home screen, and it doesn't seem to insert items to lists.

Most likely, I am missing something here...

The INSERT statement doesn't change the list. It only returns the value. You have to set the list equal to the value yourself. If you're familiar with function vocabulary,
the Prime only passes parameters by value, not by reference. Personally, if I could only pass one way, I'd pass by reference. Ideally, the interpreter would give you the option of passing variable either way like Microsoft BASIC does with the BYVAL keyword.
Passing by value makes a copy of the parameter to use in the function. You can't change the value of the parameter because you're only working with a copy.
Passing by reference passes the address of the variable to the function so you're working directly with the variable. This means if you change the variable in the function, the value will be changed in the main program. This uses less memory since you don't have to make copies of variable (especially arrays!) Only a pointer to the variable is passed. It is usually faster to pass by reference as well since you don't have the overhead of copying the value of the variable to a new location.
Since Prime passes by value, when you use INSERT(STRGS,1,STRG), you add STRG to a copy of STRGS, not the original STRGS. That's why you have to do the STRGS:= because you have to save the return value of the function. If Prime passed by reference, it would work the way you expected and the way I'd like it to and the := wouldn't be necessary.
There is a danger to passing by reference, however. You can change your original variables which makes recursion difficult and you might change variables inadvertently.

Code:
EXPORT STRINGIDS()
BEGIN

LOCAL STRGS:={},STRGID:=0,STRG:="";
PRINT();

FOR STRGID:=1 TO 100 DO
  STRG:=STRINGFROMID(101-STRGID); // To put list in correct order
  STRGS:=INSERT(STRGS,1,STRG);  
END;

PRINT(STRGS);
RETURN STRGS;

END;

Tom L
Cui bono?
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: INSERT doesn't insert - toml_12953 - 09-18-2019 04:14 PM
RE: INSERT doesn't insert - Carlos295pz - 09-20-2019, 01:09 PM



User(s) browsing this thread: 1 Guest(s)