Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a Ceylon Sequential or array into a generic Tuple with the appropriate type?

Tags:

ceylon

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?

like image 757
Renato Avatar asked Oct 30 '22 14:10

Renato


1 Answers

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);
}
like image 65
Renato Avatar answered Nov 18 '22 04:11

Renato