microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
samples/language/Array.qs
45lines · modeblame
ce8303b0Alex Hansen1 years ago | 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 | |
91f754e1Scott Carda1 years ago | 16 | // in the automatically opened namespace `Std.Core` and returns an `Int` value. |
ce8303b0Alex Hansen1 years ago | 17 | // Suitable initialization routines for arrays of `Qubit`s can be found in the |
91f754e1Scott Carda1 years ago | 18 | // `Std.Arrays` namespace. |
99c94d55Alex Hansen2 years ago | 19 | |
ce8303b0Alex Hansen1 years ago | 20 | function Main() : Int[] { |
99c94d55Alex Hansen2 years ago | 21 | |
ce8303b0Alex Hansen1 years ago | 22 | // A basic Int Array literal |
| 23 | let intArray : Int[] = [1, 2, 3, 4]; | |
| 24 | Message($"Integer Array: {intArray} of length {Length(intArray)}"); | |
5d092b61Joshua Aragon2 years ago | 25 | |
ce8303b0Alex Hansen1 years ago | 26 | // A basic String Array literal |
| 27 | let stringArray = ["a", "string", "array"]; | |
| 28 | Message($"String Array: {stringArray}"); | |
99c94d55Alex Hansen2 years ago | 29 | |
ce8303b0Alex Hansen1 years ago | 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}"); | |
99c94d55Alex Hansen2 years ago | 35 | |
ce8303b0Alex Hansen1 years ago | 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}"); | |
99c94d55Alex Hansen2 years ago | 43 | |
ce8303b0Alex Hansen1 years ago | 44 | return intArray; |
99c94d55Alex Hansen2 years ago | 45 | } |