I've got a generic function that needs to create a Tuple to call a function whose arguments I don't know the types of.
Something like this (except array in this example is created by some external code, so I can't just apply the function directly):
Result apply<Result, Where>(
    Anything[] array, 
    Callable<Result, Where> fun)
        given Where satisfies Anything[] => nothing;
Is there a type-safe way to implement this method and get the function to be called with the given arguments?
This cannot be done completely type-safely... but assuming that the array indeed contains elements of the correct types as they should appear in a Tuple of type Where, the following function will do the trick:
Tuple<Anything, Anything, Anything> typedTuple({Anything+} array) {
    if (exists second = array.rest.first) {
        return Tuple(array.first, typedTuple({ second }.chain(array.rest.rest)));
    }
    else {
        return Tuple(array.first, []);
    }
}
And apply gets implemented as:
Result apply<Result, Where>(
    [Anything+] array, 
    Callable<Result, Where> fun)
        given Where satisfies Anything[] {
    value tuple = typedTuple(array);
    assert(is Where tuple);
    return fun(*tuple);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With