microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
samples/language/Array.qs
48lines · modecode
| 1 | /// # Sample |
| 2 | /// Array |
| 3 | /// |
| 4 | /// # Description |
| 5 | /// An array literal is a sequence of one or more expressions, separated by commas |
| 6 | /// and enclosed in brackets `[` and `]`; for example, `[1,2,3]`. All expressions must |
| 7 | /// have a common base type, which is the item type of the array. |
| 8 | /// |
| 9 | /// Arrays of arbitrary length, and in particular empty arrays, may be created using |
| 10 | /// a new array expression. Such an expression is of the form new `[expr1, size = expr2]`, |
| 11 | /// where `expr1` is an expression of any type and `expr2` is an expression of type `Int`. |
| 12 | /// The expression `expr1` is used as the default value for all of the array items. |
| 13 | /// |
| 14 | /// For example, `[0, size = 10]` creates an array of zeroes containing ten items. |
| 15 | /// The length of an array can be queried with the function `Length`. It is defined |
| 16 | /// in the automatically opened namespace `Microsoft.Quantum.Core` and returns an `Int` value. |
| 17 | /// Suitable initialization routines for arrays of `Qubit`s can be found in the |
| 18 | /// `Microsoft.Quantum.Arrays` namespace. |
| 19 | namespace MyQuantumApp { |
| 20 | |
| 21 | @EntryPoint() |
| 22 | operation Main() : Int[] { |
| 23 | |
| 24 | // A basic Int Array literal |
| 25 | let intArray : Int[] = [1, 2, 3, 4]; |
| 26 | Message($"Integer Array : {intArray} of length {Length(intArray)}"); |
| 27 | |
| 28 | // A basic String Array literal |
| 29 | let stringArray = ["a", "string", "array"]; |
| 30 | Message($"{stringArray}"); |
| 31 | |
| 32 | // A new array expression creating the array `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]` |
| 33 | let repeatedArray = [0, size = 10]; |
| 34 | Message($"{repeatedArray}"); |
| 35 | let repeatedArray = Repeated(0, 10); // contains [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] |
| 36 | Message($"{repeatedArray}"); |
| 37 | |
| 38 | // Arrays can be sliced with ranges. |
| 39 | let slice = intArray[1..2..4]; // contains [2,4] |
| 40 | Message($"{slice}"); |
| 41 | let slice = intArray[2..-1..0]; // contains [3,2,1] |
| 42 | Message($"{slice}"); |
| 43 | let slice = intArray[...]; // contains [1, 2, 3, 4]; |
| 44 | Message($"{slice}"); |
| 45 | |
| 46 | return intArray; |
| 47 | } |
| 48 | } |
| 49 | |