Up |
tupleSet
Set the value of an element of a tuple from its position.
If the position is out of range, the function will return nil.
This function should be reserved to the advanced developers only, a bad use can do something unwanted. A good use should be safe.
Usually, two cases can occur :
-
You can set with any type, even if it is different than the old type. Depending on what you wish to do, this may don't be a problem. But remember you that for all futures treatments the type has changed. This may be harmless ... or not.
Look this code, it works fine :
typeof TUPLE = [I I I];; fun displayTuple (a, n)= if n < 0 then 0 else ( _fooId tupleGet a n nil; displayTuple a n-1 );; fun main ()= _showconsole; set TUPLE = [1 5 4]; _fooS "TUPLE"; _fooId tupleGet TUPLE 1 nil; displayTuple TUPLE (tupleSize TUPLE)-1; tupleSet TUPLE 1 "string"; _fooS tupleGet TUPLE 1 nil; displayTuple TUPLE (tupleSize TUPLE)-1; 0;;
The type displayTuple is
fun [u0 I] I
and _fooId accepts all types. However, in some complex process, a modified type can be dangerous.
Finally, even if the type of TUPLE is[I I I]
, Scol " accepts " this change to[I S I]
during the execution (because the prototype of the tuple in tupleGet isu0
during the compilation and Scol ignores types to the execution).Other example :
fun main ()= _showconsole; let 0 -> a in let tupleSet a 0 "string" -> b in ( _fooId a; // 0 _fooId b; // 0 _fooS tupleGet b 0 nil; // string );
tupleSet returns an integer because 'a' is an integer (even if it is not a tuple ! tupleSet returns the same type), therefore b is an integer :
_fooId b is correct.
tupleGet b 0 nil
returns the first and unique element of b, a string. It is correct with _fooS.Now, a "little" change :
fun main ()= _showconsole; let 0 -> a in let tupleSet a 0 "string" -> b in ( _fooId a; _fooS b; // change _fooId by _fooS _fooS tupleGet b 0 nil; );
Here, this code crashes :
>>> ERROR - Type mismatch (detail):
Found: [I S S]
Expected: [I I u0]
<<<Indeed, b (see above) is considered by Scol like an integer, not like a string.
Developers to be careful what they do !
-
If you change the old value by a new value of the same type, you should have no problem.
Prototype :
fun [u0 I u1] u0
- u0 : a tuple. If this argument is not a tuple, the application can have an undefined behavior (see 2nd and 3rd examples above).
- I : a position. If the position is out of range, nil will be returned
- u1 : a new value
Return : u0 the same tuple or nil if error
See also :
Example :
fun setTuple (tuple, c)=
set tuple = tupleSet tuple 0 c; // set the first element to 'c'
if c < tupleGet tuple 1 nil then // set the second element if the condition is true
set tuple = tupleSet tuple 1 c + tupleGet tuple 1 nil; // old value + 'c'
else
nil;
0;;
fun initTuple (tuple, a, b)=
set tuple = [a b b];
// others things to do
0;;
Note
The first element has always the index 0.