When scalar becomes an array, aka. type coercion in AFL

Since the subject of data types surfaced in this thread: Send orders to IB on next bar (Intraday)

Here are some comments regarding data types in AFL.

While some users who familiarized a bit with array handling in AFL may think that everything is an array in AFL, that is not the case.

The data type depends on value assigned to variable. If you assign scalar (number) the variable type will be scalar (floating point number, 4 bytes long).

So if you assign a number to variable like this:

var1 = 6; // var1 is scalar, NOT an array, consumes just single float value (4 bytes)

AmiBroker automagically does transformations for you so you don't need to worry BUT at the same time it always tries NOT to use/allocate array when it is not needed. For example if you write

level = 50; // level is NOT array, it is scalar (4 bytes)
Buy = Close > level; // here array is compared to SCALAR, resulting in True/False Buy array

AmiBroker allows you to mix arrays and scalars in expressions doing all the work for you:

var1 = (LastValue( High ) + LastValue( Low ))/2; // var1 will be SCALAR (4 bytes)
var2 = var1 + Close; // adding scalar to array gives array
// var1 is still scalar (it is NOT converted to array)

AmiBroker allows you to use scalar everywhere where you can use array. AmiBroker has polymorphic functions like IIF that return different types depending on types of inputs, like this:

result1 = IIF( LastValue( Close > Open ), 7, 5 ); // result1 will be SCALAR value 7 or 5 depending on just last bar condition
result2 = IIF( Close > Open, 7, 5 ); // result2 will be array of values 

As you can see same function IIF returns scalar or array depending on inputs.

Thanks to ability to treat scalar as arrays when array type is expected, AmiBroker will allow you to use subscript on variable that is scalar

var1 = 5;
printf("%g", var1[ 0 ] ); // even though var1 is scalar you still can treat it as array
// var1 will still be scalar 

AmiBroker does not allocate memory for array until it is absolutely necessary.

Only if you WRITE to individual element, AmiBroker will convert the type:

var1 = 5;
printf("%g\n", var1[ 0 ] ); // even though var1 is scalar you still can treat it as array
var1[0] = 6; // now var1 becomes array (because of assignment of individual element)

Once variable is upsized to array, it stays so (at least until you overwrite it with some other value).

Generally all the above details are not that important for 'regular' user. The only situation when scalar vs array becomes important is when somebody tries to use array in flow control statements. Flow control statements require scalar values to make the decision (conditional jump) as explained in http://www.amibroker.com/guide/a_mistakes.html

22 Likes