function square(input: x) {
return x * x;
}
var singleValue = 2;
var arrayValue = [1, 2, 3];
var singleResult = square(singleValue);
var arrayResult = square(each in arrayValue);
// arrayResult is [1, 4, 9]
Is it clear what the value of arrayResult will be? I am particularly interested in the opinion of newer developers here since they aren't used to seeing and thinking in forEach or map.I think the value of this style really shows its strength when you deal with a few more complicated examples
var arrayResult = pow(each in arrayValue, 3);
// arrays are iterated over in parallel, stopping when the first array ends
var actionResult = doAction(each in arrayA, transformValue(each in arrayB));
// each<n> allows you to nest loops with the smaller values taking the outer loop
// reduce combines array elements in different ways
var matrixSum = reduce sum(matrix.get(
each<0> in range(0, matrix.rowCount),
each<1> in range(0, matrix.columnCount))
)
compare that to doing something similar by traditional meansvar arrayResult = arrayValue.map((value) => pow(value, 3));
var actionResult = range(0, min(arrayA.length, arrayB.length)).map((index) => {
return doAction(arrayA[index], transformValue(arrayB[index]));
});
var matrixSum = range(0, matrix.height).flatMap((row) => {
return range(0, matrix.width).map((colum) => {
return matrix.get(row, column);
})
}).reduce(sum, 0);
I recognize that this alternate syntax isn't perfect but I really like. There are two immediate wins I see with the alternate syntax.1) You don't have to restructure you code if a variable type changes from a single value to an array
Traditionally, changing a type from a single value to an array requires you to restructure code to use a forEach.
doAction(singleValue);
arrayValue.forEach(doAction);
With the new style, no restructure needed, just add 'each in' where neededdoAction(singleValue);
doAction(each in arrayValue)
2) The compiler knows more about the forEach loop and can make better optimizationsmap can generate a lot of junk for the garbage collector since it needs to create an entire array that will be just discarded like in the case of the matrix sum example. Iterators like in Linq solve the temporary memory problem but create a chain full of virtual calls and labmda functions that can be difficult to optimize. The new syntax can allow the compiler to transform the forEach code into a simple loop and can know if a new array needs to be created, or if values are combined into a single result.
Thoughts on the syntax? Are there any glaring issues you see with it?