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 a data |
| 6 | /// structure, like an array or UDT, and update a single element in the |
| 7 | /// copied version of the structure. |
| 8 | namespace MyQuantumApp { |
| 9 | |
| 10 | newtype Pair = (first : Int, second : Int); |
| 11 | |
| 12 | @EntryPoint() |
| 13 | function Main() : Unit { |
| 14 | let array = [10, 11, 12, 13]; |
| 15 | let pair = Pair(20, 21); |
| 16 | |
| 17 | // `w/` followed by the `<-` copies and updates a single element. |
| 18 | |
| 19 | // `new_array` is an array with values `[10, 11, 100, 13]`. |
| 20 | // `array` is unchanged. |
| 21 | let new_array = array w/ 2 <- 100; |
| 22 | Message($"Updated array: {new_array}"); |
| 23 | |
| 24 | // `new_array` is an array with values `[10, 100, 12, 200]`. |
| 25 | // `array` is unchanged. |
| 26 | let new_array = array |
| 27 | w/ 1 <- 100 |
| 28 | w/ 3 <- 200; |
| 29 | Message($"Updated array: {new_array}"); |
| 30 | |
| 31 | // `new_pair` is a Pair with value `Pair(20, 100)`. |
| 32 | // `pair` is unchanged. |
| 33 | let new_pair = pair w/ second <- 100; |
| 34 | Message($"Updated struct: (first:{new_pair::first}, second:{new_pair::second})"); |
| 35 | } |
| 36 | } |