microsoft / qsharp-language

Official repository for design of the quantum programming language Q# and its core libraries
MIT License
233 stars 54 forks source link

Document updating an element of a 2D array #113

Open tcNickolas opened 2 years ago

tcNickolas commented 2 years ago

At Copy-and-Update Expressions page, we have examples of updating UDTs and 1D arrays, but not of 2D arrays. It is really hard for a new user to figure out the syntax for 2D arrays, so an example would help a lot.

cgranade commented 2 years ago

I think part of what may make this confusing is that we don't have 2D arrays in Q# currently (indeed, this issue is great feedback on #39, as one of the motivations for that QEP is to reduce confusion in representing multidimensional data). Thus, at the moment, the best option available for representing multidimensional data is to use an array of arrays, e.g.:

mutable identity = ConstantArray(3, ConstantArray(3, 0));
for idx in 0..2 {
    // Use w/= to replace the `idx`th row.
    set identity w/= idx <-
        // We want the `idx`th row to be identical to its original value,
        // except in the `idx`th column. That re
        (identity[0] w/ idx <- 1);
}

Hopefully once QEP 3 is implemented, that will look a bit simpler by allowing replacement of elements directly without having to worry about jaggedness of nested arrays:

let identity = [| 0, size = (3, 3) |]
    w/ (0, 0) <- 1
    w/ (1, 1) <- 1
    w/ (2, 2) <- 1;
TonyHoldroyd commented 2 years ago

Thank you for that, very helpful. And I'll look forward to QEP 3