askql icon indicating copy to clipboard operation
askql copied to clipboard

Cannot run an AskScript program (example)

Open czerwinskilukasz1 opened this issue 4 years ago • 3 comments

The following program does not work. The error is:

Error: Unknown identifier '='!
// Below is a complete solution for a 5kyu Codewars task: 
// https://www.codewars.com/kata/54d81488b981293527000c8f/javascript

// One of the existing solutions in Javascript,
// published at https://www.codewars.com/kata/reviews/54dfec0fa1b757b06d000179/groups/54e04095766f50701b000013
// is:
//
//var sum_pairs=function(ints, s){
//  var seen = {}
//  for (var i = 0; i < ints.length; ++i) {
//    if (seen[s - ints[i]]) return [s - ints[i], ints[i]];
//    seen[ints[i]] = true
//  }
//}

// In AskScript it looks the following:

ask {
    const sum_pairs = fun(ints: array(int), s: int): array(int) {
        let seen = {};
        for (const i = 0; i < ints:length; i = i + 1) {
            if (seen[s - ints[i]]) {
                return [s - ints[i], ints[i]];
            }
            seen[ints[i]] = true;
        }
    }
    
    [
        sum_pairs([11, 3, 7, 5],         10)   == [3, 7],
        sum_pairs([4, 3, 2, 3, 4],        6)   == [4, 2],
        sum_pairs([0, 0, -2, 3],          2)   == null,
        sum_pairs([10, 5, 2, 3, 7, 5],   10)   == [3, 7]
    ]
}

czerwinskilukasz1 avatar Jul 09 '20 18:07 czerwinskilukasz1

This is actually related to immutability of objects in AskScript, so seen[ints[i]] = true; is invalid. However, currently there is no resource which could assign values to an existing object per https://github.com/xFAANG/askql/issues/257 , and this is the underlying issue.

czerwinskilukasz1 avatar Jul 09 '20 18:07 czerwinskilukasz1

Blocked on #257

czerwinskilukasz1 avatar Jul 09 '20 18:07 czerwinskilukasz1

seen[ints[i]] = true; is incompatible with the principle of immutable data. Let me give you an example

delayedLog(seen) // should print old seen after 1 sec
seen[ints[i]] = true // should create a new seen object and assign it to the seen variable
delayedLog(seen) // should print new seen after 1 sec

If we mutate the seen object referenced by the seen variable then both logs will log the new object, which will be confusing.

mhagmajer avatar Jul 10 '20 10:07 mhagmajer