microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
samples/language/Array.qs
45lines · 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 `Std.Core` and returns an `Int` value. |
| 17 | // Suitable initialization routines for arrays of `Qubit`s can be found in the |
| 18 | // `Std.Arrays` namespace. |
| 19 | |
| 20 | function Main() : Int[] { |
| 21 | |
| 22 | // A basic Int Array literal |
| 23 | let intArray : Int[] = [1, 2, 3, 4]; |
| 24 | Message($"Integer Array: {intArray} of length {Length(intArray)}"); |
| 25 | |
| 26 | // A basic String Array literal |
| 27 | let stringArray = ["a", "string", "array"]; |
| 28 | Message($"String Array: {stringArray}"); |
| 29 | |
| 30 | // A new array expression creating the array `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]` |
| 31 | let repeatedArray = [0, size = 10]; |
| 32 | Message($"Repeated Array: {repeatedArray}"); |
| 33 | let repeatedArray = Repeated(0, 10); // contains [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] |
| 34 | Message($"Repeated Array: {repeatedArray}"); |
| 35 | |
| 36 | // Arrays can be sliced with ranges. |
| 37 | let slice = intArray[1..2..4]; // contains [2,4] |
| 38 | Message($"Sliced array: {slice}"); |
| 39 | let slice = intArray[2..-1..0]; // contains [3,2,1] |
| 40 | Message($"Sliced array: {slice}"); |
| 41 | let slice = intArray[...]; // contains [1, 2, 3, 4]; |
| 42 | Message($"Sliced array: {slice}"); |
| 43 | |
| 44 | return intArray; |
| 45 | } |
| 46 | |