A multi-core friendly switch symbol

A piece-wise defined mathematical operator or equivalent which is multi-core friendly

Version 1 (Original Version)

var i = 1 
let x = 0

switch(i){
    case 1:
    x=i
    break
    
    case 2:
    x=i+1
    break
    
    case 3:
    x=i-1
    break
    
    case 4:
    x=i^2
    break
}

Version 2

let x = { 
    i, when i==1;
    i+1, when i==2;
    i-1, when i==3;
    i^2, when i==4;
}

How is version 1 new syntax? What does version 2 do differently? And what does "multi-core friendly" mean?

2 Likes

Oh, sorry, I've updated the post to now indicate version 1 as the original version. A new symbol and/or construct which sends stronger optimization inferences to the compiler.

Thanks for the update. However, it is still unclear what kind of optimisation you are thinking of, and whether an optimisation hint would change any semantics. If it doesn't, I doubt there's much of an advantage over the current state of the art, compilers already optimise switch branching on primitive values with literal cases quite well.

2 Likes

The idea itself is good, but the post isn't. Let me rewrite a new one with a better example.

My suggestion would be a C#-like one:

let i = 0; // maybe anything
const finalize = (() => {
    let privateType;
    return type => {
        privateType = type;
        // some other operations
        return privateType;
    };
})();
let x = i switch {
    1 => finalize("one"),
    2 => finalize("two"),
    3 => "few",
    _ => "other",
};

It should be called something like (inline) switch expression, and it should treated as a syntactic sugar of

let x = (() => {
    switch (i) {
        case 1: return finalize("one");
        case 2: return finalize("two");
        case 3: return "few";
        default: return "other";
    }
})();

Or similarly:

let x = ({
    1: () => finalize("one"),
    2: () => finalize("two"),
    3: () => "few"
}[i] || () => "other")();

FYI, C# introduced this syntax in C# 8.0 in 2019.

I don't think optimization is a concern because it is simply a syntactic sugar. We don't need to discuss optimization at all, at least for now.