microsoft / QuantumLibraries

Q# libraries for the Quantum Development Kit

Home Page:https://docs.microsoft.com/quantum

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Refactor `Mapped` to avoid use of `Default`

swernli opened this issue · comments

Describe the bug
Default uses deprecated new array syntax to create default and often invalid values for generic types. Because Mapped uses Default to pre-allocate the array being mapped into, it can inadvertently trigger asserts in runtimes that check for valid content on creation of values. We should find a way to refactor Mapped to protect against this.

One possible suggestion for a new implementation (courtesy of @cgranade):

// pseudocode
function Mapped<'T, 'O>(fn : 'T -> 'O, arr : 'T[]) : 'O {
    if Length(arr) == 0 {
        return [];
    }
    let first = fn(arr[0]);
    mutable retval = [first; size=Length(arr)];
    for idx in 1..Length(arr) - 1{
        set retval w/ idx <- fn(arr[idx]);
    }
    return retval;
}

Related:
microsoft/qsharp-runtime#977
microsoft/qsharp-runtime#975