microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
samples/language/CopyAndUpdateOperator.qs
36lines · modecode
| 1 | // # Sample |
| 2 | // Copy and Update Operator |
| 3 | // |
| 4 | // # Description |
| 5 | // The copy and update operator in Q# is used to make a copy of an |
| 6 | // array and update a single element in the copied version. |
| 7 | |
| 8 | function Main() : Unit { |
| 9 | let array = [10, 11, 12, 13]; |
| 10 | |
| 11 | // `w/` followed by the `<-` copies and updates a single element. |
| 12 | |
| 13 | // `new_array` is an array with values `[10, 11, 100, 13]`. |
| 14 | // `array` is unchanged. |
| 15 | let new_array = array w/ 2 <- 100; |
| 16 | Message($"Updated array: {new_array}"); |
| 17 | |
| 18 | // `new_array` is an array with values `[10, 100, 12, 200]`. |
| 19 | // `array` is unchanged. |
| 20 | let new_array = array |
| 21 | w/ 1 <- 100 |
| 22 | w/ 3 <- 200; |
| 23 | Message($"Updated array: {new_array}"); |
| 24 | |
| 25 | // In addition to arrays, we can also copy-and-update structs. |
| 26 | // First, let's define a struct called `Complex` which represents a |
| 27 | // complex number. |
| 28 | struct Complex { Real : Double, Imaginary : Double } |
| 29 | // Instantiation of the above struct. |
| 30 | let complex = new Complex { Real = 42.0, Imaginary = 0.0 }; |
| 31 | |
| 32 | // `new_complex` is a new instance of the `Complex` struct with the |
| 33 | // `Real` field updated to `100.0`. |
| 34 | // `complex` is unchanged. |
| 35 | let new_complex = new Complex { ...complex, Real = 100.0 }; |
| 36 | } |
| 37 | |