From 5c3cb41a952ba6ad0cc22fd8b6266abfead29604 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Fri, 22 Mar 2024 12:18:40 -0700 Subject: [PATCH 01/13] Remove unauthoritative newlines --- compiler/qsc_formatter/src/formatter.rs | 79 +++++++++++-------------- compiler/qsc_formatter/src/lib.rs | 8 ++- 2 files changed, 38 insertions(+), 49 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index bdbe4faea3..5667ffa62f 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -357,13 +357,16 @@ impl<'a> Formatter<'a> { | (_, Keyword(Keyword::Slf)) => { effect_single_space(left, whitespace, right, &mut edits); } - (_, _) if are_newlines_in_spaces => { - effect_trim_whitespace(left, whitespace, right, &mut edits); - // Ignore the rest of the cases if the user has a newline in the whitespace. - // This is done because we don't currently have logic for determining when - // lines are too long and require newlines, and we don't have logic - // for determining what the correct indentation should be in these cases, - // so we put this do-nothing case in to leave user code unchanged. + (Close(Delim::Brace), _) + if is_newline_after_brace(cooked_right, right_delim_state) => + { + effect_correct_indentation( + left, + whitespace, + right, + &mut edits, + self.indent_level, + ); } (String(StringToken::Interpolated(_, InterpolatedEnding::LBrace)), _) | (_, String(StringToken::Interpolated(InterpolatedStart::RBrace, _))) => { @@ -391,14 +394,10 @@ impl<'a> Formatter<'a> { effect_single_space(left, whitespace, right, &mut edits); } } - (_, Keyword(Keyword::Is)) - | (_, Keyword(Keyword::For)) - | (_, Keyword(Keyword::While)) - | (_, Keyword(Keyword::Repeat)) - | (_, Keyword(Keyword::If)) - | (_, Keyword(Keyword::Within)) - | (_, Keyword(Keyword::Return)) - | (_, Keyword(Keyword::Fail)) => { + (_, Keyword(Keyword::Is)) => { + effect_single_space(left, whitespace, right, &mut edits); + } + (_, Keyword(keyword)) if is_starter_keyword(keyword) => { effect_single_space(left, whitespace, right, &mut edits); } (_, _) if is_value_token_right(cooked_right, right_delim_state) => { @@ -421,6 +420,9 @@ impl<'a> Formatter<'a> { (_, _) if is_prefix_without_space(cooked_right) => { effect_no_space(left, whitespace, right, &mut edits); } + (_, Keyword(keyword)) if is_prefix_keyword(keyword) => { + effect_single_space(left, whitespace, right, &mut edits); + } (_, _) if is_bin_op(cooked_right) => { effect_single_space(left, whitespace, right, &mut edits); } @@ -586,10 +588,6 @@ fn is_bin_op(cooked: &TokenKind) -> bool { | TokenKind::WSlashEq | TokenKind::Keyword(Keyword::And) | TokenKind::Keyword(Keyword::Or) - // Technically the rest are not binary ops, but has the same spacing as one - | TokenKind::Keyword(Keyword::Not) - | TokenKind::Keyword(Keyword::AdjointUpper) - | TokenKind::Keyword(Keyword::ControlledUpper) ) } @@ -614,6 +612,11 @@ fn is_suffix(cooked: &TokenKind) -> bool { matches!(cooked, TokenKind::Bang | TokenKind::Comma) } +fn is_prefix_keyword(keyword: &Keyword) -> bool { + use Keyword::*; + matches!(keyword, Not | AdjointUpper | ControlledUpper) +} + fn is_keyword_value(keyword: &Keyword) -> bool { use Keyword::*; matches!( @@ -649,6 +652,17 @@ fn is_newline_keyword_or_ampersat(cooked: &TokenKind) -> bool { ) } +fn is_starter_keyword(keyword: &Keyword) -> bool { + use Keyword::*; + matches!(keyword, For | While | Repeat | If | Within | Return | Fail) +} + +fn is_newline_after_brace(cooked: &TokenKind, delim_state: Delimiter) -> bool { + is_value_token_right(cooked, delim_state) + || matches!(cooked, TokenKind::Keyword(keyword) if is_starter_keyword(keyword)) + || matches!(cooked, TokenKind::Keyword(keyword) if is_prefix_keyword(keyword)) +} + /// Note that this does not include interpolated string literals fn is_value_lit(cooked: &TokenKind) -> bool { matches!( @@ -728,33 +742,6 @@ fn effect_trim_comment(left: &ConcreteToken, edits: &mut Vec, code: &s } } -fn effect_trim_whitespace( - left: &ConcreteToken, - whitespace: &str, - right: &ConcreteToken, - edits: &mut Vec, -) { - let count_newlines = whitespace.chars().filter(|c| *c == '\n').count(); - let suffix = match whitespace.rsplit_once('\n') { - Some((_, suffix)) => suffix, - None => "", - }; - - let mut new_whitespace = if whitespace.contains("\r\n") { - "\r\n".repeat(count_newlines) - } else { - "\n".repeat(count_newlines) - }; - new_whitespace.push_str(suffix); - if whitespace != new_whitespace { - edits.push(TextEdit::new( - new_whitespace.as_str(), - left.span.hi, - right.span.lo, - )); - } -} - fn effect_correct_indentation( left: &ConcreteToken, whitespace: &str, diff --git a/compiler/qsc_formatter/src/lib.rs b/compiler/qsc_formatter/src/lib.rs index dcfeb86981..21b1bafc3e 100644 --- a/compiler/qsc_formatter/src/lib.rs +++ b/compiler/qsc_formatter/src/lib.rs @@ -6,8 +6,10 @@ //! uses the cooked and concrete tokens from the parser crate to create a //! token stream of the given source code string. It then uses a sliding window //! over this token stream to apply formatting rules when the selected tokens -//! match certain patterns. Formatting rules will generate text edit objects -//! when the format of the input string does not match the expected format, and -//! these edits are returned on using the formatter. +//! match certain patterns. The formatting algorithm uses state to help make +//! correct decisions, particularly around indentation. Formatting rules will +//! generate text edit objects when the format of the input string does not +//! match the expected format, and these edits are returned on using the +//! formatter. pub mod formatter; From c142806ba2941153a48a5e08b9460da64b74a93e Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Fri, 22 Mar 2024 13:24:36 -0700 Subject: [PATCH 02/13] test cases for removing newlines --- compiler/qsc_formatter/src/formatter/tests.rs | 117 ++++++++++++++++-- 1 file changed, 108 insertions(+), 9 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter/tests.rs b/compiler/qsc_formatter/src/formatter/tests.rs index 785824ea3d..d97ff1da63 100644 --- a/compiler/qsc_formatter/src/formatter/tests.rs +++ b/compiler/qsc_formatter/src/formatter/tests.rs @@ -520,10 +520,10 @@ fn single_space_before_open_brace_and_newline_after() { operation Foo() : Unit { let x = 3; } - operation Bar() : Unit - { { + operation Bar() : Unit { { let x = 3; - } { + } + { let x = 4; } } "#]], @@ -903,12 +903,111 @@ fn preserve_string_indentation() { // Will respect user new-lines and indentation added into expressions #[test] -fn preserve_user_newlines_in_expressions() { - let input = indoc! {r#" - let y = 1 + 2 + 3 + 4 + 5 + - 6 + 7 + 8 + 9 + 10; - "#}; - assert!(super::calculate_format_edits(input).is_empty()); +fn newline_after_brace_before_value() { + check(indoc! {r#" + { + let x = 3; + } x + "#}, &expect![[r#" + { + let x = 3; + } + x + "#]]) +} + +#[test] +fn newline_after_brace_before_functor() { + check(indoc! {r#" + { + let x = 3; + } Adjoint Foo(); + "#}, &expect![[r#" + { + let x = 3; + } + Adjoint Foo(); + "#]]) +} + +#[test] +fn newline_after_brace_before_not_keyword() { + check(indoc! {r#" + { + let x = 3; + } not true + "#}, &expect![[r#" + { + let x = 3; + } + not true + "#]]) +} + +#[test] +fn newline_after_brace_before_starter_keyword() { + check(indoc! {r#" + { + let x = 3; + } if true {} + "#}, &expect![[r#" + { + let x = 3; + } + if true {} + "#]]) +} + +#[test] +fn newline_after_brace_before_brace() { + check(indoc! {r#" + { + let x = 3; + } {} + "#}, &expect![[r#" + { + let x = 3; + } + {} + "#]]) +} + +#[test] +fn space_after_brace_before_operator() { + check(indoc! {r#" + { + let x = 3; + } + {} + "#}, &expect![[r#" + { + let x = 3; + } + {} + "#]]) +} + +#[test] +fn newline_after_brace_before_delim() { + check(indoc! {r#" + {} () + {} [] + "#}, &expect![[r#" + {} + () {} + [] + "#]]) +} + +#[test] +fn test() { + check(indoc! {r#" + {} (); + {} [] + "#}, &expect![[r#" + {} + (); + {} + [] + "#]]) } // Remove extra whitespace from start of code From 8d3a1c15ee920a33005f3f8e2739a3d8795fa26d Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Fri, 22 Mar 2024 14:53:28 -0700 Subject: [PATCH 03/13] Allow copy and update to have newlines --- compiler/qsc_formatter/src/formatter.rs | 9 +++++++ compiler/qsc_formatter/src/formatter/tests.rs | 25 +++++++++++++------ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index 5667ffa62f..6462337562 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -423,6 +423,15 @@ impl<'a> Formatter<'a> { (_, Keyword(keyword)) if is_prefix_keyword(keyword) => { effect_single_space(left, whitespace, right, &mut edits); } + (_, WSlash) if are_newlines_in_spaces => { + effect_correct_indentation( + left, + whitespace, + right, + &mut edits, + self.indent_level + 1, + ); + } (_, _) if is_bin_op(cooked_right) => { effect_single_space(left, whitespace, right, &mut edits); } diff --git a/compiler/qsc_formatter/src/formatter/tests.rs b/compiler/qsc_formatter/src/formatter/tests.rs index d97ff1da63..3071d6426f 100644 --- a/compiler/qsc_formatter/src/formatter/tests.rs +++ b/compiler/qsc_formatter/src/formatter/tests.rs @@ -997,16 +997,27 @@ fn newline_after_brace_before_delim() { "#]]) } +// Copy operator can have single space or newline + #[test] -fn test() { +fn copy_operator_with_newline_is_indented() { check(indoc! {r#" - {} (); - {} [] + let x = arr + w/ 0 <- 10 + w/ 1 <- 11 "#}, &expect![[r#" - {} - (); - {} - [] + let x = arr + w/ 0 <- 10 + w/ 1 <- 11 + "#]]) +} + +#[test] +fn copy_operator_with_space_has_single_space() { + check(indoc! {r#" + let x = arr w/ 0 <- 10 w/ 1 <- 11 + "#}, &expect![[r#" + let x = arr w/ 0 <- 10 w/ 1 <- 11 "#]]) } From 4cecabc8473cd36832e82c5f88a97bc2325aa05e Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Fri, 22 Mar 2024 16:57:53 -0700 Subject: [PATCH 04/13] Fixed spacing for ellipse --- compiler/qsc_formatter/src/formatter.rs | 54 ++++- compiler/qsc_formatter/src/formatter/tests.rs | 107 +++++--- compiler/qsc_formatter/src/main.rs | 17 ++ format_all.ps1 | 12 + library/core/core.qs | 2 +- library/src/tests/resources/add_le.qs | 19 +- library/src/tests/resources/compare.qs | 29 +-- library/src/tests/resources/inc_by_le.qs | 30 +-- library/src/tests/resources/qft_le.qs | 25 +- library/src/tests/resources/select.qs | 4 +- .../src/tests/resources/state_preparation.qs | 24 +- library/std/arrays.qs | 91 ++++--- library/std/canon.qs | 45 ++-- library/std/convert.qs | 18 +- library/std/core.qs | 4 +- library/std/diagnostics.qs | 7 +- library/std/internal.qs | 81 +++---- library/std/intrinsic.qs | 229 ++++++------------ library/std/math.qs | 121 +++++---- library/std/measurement.qs | 12 +- library/std/re.qs | 8 +- library/std/unstable_arithmetic.qs | 106 ++++---- library/std/unstable_arithmetic_internal.qs | 108 ++++----- library/std/unstable_state_preparation.qs | 34 ++- library/std/unstable_table_lookup.qs | 34 +-- samples/algorithms/BernsteinVazirani.qs | 20 +- samples/algorithms/BernsteinVaziraniNISQ.qs | 18 +- samples/algorithms/BitFlipCode.qs | 17 +- samples/algorithms/DeutschJozsa.qs | 10 +- samples/algorithms/Entanglement.qs | 2 +- samples/algorithms/Grover.qs | 3 +- samples/algorithms/HiddenShift.qs | 14 +- samples/algorithms/HiddenShiftNISQ.qs | 11 +- samples/algorithms/Measurement.qs | 2 +- samples/algorithms/PhaseFlipCode.qs | 17 +- samples/algorithms/QRNG.qs | 2 +- samples/algorithms/RandomBit.qs | 2 +- samples/algorithms/Shor.qs | 73 +++--- samples/algorithms/SuperdenseCoding.qs | 3 +- samples/algorithms/Superposition.qs | 2 +- samples/algorithms/Teleportation.qs | 2 +- samples/estimation/Dynamics.qs | 38 ++- samples/estimation/EkeraHastadFactoring.qs | 10 +- samples/estimation/Precalculated.qs | 7 +- samples/estimation/ShorRE.qs | 31 +-- .../df-chemistry/src/df_chemistry.qs | 52 ++-- .../estimation/df-chemistry/src/prepare.qs | 47 ++-- samples/language/Comments.qs | 4 +- samples/language/ConditionalBranching.qs | 2 +- samples/language/EntryPoint.qs | 2 +- samples/language/ForLoops.qs | 6 +- samples/language/LambdaExpression.qs | 2 +- samples/language/MultiFileProject/src/Main.qs | 16 +- .../language/MultiFileProject/src/Particle.qs | 12 +- samples/language/Namespaces.qs | 2 +- samples/language/Operations.qs | 12 +- samples/language/Pauli.qs | 4 +- samples/language/QuantumMemory.qs | 2 +- samples/language/Qubit.qs | 4 +- samples/language/Range.qs | 2 +- samples/language/Result.qs | 2 +- samples/language/ReturnStatement.qs | 2 +- samples/language/Specializations.qs | 30 ++- samples/language/Unit.qs | 2 +- 64 files changed, 877 insertions(+), 833 deletions(-) create mode 100644 compiler/qsc_formatter/src/main.rs create mode 100644 format_all.ps1 diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index 6462337562..32d8c962b8 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -43,6 +43,7 @@ pub fn calculate_format_edits(code: &str) -> Vec { indent_level: 0, delim_newlines_stack: vec![], type_param_state: TypeParameterListState::NoState, + spec_decl_state: SpecDeclState::NoState, }; // The sliding window used is over three adjacent tokens @@ -143,6 +144,21 @@ enum TypeParameterListState { InTypeParamList, } +/// This is to keep track of whether or not the formatter +/// is currently processing a functor specialization +/// declaration. +#[derive(Clone, Copy)] +enum SpecDeclState { + /// Not in a location relevant to this state. + NoState, + /// Formatter is on the specialization keyword. + /// (it is the left-hand token) + OnSpecKeyword, + /// Formatter is on the specialization ellipse. + /// (it is the left-hand token) + OnEllipse, +} + /// Enum for a token's status as a delimiter. /// `<` and `>` are delimiters only with type-parameter lists, /// which is determined using the TypeParameterListState enum. @@ -185,6 +201,7 @@ struct Formatter<'a> { indent_level: usize, delim_newlines_stack: Vec, type_param_state: TypeParameterListState, + spec_decl_state: SpecDeclState, } impl<'a> Formatter<'a> { @@ -205,6 +222,8 @@ impl<'a> Formatter<'a> { let are_newlines_in_spaces = whitespace.contains('\n'); let does_right_required_newline = matches!(&right.kind, Syntax(cooked_right) if is_newline_keyword_or_ampersat(cooked_right)); + self.update_spec_decl_state(&left.kind); + let (left_delim_state, right_delim_state) = self.update_type_param_state(&left.kind, &right.kind); @@ -372,15 +391,23 @@ impl<'a> Formatter<'a> { | (_, String(StringToken::Interpolated(InterpolatedStart::RBrace, _))) => { effect_no_space(left, whitespace, right, &mut edits); } - (_, Open(Delim::Brace)) => { - // Special-case braces to always have a leading single space + (DotDotDot, _) if matches!(self.spec_decl_state, SpecDeclState::OnEllipse) => { + // Special-case specialization declaration ellipses to have a space after effect_single_space(left, whitespace, right, &mut edits); } + (_, Open(Delim::Brace)) => { + // Special-case braces to have a leading single space with values + if is_prefix(cooked_left) { + effect_no_space(left, whitespace, right, &mut edits); + } else { + effect_single_space(left, whitespace, right, &mut edits); + } + } (_, _) if matches!(right_delim_state, Delimiter::Open) => { // Otherwise, all open delims have the same logic if is_value_token_left(cooked_left, left_delim_state) || is_prefix(cooked_left) { - // i.e. foo() or { foo }[3] + // i.e. foo() or foo[3] effect_no_space(left, whitespace, right, &mut edits); } else { // i.e. let x = (1, 2, 3); @@ -442,6 +469,27 @@ impl<'a> Formatter<'a> { edits } + fn update_spec_decl_state(&mut self, left_kind: &ConcreteTokenKind) { + use qsc_frontend::keyword::Keyword; + use ConcreteTokenKind::*; + use TokenKind::*; + + match left_kind { + Comment => { + // Comments don't update state + } + Syntax(Keyword(Keyword::Body | Keyword::Adjoint | Keyword::Controlled)) => { + self.spec_decl_state = SpecDeclState::OnSpecKeyword; + } + Syntax(DotDotDot) if matches!(self.spec_decl_state, SpecDeclState::OnSpecKeyword) => { + self.spec_decl_state = SpecDeclState::OnEllipse; + } + _ => { + self.spec_decl_state = SpecDeclState::NoState; + } + } + } + /// Updates the type_param_state of the FormatterState based /// on the left and right token kinds. Returns the delimiter /// state of the left and right tokens. diff --git a/compiler/qsc_formatter/src/formatter/tests.rs b/compiler/qsc_formatter/src/formatter/tests.rs index 3071d6426f..1d8f9b9f66 100644 --- a/compiler/qsc_formatter/src/formatter/tests.rs +++ b/compiler/qsc_formatter/src/formatter/tests.rs @@ -904,121 +904,174 @@ fn preserve_string_indentation() { #[test] fn newline_after_brace_before_value() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } x - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } x - "#]]) + "#]], + ) } #[test] fn newline_after_brace_before_functor() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } Adjoint Foo(); - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } Adjoint Foo(); - "#]]) + "#]], + ) } #[test] fn newline_after_brace_before_not_keyword() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } not true - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } not true - "#]]) + "#]], + ) } #[test] fn newline_after_brace_before_starter_keyword() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } if true {} - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } if true {} - "#]]) + "#]], + ) } #[test] fn newline_after_brace_before_brace() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } {} - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } {} - "#]]) + "#]], + ) } #[test] fn space_after_brace_before_operator() { - check(indoc! {r#" + check( + indoc! {r#" { let x = 3; } + {} - "#}, &expect![[r#" + "#}, + &expect![[r#" { let x = 3; } + {} - "#]]) + "#]], + ) } #[test] fn newline_after_brace_before_delim() { - check(indoc! {r#" + check( + indoc! {r#" {} () {} [] - "#}, &expect![[r#" + "#}, + &expect![[r#" {} () {} [] - "#]]) + "#]], + ) } // Copy operator can have single space or newline #[test] fn copy_operator_with_newline_is_indented() { - check(indoc! {r#" + check( + indoc! {r#" let x = arr w/ 0 <- 10 w/ 1 <- 11 - "#}, &expect![[r#" + "#}, + &expect![[r#" let x = arr w/ 0 <- 10 w/ 1 <- 11 - "#]]) + "#]], + ) } #[test] fn copy_operator_with_space_has_single_space() { - check(indoc! {r#" + check( + indoc! {r#" let x = arr w/ 0 <- 10 w/ 1 <- 11 - "#}, &expect![[r#" + "#}, + &expect![[r#" let x = arr w/ 0 <- 10 w/ 1 <- 11 - "#]]) + "#]], + ) +} + +#[test] +fn no_space_around_ellipse() { + check( + indoc! {r#" + {} ... {} + "#}, + &expect![[r#" + {}...{} + "#]], + ) +} + +#[test] +fn single_space_after_spec_decl_ellipse() { + check( + indoc! {r#" + body ...auto + adjoint ...{} + "#}, + &expect![[r#" + body ... auto + adjoint ... {} + "#]], + ) } // Remove extra whitespace from start of code diff --git a/compiler/qsc_formatter/src/main.rs b/compiler/qsc_formatter/src/main.rs new file mode 100644 index 0000000000..d6ab177724 --- /dev/null +++ b/compiler/qsc_formatter/src/main.rs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::env; +mod formatter; +use formatter::format_str; + +fn main() { + let args: Vec = env::args().collect(); + let path = args.get(1).expect("expected path to file to format"); + // read file from `path` into buffer + let file_as_string = std::fs::read_to_string(path).expect("file not found"); + // format the buffer + let formatted = format_str(&file_as_string); + // write the formatted buffer back to `path` + std::fs::write(path, formatted).expect("could not write to file"); +} diff --git a/format_all.ps1 b/format_all.ps1 new file mode 100644 index 0000000000..b9077ab541 --- /dev/null +++ b/format_all.ps1 @@ -0,0 +1,12 @@ +Get-ChildItem -Recurse .\samples -Filter *.qs | +ForEach-Object { + #cargo run --bin qsc_formatter $_.FullName + .\target\release\qsc_formatter.exe $_.FullName +} + +Get-ChildItem -Recurse .\library -Filter *.qs | +ForEach-Object { + #cargo run --bin qsc_formatter $_.FullName + .\target\release\qsc_formatter.exe $_.FullName +} + diff --git a/library/core/core.qs b/library/core/core.qs index 9e30481278..b8abde5509 100644 --- a/library/core/core.qs +++ b/library/core/core.qs @@ -38,7 +38,7 @@ namespace Microsoft.Quantum.Core { } mutable output = []; - for _ in 1 .. length { + for _ in 1..length { set output += [value]; } diff --git a/library/src/tests/resources/add_le.qs b/library/src/tests/resources/add_le.qs index 948e57b5dc..e9b8b6c522 100644 --- a/library/src/tests/resources/add_le.qs +++ b/library/src/tests/resources/add_le.qs @@ -8,7 +8,8 @@ namespace Test { adder : (Qubit[], Qubit[], Qubit[]) => Unit, xLen : Int, yLen : Int, - zLen : Int) : Unit { + zLen : Int + ) : Unit { use x = Qubit[xLen]; use y = Qubit[yLen]; @@ -25,12 +26,9 @@ namespace Test { let zActual = MeasureInteger(z); let zExpected = (xValue + yValue) % (1 <<< zLen); - Fact(xActual == xValue, - $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); - Fact(yActual == yValue, - $"{name}: Incorrect y={yActual}, expected={yValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); - Fact(zActual == zExpected, - $"{name}: Incorrect z={zActual}, expected={zExpected}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); + Fact(xActual == xValue, $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); + Fact(yActual == yValue, $"{name}: Incorrect y={yActual}, expected={yValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); + Fact(zActual == zExpected, $"{name}: Incorrect z={zActual}, expected={zExpected}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); ResetAll(x); ResetAll(y); @@ -42,11 +40,12 @@ namespace Test { internal operation TestAddLE( name : String, adder : (Qubit[], Qubit[], Qubit[]) => Unit, - bitwidth : Int) : Unit { + bitwidth : Int + ) : Unit { TestAddLE3(name, adder, bitwidth, bitwidth, bitwidth); - TestAddLE3(name, adder, bitwidth, bitwidth, bitwidth+1); - TestAddLE3(name, adder, bitwidth, bitwidth, bitwidth+2); + TestAddLE3(name, adder, bitwidth, bitwidth, bitwidth + 1); + TestAddLE3(name, adder, bitwidth, bitwidth, bitwidth + 2); } diff --git a/library/src/tests/resources/compare.qs b/library/src/tests/resources/compare.qs index 6b85f448b7..74baf92e3a 100644 --- a/library/src/tests/resources/compare.qs +++ b/library/src/tests/resources/compare.qs @@ -4,23 +4,24 @@ namespace Test { open Microsoft.Quantum.Diagnostics; internal operation CompareWithBigInt( - name: String, + name : String, bitwidth : Int, quantumComparator : (BigInt, Qubit[], Qubit) => Unit, - classicalComparator : (Int, Int) -> Bool) : Unit { - + classicalComparator : (Int, Int) -> Bool + ) : Unit { + for n in 1..bitwidth { use qs = Qubit[n]; use t = Qubit(); - for a in 0 .. 2^n+1 { // We want b to have more bits sometimes... - for b in 0 .. 2^n-1 { + for a in 0..2 ^ n + 1 { + // We want b to have more bits sometimes... + for b in 0..2 ^ n-1 { ApplyXorInPlace(b, qs); quantumComparator(IntAsBigInt(a), qs, t); let actual = MResetZ(t) == One; let expected = classicalComparator(a, b); - Fact(actual == expected, - $"{name}: Wrong result {actual}, expected {expected}. bitwidth={n}, a={a}, b={b}."); + Fact(actual == expected, $"{name}: Wrong result {actual}, expected {expected}. bitwidth={n}, a={a}, b={b}."); ResetAll(qs); } } @@ -28,25 +29,25 @@ namespace Test { } internal operation CompareWithLE( - name: String, + name : String, bitwidth : Int, quantumComparator : (Qubit[], Qubit[], Qubit) => Unit, - classicalComparator : (Int, Int) -> Bool) : Unit { - + classicalComparator : (Int, Int) -> Bool + ) : Unit { + for n in 1..bitwidth { use x = Qubit[n]; use y = Qubit[n]; use t = Qubit(); - for a in 0 .. 2^n-1 { - for b in 0 .. 2^n-1 { + for a in 0..2 ^ n-1 { + for b in 0..2 ^ n-1 { ApplyXorInPlace(a, x); ApplyXorInPlace(b, y); quantumComparator(x, y, t); let actual = MResetZ(t) == One; let expected = classicalComparator(a, b); - Fact(actual == expected, - $"{name}: Wrong result {actual}, expected {expected}. bitwidth={n}, a={a}, b={b}."); + Fact(actual == expected, $"{name}: Wrong result {actual}, expected {expected}. bitwidth={n}, a={a}, b={b}."); ResetAll(x); ResetAll(y); } diff --git a/library/src/tests/resources/inc_by_le.qs b/library/src/tests/resources/inc_by_le.qs index d8c54161a0..5f12d11b0f 100644 --- a/library/src/tests/resources/inc_by_le.qs +++ b/library/src/tests/resources/inc_by_le.qs @@ -7,7 +7,8 @@ namespace Test { name : String, adder : (Qubit[], Qubit[]) => Unit, xLen : Int, - yLen : Int) : Unit { + yLen : Int + ) : Unit { use x = Qubit[xLen]; use y = Qubit[yLen]; @@ -22,10 +23,8 @@ namespace Test { let xActual = MeasureInteger(x); let yExpected = (xValue + yValue) % (1 <<< yLen); - Fact(yActual == yExpected, - $"{name}: Incorrect sum={yActual}, expected={yExpected}. |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); - Fact(xActual == xValue, - $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); + Fact(yActual == yExpected, $"{name}: Incorrect sum={yActual}, expected={yExpected}. |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); + Fact(xActual == xValue, $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); ResetAll(x); ResetAll(y); @@ -37,7 +36,8 @@ namespace Test { name : String, adder : (Qubit[], Qubit[]) => Unit is Ctl, xLen : Int, - yLen : Int) : Unit { + yLen : Int + ) : Unit { use ctl = Qubit(); use x = Qubit[xLen]; @@ -57,11 +57,9 @@ namespace Test { let xActual = MeasureInteger(x); let yExpected = isCtl ? (xValue + yValue) % (1 <<< yLen) | yValue; - Fact(yActual == yExpected, - $"{name}: Incorrect sum={yActual}, expected={yExpected}. ctl={isCtl}, |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); - Fact(xActual == xValue, - $"{name}: Incorrect x={xActual}, expected={xValue}. ctl={isCtl}, |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); - + Fact(yActual == yExpected, $"{name}: Incorrect sum={yActual}, expected={yExpected}. ctl={isCtl}, |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); + Fact(xActual == xValue, $"{name}: Incorrect x={xActual}, expected={xValue}. ctl={isCtl}, |x|={xLen}, |y|={yLen}, x={xValue}, y={yValue}."); + ResetAll(x); ResetAll(y); Reset(ctl); @@ -73,17 +71,19 @@ namespace Test { internal operation TestIncByLE( name : String, adder : (Qubit[], Qubit[]) => Unit, - bitwidth : Int) : Unit { + bitwidth : Int + ) : Unit { TestIncByLE2(name, adder, bitwidth, bitwidth); - TestIncByLE2(name, adder, bitwidth, bitwidth+1); - TestIncByLE2(name, adder, bitwidth, bitwidth+2); + TestIncByLE2(name, adder, bitwidth, bitwidth + 1); + TestIncByLE2(name, adder, bitwidth, bitwidth + 2); } internal operation TestIncByLECtl( name : String, adder : (Qubit[], Qubit[]) => Unit is Ctl, - bitwidth : Int) : Unit { + bitwidth : Int + ) : Unit { TestIncByLECtl2(name, adder, bitwidth, bitwidth); } diff --git a/library/src/tests/resources/qft_le.qs b/library/src/tests/resources/qft_le.qs index 9c1341e687..ab229c7816 100644 --- a/library/src/tests/resources/qft_le.qs +++ b/library/src/tests/resources/qft_le.qs @@ -2,21 +2,22 @@ namespace Test { open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Arrays; - operation PrepareEntangledState ( + operation PrepareEntangledState( left : Qubit[], - right : Qubit[]) : Unit is Adj + Ctl { + right : Qubit[] + ) : Unit is Adj + Ctl { - for idxQubit in 0 .. Length(left) - 1 - { + for idxQubit in 0..Length(left) - 1 { H(left[idxQubit]); Controlled X([left[idxQubit]], right[idxQubit]); } } - operation AssertOperationsEqualReferenced ( + operation AssertOperationsEqualReferenced( nQubits : Int, actual : (Qubit[] => Unit), - expected : (Qubit[] => Unit is Adj)) : Unit { + expected : (Qubit[] => Unit is Adj) + ) : Unit { // Prepare a reference register entangled with the target register. use (reference, target) = (Qubit[nQubits], Qubit[nQubits]) { @@ -33,14 +34,14 @@ namespace Test { /// # Summary /// Hard-code 1 qubit QFT - operation QFT1 (target : Qubit[]) : Unit is Adj { + operation QFT1(target : Qubit[]) : Unit is Adj { Fact(Length(target) == 1, $"`Length(target!)` must be 1"); H((target)[0]); } /// # Summary /// Hard-code 2 qubit QFT - operation QFT2 (target : Qubit[]) : Unit is Adj { + operation QFT2(target : Qubit[]) : Unit is Adj { Fact(Length(target) == 2, $"`Length(target!)` must be 2"); let (q1, q2) = ((target)[0], (target)[1]); H(q1); @@ -50,7 +51,7 @@ namespace Test { /// # Summary /// Hard-code 3 qubit QFT - operation QFT3 (target : Qubit[]) : Unit is Adj { + operation QFT3(target : Qubit[]) : Unit is Adj { Fact(Length(target) == 3, $"`Length(target)` must be 3"); let (q1, q2, q3) = ((target)[0], (target)[1], (target)[2]); H(q1); @@ -63,7 +64,7 @@ namespace Test { /// # Summary /// Hard-code 4 qubit QFT - operation QFT4 (target : Qubit[]) : Unit is Adj { + operation QFT4(target : Qubit[]) : Unit is Adj { Fact(Length(target) == 4, $"`Length(target!)` must be 4"); let (q1, q2, q3, q4) = ((target)[0], (target)[1], (target)[2], (target)[3]); H(q1); @@ -80,8 +81,8 @@ namespace Test { /// # Summary /// Compares QFT to the hard-coded implementations - operation TestQFT(n: Int) : Unit { - Fact(n>=1 and n<=4, "Only have four tests for QFT."); + operation TestQFT(n : Int) : Unit { + Fact(n >= 1 and n <= 4, "Only have four tests for QFT."); let testOperations = [QFT1, QFT2, QFT3, QFT4]; AssertOperationsEqualReferenced(n, testOperations[n-1], q => ApplyQFT(Reversed(q))); } diff --git a/library/src/tests/resources/select.qs b/library/src/tests/resources/select.qs index 08087539ad..ceb035e149 100644 --- a/library/src/tests/resources/select.qs +++ b/library/src/tests/resources/select.qs @@ -10,7 +10,7 @@ namespace Test { use temporaryRegister = Qubit[dataBits]; use dataRegister = Qubit[dataBits]; - let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), 2^addressBits, 0); + let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), 2 ^ addressBits, 0); for (index, expected) in Enumerated(data) { ApplyXorInPlace(index, addressRegister); @@ -32,7 +32,7 @@ namespace Test { for _ in 1..rounds { let addressBits = DrawRandomInt(2, 6); let dataBits = 10; - let numData = DrawRandomInt(2^(addressBits - 1) + 1, 2^addressBits - 1); + let numData = DrawRandomInt(2 ^ (addressBits - 1) + 1, 2 ^ addressBits - 1); let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), numData, 0); diff --git a/library/src/tests/resources/state_preparation.qs b/library/src/tests/resources/state_preparation.qs index 3c80bb6934..9332382975 100644 --- a/library/src/tests/resources/state_preparation.qs +++ b/library/src/tests/resources/state_preparation.qs @@ -6,7 +6,7 @@ namespace Test { open Microsoft.Quantum.Unstable.StatePreparation; - operation TestPlusState(): Unit { + operation TestPlusState() : Unit { use q = Qubit(); PreparePureStateD([Sqrt(0.5), Sqrt(0.5)], [q]); DumpMachine(); @@ -14,7 +14,7 @@ namespace Test { H(q); } - operation TestMinusState(): Unit { + operation TestMinusState() : Unit { use q = Qubit(); PreparePureStateD([Sqrt(0.5), -Sqrt(0.5)], [q]); DumpMachine(); @@ -23,7 +23,7 @@ namespace Test { X(q); } - operation TestBellState(): Unit { + operation TestBellState() : Unit { use q = Qubit[2]; PreparePureStateD([Sqrt(0.5), 0.0, 0.0, Sqrt(0.5)], q); DumpMachine(); @@ -32,7 +32,7 @@ namespace Test { H(q[0]); } - operation TestCat3State(): Unit { + operation TestCat3State() : Unit { use q = Qubit[3]; PreparePureStateD([Sqrt(0.5), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Sqrt(0.5)], q); DumpMachine(); @@ -49,18 +49,18 @@ namespace Test { T(qs[1]); } - operation TestPrepareComplex(): Unit { + operation TestPrepareComplex() : Unit { use q = Qubit[2]; let c00 = ComplexPolar(0.5, 0.0); - let c01 = ComplexPolar(0.5, PI()/4.0); - let c10 = ComplexPolar(0.5, PI()/2.0); - let c11 = ComplexPolar(0.5, 3.0*PI()/4.0); + let c01 = ComplexPolar(0.5, PI() / 4.0); + let c10 = ComplexPolar(0.5, PI() / 2.0); + let c11 = ComplexPolar(0.5, 3.0 * PI() / 4.0); ApproximatelyPreparePureStateCP(0.0, [c00, c01, c10, c11], q); DumpMachine(); Adjoint PrepareComplex(q); } - operation TestPreparationCompletion(): Unit { + operation TestPreparationCompletion() : Unit { let testCases = [ // Test positive coefficients [0.773761, 0.633478], @@ -83,7 +83,7 @@ namespace Test { for coefficients in testCases { let L = Length(coefficients); - let N = Ceiling(Log(IntAsDouble(L))/LogOf2() - 0.001); + let N = Ceiling(Log(IntAsDouble(L)) / LogOf2() - 0.001); use q = Qubit[N]; PreparePureStateD(coefficients, q); DumpMachine(); @@ -91,10 +91,10 @@ namespace Test { } } - operation TestEndianness(): Unit { + operation TestEndianness() : Unit { let n = 4; use qs = Qubit[n]; - let bitsize = 2^n; + let bitsize = 2 ^ n; for i in 0..bitsize-1 { mutable c = Repeated(0.0, bitsize); set c w/= i <- 1.0; diff --git a/library/std/arrays.qs b/library/std/arrays.qs index 0b7b08ce2a..b8b8211ee7 100644 --- a/library/std/arrays.qs +++ b/library/std/arrays.qs @@ -28,7 +28,7 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let allNonZero = All(x -> x != 0, [1, 2, 3, 4, 5]); /// ``` - function All<'T> (predicate : ('T -> Bool), array : 'T[]) : Bool { + function All<'T>(predicate : ('T -> Bool), array : 'T[]) : Bool { for element in array { if not predicate(element) { return false; @@ -60,7 +60,7 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let anyEven = Any(x -> x % 2 == 0, [1, 3, 6, 7, 9]); /// ``` - function Any<'T> (predicate : ('T -> Bool), array : 'T[]) : Bool { + function Any<'T>(predicate : ('T -> Bool), array : 'T[]) : Bool { for element in array { if predicate(element) { return true; @@ -125,7 +125,7 @@ namespace Microsoft.Quantum.Arrays { /// // The following line returns [12, 10, 11]. /// let output = CircularlyShifted(-2, array); /// ``` - function CircularlyShifted<'T> (stepCount : Int, array : 'T[]) : 'T[] { + function CircularlyShifted<'T>(stepCount : Int, array : 'T[]) : 'T[] { let arrayLength = Length(array); if arrayLength <= 1 { return array; @@ -246,7 +246,7 @@ namespace Microsoft.Quantum.Arrays { let columns = rows == 0 ? 0 | Length(Head(matrix)); let rangeLimit = MinI(rows, columns) - 1; mutable diagonal = []; - for index in 0 .. rangeLimit { + for index in 0..rangeLimit { set diagonal += [matrix[index][index]]; } @@ -277,10 +277,9 @@ namespace Microsoft.Quantum.Arrays { /// use qubit = Qubit(); /// let results = Microsoft.Quantum.Arrays.DrawMany(q => {X(q); M(q)}, 3, qubit); /// ``` - operation DrawMany<'TInput, 'TOutput>(op : ('TInput => 'TOutput), nSamples : Int, input : 'TInput) - : 'TOutput[] { + operation DrawMany<'TInput, 'TOutput>(op : ('TInput => 'TOutput), nSamples : Int, input : 'TInput) : 'TOutput[] { mutable outputs = []; - for _ in 1 .. nSamples { + for _ in 1..nSamples { set outputs += [op(input)]; } outputs @@ -349,7 +348,7 @@ namespace Microsoft.Quantum.Arrays { set toKeep w/= indexToRemove <- false; } mutable output = []; - for index in 0 .. arrayLength - 1 { + for index in 0..arrayLength - 1 { if toKeep[index] { set output += [array[index]]; } @@ -478,7 +477,7 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let sum = Fold((x, y) -> x + y, 0, [1, 2, 3, 4, 5]); // `sum` is 15. /// ``` - function Fold<'State, 'T> (folder : (('State, 'T) -> 'State), state : 'State, array : 'T[]) : 'State { + function Fold<'State, 'T>(folder : (('State, 'T) -> 'State), state : 'State, array : 'T[]) : 'State { mutable current = state; for element in array { set current = folder(current, element); @@ -508,7 +507,7 @@ namespace Microsoft.Quantum.Arrays { /// /// # See Also /// - Microsoft.Quantum.Arrays.Mapped - operation ForEach<'T, 'U> (action : ('T => 'U), array : 'T[]) : 'U[] { + operation ForEach<'T, 'U>(action : ('T => 'U), array : 'T[]) : 'U[] { mutable output = []; for element in array { set output += [action(element)]; @@ -529,7 +528,7 @@ namespace Microsoft.Quantum.Arrays { /// /// # Output /// The first element of the array. - function Head<'A> (array : 'A[]) : 'A { + function Head<'A>(array : 'A[]) : 'A { Fact(Length(array) > 0, "Array must have at least 1 element"); array[0] } @@ -572,7 +571,7 @@ namespace Microsoft.Quantum.Arrays { /// // `indexOfFirstEven` is 3. /// ``` function IndexOf<'T>(predicate : ('T -> Bool), array : 'T[]) : Int { - for index in 0 .. Length(array) - 1 { + for index in 0..Length(array) - 1 { if predicate(array[index]) { return index; } @@ -602,7 +601,7 @@ namespace Microsoft.Quantum.Arrays { /// for idx in 0 .. Length(array) - 1 { ... } /// ``` function IndexRange<'TElement>(array : 'TElement[]) : Range { - 0 .. Length(array) - 1 + 0..Length(array) - 1 } /// # Summary @@ -640,15 +639,14 @@ namespace Microsoft.Quantum.Arrays { let secondLength = Length(second); Fact( firstLength == secondLength or firstLength == secondLength + 1, - "Array `first` must either be of same size as `second` or have one more element"); + "Array `first` must either be of same size as `second` or have one more element" + ); let interleavedLength = firstLength + secondLength; mutable interleaved = []; for index in 0..interleavedLength - 1 { let originalIndex = index / 2; - let value = - if index % 2 == 0 {first[originalIndex]} - else {second[originalIndex]}; + let value = if index % 2 == 0 { first[originalIndex] } else { second[originalIndex] }; set interleaved += [value]; } interleaved @@ -693,7 +691,7 @@ namespace Microsoft.Quantum.Arrays { function IsRectangularArray<'T>(array : 'T[][]) : Bool { if (Length(array) > 0) { let columnCount = Length(Head(array)); - for index in 1 .. Length(array) - 1 { + for index in 1..Length(array) - 1 { if Length(array[index]) != columnCount { return false; } @@ -727,7 +725,7 @@ namespace Microsoft.Quantum.Arrays { /// if `comparison(a, b)` and `comparison(b, c)`, then `comparison(a, c)` /// is assumed. function IsSorted<'T>(comparison : (('T, 'T) -> Bool), array : 'T[]) : Bool { - for index in 1 .. Length(array) - 1 { + for index in 1..Length(array) - 1 { if not comparison(array[index - 1], array[index]) { return false; } @@ -793,7 +791,7 @@ namespace Microsoft.Quantum.Arrays { /// /// # See Also /// - Microsoft.Quantum.Arrays.ForEach - function Mapped<'T, 'U> (mapper : ('T -> 'U), array : 'T[]) : 'U[] { + function Mapped<'T, 'U>(mapper : ('T -> 'U), array : 'T[]) : 'U[] { mutable mapped = []; for element in array { set mapped += [mapper(element)]; @@ -827,16 +825,16 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let array = MappedByIndex(f, [x0, x1, x2]); /// ``` - /// and - /// ```qsharp + /// and + /// ```qsharp /// let array = [f(0, x0), f(1, x1), f(2, x2)]; /// ``` /// /// # See Also /// - Microsoft.Quantum.Arrays.Mapped - function MappedByIndex<'T, 'U> (mapper : ((Int, 'T) -> 'U), array : 'T[]) : 'U[] { + function MappedByIndex<'T, 'U>(mapper : ((Int, 'T) -> 'U), array : 'T[]) : 'U[] { mutable mapped = []; - for index in 0 .. Length(array) - 1 { + for index in 0..Length(array) - 1 { set mapped += [mapper(index, array[index])]; } mapped @@ -869,7 +867,7 @@ namespace Microsoft.Quantum.Arrays { /// /// # See Also /// - Microsoft.Quantum.Arrays.Mapped - function MappedOverRange<'T> (mapper : (Int -> 'T), range : Range) : 'T[] { + function MappedOverRange<'T>(mapper : (Int -> 'T), range : Range) : 'T[] { mutable output = []; for element in range { set output += [mapper(element)]; @@ -891,8 +889,8 @@ namespace Microsoft.Quantum.Arrays { /// /// # Output /// An array containing the elements `array[0..Length(array) - 2]`. - function Most<'T> (array : 'T[]) : 'T[] { - array[... Length(array) - 2] + function Most<'T>(array : 'T[]) : 'T[] { + array[...Length(array) - 2] } /// # Summary @@ -942,7 +940,7 @@ namespace Microsoft.Quantum.Arrays { /// // The following line returns [2, 2, 10, 12, 15]. /// let output = Padded(5, 2, array); /// ``` - function Padded<'T> (paddedLength : Int, defaultElement : 'T, inputArray : 'T[]) : 'T[] { + function Padded<'T>(paddedLength : Int, defaultElement : 'T, inputArray : 'T[]) : 'T[] { let nElementsInitial = Length(inputArray); let nAbsElementsTotal = AbsI(paddedLength); if nAbsElementsTotal < nElementsInitial { @@ -990,10 +988,10 @@ namespace Microsoft.Quantum.Arrays { if partitionEndIndex >= Length(array) { fail "Partitioned argument out of bounds."; } - set output w/= index <- array[partitionStartIndex .. partitionEndIndex]; + set output w/= index <- array[partitionStartIndex..partitionEndIndex]; set partitionStartIndex = partitionEndIndex + 1; } - set output w/= Length(partitionSizes) <- array[partitionStartIndex .. Length(array) - 1]; + set output w/= Length(partitionSizes) <- array[partitionStartIndex..Length(array) - 1]; output } @@ -1011,8 +1009,8 @@ namespace Microsoft.Quantum.Arrays { /// /// # Output /// An array containing the elements `array[1..Length(array) - 1]`. - function Rest<'T> (array : 'T[]) : 'T[] { - array[1 ...] + function Rest<'T>(array : 'T[]) : 'T[] { + array[1...] } /// # Summary @@ -1030,7 +1028,7 @@ namespace Microsoft.Quantum.Arrays { /// # Output /// An array containing the elements `array[Length(array) - 1]` .. `array[0]`. function Reversed<'T>(array : 'T[]) : 'T[] { - array[... -1 ...] + array[... -1...] } /// # Summary @@ -1055,10 +1053,10 @@ namespace Microsoft.Quantum.Arrays { /// let numbers = SequenceI(0, _); // function to create sequence from 0 to `to` /// let naturals = SequenceI(1, _); // function to create sequence from 1 to `to` /// ``` - function SequenceI (from : Int, to : Int) : Int[] { + function SequenceI(from : Int, to : Int) : Int[] { Fact(to >= from, $"`to` must be larger than `from`."); mutable array = []; - for index in from .. to { + for index in from..to { set array += [index]; } array @@ -1086,7 +1084,7 @@ namespace Microsoft.Quantum.Arrays { /// let arr2 = SequenceL(23L, 29L); // [23L, 24L, 25L, 26L, 27L, 28L, 29L] /// let arr3 = SequenceL(-5L, -2L); // [-5L, -4L, -3L, -2L] /// ``` - function SequenceL (from : BigInt, to : BigInt) : BigInt[] { + function SequenceL(from : BigInt, to : BigInt) : BigInt[] { Fact(to >= from, "`to` must be larger than `from`"); mutable array = []; mutable current = from; @@ -1200,7 +1198,7 @@ namespace Microsoft.Quantum.Arrays { /// let permutation = Subarray([3, 0, 2, 1], array); // [4, 1, 3, 2] /// let duplicates = Subarray([1, 2, 2], array); // [2, 3, 3] /// ``` - function Subarray<'T> (locations : Int[], array : 'T[]) : 'T[] { + function Subarray<'T>(locations : Int[], array : 'T[]) : 'T[] { mutable subarray = []; for location in locations { set subarray += [array[location]]; @@ -1269,9 +1267,9 @@ namespace Microsoft.Quantum.Arrays { Fact(columnCount > 0, "Matrix must have at least 1 column"); Fact(IsRectangularArray(matrix), "Matrix is not a rectangular array"); mutable transposed = []; - for columnIndex in 0 .. columnCount - 1 { + for columnIndex in 0..columnCount - 1 { mutable newRow = []; - for rowIndex in 0 .. rowCount - 1 { + for rowIndex in 0..rowCount - 1 { set newRow += [matrix[rowIndex][columnIndex]]; } set transposed += [newRow]; @@ -1292,7 +1290,7 @@ namespace Microsoft.Quantum.Arrays { /// /// # Output /// The last element of the array. - function Tail<'A> (array : 'A[]) : 'A { + function Tail<'A>(array : 'A[]) : 'A { let size = Length(array); Fact(size > 0, "Array must have at least 1 element"); array[size - 1] @@ -1327,7 +1325,7 @@ namespace Microsoft.Quantum.Arrays { function Unzipped<'T, 'U>(array : ('T, 'U)[]) : ('T[], 'U[]) { mutable first = []; mutable second = []; - for index in 0 .. Length(array) - 1 { + for index in 0..Length(array) - 1 { let (left, right) = array[index]; set first += [left]; set second += [right]; @@ -1353,7 +1351,7 @@ namespace Microsoft.Quantum.Arrays { /// An array of indices where `predicate` is true. function Where<'T>(predicate : ('T -> Bool), array : 'T[]) : Int[] { mutable indexes = []; - for index in 0 .. Length(array) - 1 { + for index in 0..Length(array) - 1 { if predicate(array[index]) { set indexes += [index]; } @@ -1393,11 +1391,12 @@ namespace Microsoft.Quantum.Arrays { let arrayLength = Length(array); Fact( size > 0 or size <= arrayLength, - "The size of the window must be a positive integer no greater than the size of the array"); + "The size of the window must be a positive integer no greater than the size of the array" + ); mutable windows = []; - for index in 0 .. arrayLength - size { - set windows += [array[index .. index + size - 1]]; + for index in 0..arrayLength - size { + set windows += [array[index..index + size - 1]]; } windows } @@ -1435,7 +1434,7 @@ namespace Microsoft.Quantum.Arrays { function Zipped<'T, 'U>(left : 'T[], right : 'U[]) : ('T, 'U)[] { let arrayLength = MinI(Length(left), Length(right)); mutable zipped = []; - for index in 0 .. arrayLength - 1 { + for index in 0..arrayLength - 1 { set zipped += [(left[index], right[index])]; } zipped diff --git a/library/std/canon.qs b/library/std/canon.qs index 244b914d63..7371e9e3d3 100644 --- a/library/std/canon.qs +++ b/library/std/canon.qs @@ -26,7 +26,7 @@ namespace Microsoft.Quantum.Canon { /// use register = Qubit[3]; /// ApplyToEach(H, register); /// ``` - operation ApplyToEach<'T> (singleElementOperation : ('T => Unit), register : 'T[]) : Unit { + operation ApplyToEach<'T>(singleElementOperation : ('T => Unit), register : 'T[]) : Unit { for item in register { singleElementOperation(item); } @@ -55,8 +55,7 @@ namespace Microsoft.Quantum.Canon { /// /// # See Also /// - Microsoft.Quantum.Canon.ApplyToEach - operation ApplyToEachA<'T> (singleElementOperation : ('T => Unit is Adj), register : 'T[]) - : Unit is Adj { + operation ApplyToEachA<'T>(singleElementOperation : ('T => Unit is Adj), register : 'T[]) : Unit is Adj { for item in register { singleElementOperation(item); } @@ -85,8 +84,7 @@ namespace Microsoft.Quantum.Canon { /// /// # See Also /// - Microsoft.Quantum.Canon.ApplyToEach - operation ApplyToEachC<'T> (singleElementOperation : ('T => Unit is Ctl), register : 'T[]) - : Unit is Ctl { + operation ApplyToEachC<'T>(singleElementOperation : ('T => Unit is Ctl), register : 'T[]) : Unit is Ctl { for item in register { singleElementOperation(item); } @@ -115,8 +113,7 @@ namespace Microsoft.Quantum.Canon { /// /// # See Also /// - Microsoft.Quantum.Canon.ApplyToEach - operation ApplyToEachCA<'T> (singleElementOperation : ('T => Unit is Adj + Ctl), register : 'T[]) - : Unit is Adj + Ctl { + operation ApplyToEachCA<'T>(singleElementOperation : ('T => Unit is Adj + Ctl), register : 'T[]) : Unit is Adj + Ctl { for item in register { singleElementOperation(item); } @@ -153,7 +150,7 @@ namespace Microsoft.Quantum.Canon { /// ```qsharp /// CNOT(control, target); /// ``` - operation CX(control : Qubit, target : Qubit) : Unit is Adj + Ctl{ + operation CX(control : Qubit, target : Qubit) : Unit is Adj + Ctl { body ... { __quantum__qis__cx__body(control, target); } @@ -188,7 +185,7 @@ namespace Microsoft.Quantum.Canon { /// ```qsharp /// Controlled Y([control], target); /// ``` - operation CY(control : Qubit, target : Qubit) : Unit is Adj + Ctl{ + operation CY(control : Qubit, target : Qubit) : Unit is Adj + Ctl { body ... { __quantum__qis__cy__body(control, target); } @@ -234,13 +231,13 @@ namespace Microsoft.Quantum.Canon { } /// Given a pair, returns its first element. - function Fst<'T, 'U> (pair : ('T, 'U)) : 'T { + function Fst<'T, 'U>(pair : ('T, 'U)) : 'T { let (fst, _) = pair; return fst; } /// Given a pair, returns its second element. - function Snd<'T, 'U> (pair : ('T, 'U)) : 'U { + function Snd<'T, 'U>(pair : ('T, 'U)) : 'U { let (_, snd) = pair; return snd; } @@ -263,7 +260,7 @@ namespace Microsoft.Quantum.Canon { /// $$ operation ApplyCNOTChain(qubits : Qubit[]) : Unit is Adj + Ctl { for i in 0..Length(qubits)-2 { - CNOT(qubits[i], qubits[i+1]); + CNOT(qubits[i], qubits[i + 1]); } } @@ -287,9 +284,7 @@ namespace Microsoft.Quantum.Canon { /// X(q); /// ``` operation ApplyP(pauli : Pauli, target : Qubit) : Unit is Adj + Ctl { - if pauli == PauliX { X(target); } - elif pauli == PauliY { Y(target); } - elif pauli == PauliZ { Z(target); } + if pauli == PauliX { X(target); } elif pauli == PauliY { Y(target); } elif pauli == PauliZ { Z(target); } } /// # Summary @@ -347,8 +342,7 @@ namespace Microsoft.Quantum.Canon { /// // Apply when index in `bits` is `false`. /// ApplyPauliFromBitString(PauliZ, false, bits, qubits); /// ``` - operation ApplyPauliFromBitString(pauli : Pauli, bitApply : Bool, bits : Bool[], qubits : Qubit[]) - : Unit is Adj + Ctl { + operation ApplyPauliFromBitString(pauli : Pauli, bitApply : Bool, bits : Bool[], qubits : Qubit[]) : Unit is Adj + Ctl { let nBits = Length(bits); Fact(nBits == Length(qubits), "Number of control bits must be equal to number of control qubits."); for i in 0..nBits-1 { @@ -387,7 +381,8 @@ namespace Microsoft.Quantum.Canon { pauli : Pauli, bitApply : Bool, numberState : Int, - qubits : Qubit[]) : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { let length = Length(qubits); Fact(numberState >= 0, "number must be non-negative"); @@ -426,7 +421,8 @@ namespace Microsoft.Quantum.Canon { numberState : Int, oracle : ('T => Unit is Adj + Ctl), controlRegister : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { within { ApplyPauliFromInt(PauliX, false, numberState, controlRegister); @@ -461,7 +457,8 @@ namespace Microsoft.Quantum.Canon { bits : Bool[], oracle : ('T => Unit is Adj + Ctl), controlRegister : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { // The control register must have enough bits to implement the requested control. Fact(Length(bits) <= Length(controlRegister), "Control register shorter than control pattern."); @@ -491,13 +488,13 @@ namespace Microsoft.Quantum.Canon { /// /// # Reference /// - [Quantum Fourier transform](https://en.wikipedia.org/wiki/Quantum_Fourier_transform) - operation ApplyQFT (qs : Qubit[]) : Unit is Adj + Ctl { + operation ApplyQFT(qs : Qubit[]) : Unit is Adj + Ctl { let length = Length(qs); Fact(length >= 1, "ApplyQFT: Length(qs) must be at least 1."); for i in length-1..-1..0 { H(qs[i]); for j in 0..i-1 { - Controlled R1Frac([qs[i]], (1, j+1, qs[i-j-1])); + Controlled R1Frac([qs[i]], (1, j + 1, qs[i-j-1])); } } } @@ -508,9 +505,9 @@ namespace Microsoft.Quantum.Canon { /// # Input /// ## register /// The qubits order of which should be reversed using SWAP gates - operation SwapReverseRegister (register : Qubit[]) : Unit is Adj + Ctl { + operation SwapReverseRegister(register : Qubit[]) : Unit is Adj + Ctl { let length = Length(register); - for i in 0 .. length/2 - 1 { + for i in 0..length / 2 - 1 { SWAP(register[i], register[(length - i) - 1]); } } diff --git a/library/std/convert.qs b/library/std/convert.qs index 0f75aeb1f6..a2fa592395 100644 --- a/library/std/convert.qs +++ b/library/std/convert.qs @@ -44,7 +44,7 @@ namespace Microsoft.Quantum.Convert { /// A `Result` representing the `input`. @Config(Unrestricted) function BoolAsResult(input : Bool) : Result { - if input {One} else {Zero} + if input { One } else { Zero } } /// # Summary @@ -58,7 +58,7 @@ namespace Microsoft.Quantum.Convert { Fact(nBits < 64, $"`Length(bits)` must be less than 64, but was {nBits}."); mutable number = 0; - for i in 0 .. nBits - 1 { + for i in 0..nBits - 1 { if (bits[i]) { set number |||= 1 <<< i; } @@ -89,7 +89,7 @@ namespace Microsoft.Quantum.Convert { mutable runningValue = number; mutable result = []; for _ in 1..bits { - set result += [ (runningValue &&& 1) != 0 ]; + set result += [(runningValue &&& 1) != 0]; set runningValue >>>= 1; } Fact(runningValue == 0, $"`number`={number} is too large to fit into {bits} bits."); @@ -119,7 +119,7 @@ namespace Microsoft.Quantum.Convert { set result += 1L <<< i; } } - + result } @@ -145,7 +145,7 @@ namespace Microsoft.Quantum.Convert { mutable runningValue = number; mutable result = []; for _ in 1..bits { - set result += [ (runningValue &&& 1L) != 0L ]; + set result += [(runningValue &&& 1L) != 0L]; set runningValue >>>= 1; } Fact(runningValue == 0L, $"`number`={number} is too large to fit into {bits} bits."); @@ -174,7 +174,7 @@ namespace Microsoft.Quantum.Convert { Fact(nBits < 64, $"`Length(bits)` must be less than 64, but was {nBits}."); mutable number = 0; - for idxBit in 0 .. nBits - 1 { + for idxBit in 0..nBits - 1 { if (results[idxBit] == One) { set number |||= 1 <<< idxBit; } @@ -217,7 +217,7 @@ namespace Microsoft.Quantum.Convert { function BoolArrayAsResultArray(input : Bool[]) : Result[] { mutable output = []; for b in input { - set output += [if b {One} else {Zero}]; + set output += [if b { One } else { Zero }]; } output @@ -233,7 +233,7 @@ namespace Microsoft.Quantum.Convert { /// /// # Output /// Complex number c = r⋅e^(t𝑖). - function ComplexAsComplexPolar (input : Complex) : ComplexPolar { + function ComplexAsComplexPolar(input : Complex) : ComplexPolar { return ComplexPolar(AbsComplex(input), ArgComplex(input)); } @@ -247,7 +247,7 @@ namespace Microsoft.Quantum.Convert { /// /// # Output /// Complex number c = x + y𝑖. - function ComplexPolarAsComplex (input : ComplexPolar) : Complex { + function ComplexPolarAsComplex(input : ComplexPolar) : Complex { return Complex( input::Magnitude * Cos(input::Argument), input::Magnitude * Sin(input::Argument) diff --git a/library/std/core.qs b/library/std/core.qs index 1c1b458a93..37ff549950 100644 --- a/library/std/core.qs +++ b/library/std/core.qs @@ -16,7 +16,7 @@ namespace Microsoft.Quantum.Core { /// A range expression's first element is `start`, /// its second element is `start+step`, third element is `start+step+step`, etc., /// until `end` is passed. - /// + /// /// Note that the defined start value of a range is the same as the first element of the sequence, /// unless the range specifies an empty sequence (for example, 2 .. 1). function RangeStart(r : Range) : Int { @@ -39,7 +39,7 @@ namespace Microsoft.Quantum.Core { /// A range expression's first element is `start`, /// its second element is `start+step`, third element is `start+step+step`, etc., /// until `end` is passed. - /// + /// /// Note that the defined end value of a range can differ from the last element in the sequence specified by the range; /// for example, in a range 0 .. 2 .. 5 the last element is 4 but the end value is 5. function RangeEnd(r : Range) : Int { diff --git a/library/std/diagnostics.qs b/library/std/diagnostics.qs index 1a976b0a19..669e1853b0 100644 --- a/library/std/diagnostics.qs +++ b/library/std/diagnostics.qs @@ -121,10 +121,11 @@ namespace Microsoft.Quantum.Diagnostics { /// # Output /// True if operations are equal, false otherwise. @Config(Unrestricted) - operation CheckOperationsAreEqual ( + operation CheckOperationsAreEqual( nQubits : Int, actual : (Qubit[] => Unit), - expected : (Qubit[] => Unit is Adj)) : Bool { + expected : (Qubit[] => Unit is Adj) + ) : Bool { // Prepare a reference register entangled with the target register. use reference = Qubit[nQubits]; @@ -132,7 +133,7 @@ namespace Microsoft.Quantum.Diagnostics { // Apply operations. within { - for i in 0 .. nQubits - 1 { + for i in 0..nQubits - 1 { H(reference[i]); CNOT(reference[i], target[i]); } diff --git a/library/std/internal.qs b/library/std/internal.qs index 6a2f4dc4e4..75d1559a5a 100644 --- a/library/std/internal.qs +++ b/library/std/internal.qs @@ -11,8 +11,7 @@ namespace Microsoft.Quantum.Intrinsic { S(target); H(target); T(target); - } - apply { + } apply { CNOT(control, target); } } @@ -22,8 +21,7 @@ namespace Microsoft.Quantum.Intrinsic { S(target); H(target); T(target); - } - apply { + } apply { CCNOT(control1, control2, target); } } @@ -33,22 +31,20 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { // Noop - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { Rz(theta, ctls[0]); - } - else { + } else { Controlled R1(ctls[1..(Length(ctls) - 1)], (theta, ctls[0])); } } } internal operation CR1(theta : Double, control : Qubit, target : Qubit) : Unit is Adj { - Rz(theta/2.0, target); - Rz(theta/2.0, control); - CNOT(control,target); - Rz(-theta/2.0, target); - CNOT(control,target); + Rz(theta / 2.0, target); + Rz(theta / 2.0, control); + CNOT(control, target); + Rz(-theta / 2.0, target); + CNOT(control, target); } internal operation CRz(control : Qubit, theta : Double, target : Qubit) : Unit is Adj { @@ -76,28 +72,21 @@ namespace Microsoft.Quantum.Intrinsic { } internal operation MapPauli(qubit : Qubit, from : Pauli, to : Pauli) : Unit is Adj { - if from == to { - } - elif (from == PauliZ and to == PauliX) or (from == PauliX and to == PauliZ) { + if from == to {} elif (from == PauliZ and to == PauliX) or (from == PauliX and to == PauliZ) { H(qubit); - } - elif from == PauliZ and to == PauliY { + } elif from == PauliZ and to == PauliY { H(qubit); S(qubit); H(qubit); - } - elif from == PauliY and to == PauliZ { + } elif from == PauliY and to == PauliZ { H(qubit); Adjoint S(qubit); H(qubit); - } - elif from == PauliY and to == PauliX { + } elif from == PauliY and to == PauliX { S(qubit); - } - elif from == PauliX and to == PauliY { + } elif from == PauliX and to == PauliY { Adjoint S(qubit); - } - else { + } else { fail "Unsupported input"; } } @@ -105,11 +94,9 @@ namespace Microsoft.Quantum.Intrinsic { internal operation EntangleForJointMeasure(basis : Pauli, aux : Qubit, qubit : Qubit) : Unit { if basis == PauliX { Controlled X([aux], qubit); - } - elif basis == PauliZ { + } elif basis == PauliZ { Controlled Z([aux], qubit); - } - elif basis == PauliY { + } elif basis == PauliY { Controlled Y([aux], qubit); } } @@ -164,15 +151,15 @@ namespace Microsoft.Quantum.Intrinsic { internal operation PhaseCCX(control1 : Qubit, control2 : Qubit, target : Qubit) : Unit is Adj { // https://arxiv.org/pdf/1210.0974.pdf#page=2 H(target); - CNOT(target,control1); - CNOT(control1,control2); + CNOT(target, control1); + CNOT(control1, control2); T(control2); Adjoint T(control1); T(target); - CNOT(target,control1); - CNOT(control1,control2); + CNOT(target, control1); + CNOT(control1, control2); Adjoint T(control2); - CNOT(target,control2); + CNOT(target, control2); H(target); } @@ -187,8 +174,7 @@ namespace Microsoft.Quantum.Intrinsic { internal operation CCY(control1 : Qubit, control2 : Qubit, target : Qubit) : Unit is Adj { within { MapPauli(target, PauliX, PauliY); - } - apply { + } apply { CCNOT(control1, control2, target); } } @@ -196,8 +182,7 @@ namespace Microsoft.Quantum.Intrinsic { internal operation CRxx(control : Qubit, theta : Double, qubit0 : Qubit, qubit1 : Qubit) : Unit { within { CNOT(qubit1, qubit0); - } - apply { + } apply { Controlled Rx([control], (theta, qubit0)); } } @@ -205,8 +190,7 @@ namespace Microsoft.Quantum.Intrinsic { internal operation CRyy(control : Qubit, theta : Double, qubit0 : Qubit, qubit1 : Qubit) : Unit { within { CNOT(qubit1, qubit0); - } - apply { + } apply { Controlled Ry([control], (theta, qubit0)); } } @@ -214,15 +198,14 @@ namespace Microsoft.Quantum.Intrinsic { internal operation CRzz(control : Qubit, theta : Double, qubit0 : Qubit, qubit1 : Qubit) : Unit { within { CNOT(qubit1, qubit0); - } - apply { + } apply { Controlled Rz([control], (theta, qubit0)); } } - internal function IndicesOfNonIdentity (paulies : Pauli[]) : Int[] { + internal function IndicesOfNonIdentity(paulies : Pauli[]) : Int[] { mutable indices = []; - for i in 0 .. Length(paulies) - 1 { + for i in 0..Length(paulies) - 1 { if (paulies[i] != PauliI) { set indices += [i]; } @@ -230,19 +213,19 @@ namespace Microsoft.Quantum.Intrinsic { indices } - internal function RemovePauliI (paulis : Pauli[], qubits : Qubit[]) : (Pauli[], Qubit[]) { + internal function RemovePauliI(paulis : Pauli[], qubits : Qubit[]) : (Pauli[], Qubit[]) { let indices = IndicesOfNonIdentity(paulis); let newPaulis = Subarray(indices, paulis); let newQubits = Subarray(indices, qubits); return (newPaulis, newQubits); } - internal operation SpreadZ (from : Qubit, to : Qubit[]) : Unit is Adj { + internal operation SpreadZ(from : Qubit, to : Qubit[]) : Unit is Adj { if (Length(to) > 0) { if (Length(to) > 1) { let half = Length(to) / 2; - SpreadZ(to[0], to[half + 1 .. Length(to) - 1]); - SpreadZ(from, to[1 .. half]); + SpreadZ(to[0], to[half + 1..Length(to) - 1]); + SpreadZ(from, to[1..half]); } CNOT(to[0], from); } diff --git a/library/std/intrinsic.qs b/library/std/intrinsic.qs index c1d5c01e7d..23ade7e4cf 100644 --- a/library/std/intrinsic.qs +++ b/library/std/intrinsic.qs @@ -93,45 +93,39 @@ namespace Microsoft.Quantum.Intrinsic { /// $$ /// where $P_i$ is the $i$th element of `paulis`, and where /// $N = $`Length(paulis)`. - operation Exp (paulis : Pauli[], theta : Double, qubits : Qubit[]) : Unit is Adj + Ctl { + operation Exp(paulis : Pauli[], theta : Double, qubits : Qubit[]) : Unit is Adj + Ctl { body ... { - Fact(Length(paulis) == Length(qubits), - "Arrays 'pauli' and 'qubits' must have the same length"); + Fact(Length(paulis) == Length(qubits), "Arrays 'pauli' and 'qubits' must have the same length"); let (newPaulis, newQubits) = RemovePauliI(paulis, qubits); let angle = -2.0 * theta; let len = Length(newPaulis); if len == 0 { ApplyGlobalPhase(theta); - } - elif len == 1 { + } elif len == 1 { R(newPaulis[0], angle, qubits[0]); - } - elif len == 2 { + } elif len == 2 { within { MapPauli(qubits[1], paulis[0], paulis[1]); - } - apply { + } apply { if (paulis[0] == PauliX) { - Rxx(angle , qubits[0], qubits[1]); + Rxx(angle, qubits[0], qubits[1]); } elif (paulis[0] == PauliY) { Ryy(angle, qubits[0], qubits[1]); } elif (paulis[0] == PauliZ) { Rzz(angle, qubits[0], qubits[1]); } } - } - else { // len > 2 + } else { + // len > 2 within { - for i in 0 .. Length(paulis) - 1 { + for i in 0..Length(paulis) - 1 { MapPauli(qubits[i], PauliZ, paulis[i]); } - } - apply { + } apply { within { - SpreadZ(qubits[1], qubits[2 .. Length(qubits) - 1]); - } - apply { + SpreadZ(qubits[1], qubits[2..Length(qubits) - 1]); + } apply { Rzz(angle, qubits[0], qubits[1]); } } @@ -167,23 +161,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__h__body(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CH(ctls[0], qubit); - } - elif Length(ctls) == 2 { + } elif Length(ctls) == 2 { CCH(ctls[0], ctls[1], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 1 - (Length(ctls) % 2)]; within { CollectControls(ctls, aux, 0); - } - apply { + } apply { if Length(ctls) % 2 != 0 { CCH(ctls[Length(ctls) - 1], aux[Length(ctls) - 3], qubit); - } - else { + } else { CCH(aux[Length(ctls) - 3], aux[Length(ctls) - 4], qubit); } } @@ -199,7 +188,7 @@ namespace Microsoft.Quantum.Intrinsic { /// This is a no-op. It is provided for completeness and because /// sometimes it is useful to call the identity in an algorithm or to pass it as a parameter. operation I(target : Qubit) : Unit is Adj + Ctl { - body ... { } + body ... {} adjoint self; } @@ -309,17 +298,14 @@ namespace Microsoft.Quantum.Intrinsic { if Length(bases) == 1 { within { MapPauli(qubits[0], PauliZ, bases[0]); - } - apply { + } apply { __quantum__qis__m__body(qubits[0]) } - } - else { + } else { use aux = Qubit(); within { H(aux); - } - apply { + } apply { for i in 0..Length(bases)-1 { EntangleForJointMeasure(bases[i], aux, qubits[i]); } @@ -375,8 +361,7 @@ namespace Microsoft.Quantum.Intrinsic { use aux = Qubit(); within { H(aux); - } - apply { + } apply { for i in 0..Length(bases)-1 { EntangleForJointMeasure(bases[i], aux, qubits[i]); } @@ -410,15 +395,13 @@ namespace Microsoft.Quantum.Intrinsic { operation R(pauli : Pauli, theta : Double, qubit : Qubit) : Unit is Adj + Ctl { if (pauli == PauliX) { Rx(theta, qubit); - } - elif (pauli == PauliY) { + } elif (pauli == PauliY) { Ry(theta, qubit); - } - elif (pauli == PauliZ) { + } elif (pauli == PauliZ) { Rz(theta, qubit); - } - else { // PauliI - ApplyGlobalPhase( - theta / 2.0 ); + } else { + // PauliI + ApplyGlobalPhase( - theta / 2.0); } } @@ -451,17 +434,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { Rz(theta, qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CR1(theta, ctls[0], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CR1(theta, aux[Length(ctls) - 2], qubit); } } @@ -602,12 +582,10 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__rx__body(theta, qubit); - } - else { + } else { within { MapPauli(qubit, PauliZ, PauliX); - } - apply { + } apply { Controlled Rz(ctls, (theta, qubit)); } } @@ -647,17 +625,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__rxx__body(theta, qubit0, qubit1); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CRxx(ctls[0], theta, qubit0, qubit1); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CRxx(aux[Length(ctls) - 2], theta, qubit0, qubit1); } } @@ -699,12 +674,10 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__ry__body(theta, qubit); - } - else { + } else { within { MapPauli(qubit, PauliZ, PauliY); - } - apply { + } apply { Controlled Rz(ctls, (theta, qubit)); } } @@ -744,17 +717,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__ryy__body(theta, qubit0, qubit1); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CRyy(ctls[0], theta, qubit0, qubit1); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CRyy(aux[Length(ctls) - 2], theta, qubit0, qubit1); } } @@ -796,17 +766,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__rz__body(theta, qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CRz(ctls[0], theta, qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CRz(aux[Length(ctls) - 2], theta, qubit); } } @@ -846,17 +813,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__rzz__body(theta, qubit0, qubit1); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CRzz(ctls[0], theta, qubit0, qubit1); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CRzz(aux[Length(ctls) - 2], theta, qubit0, qubit1); } } @@ -893,23 +857,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__s__body(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CS(ctls[0], qubit); - } - elif Length(ctls) == 2 { + } elif Length(ctls) == 2 { Controlled CS([ctls[0]], (ctls[1], qubit)); - } - else { + } else { use aux = Qubit[Length(ctls) - 2]; within { CollectControls(ctls, aux, 1 - (Length(ctls) % 2)); - } - apply { + } apply { if Length(ctls) % 2 != 0 { Controlled CS([ctls[Length(ctls) - 1]], (aux[Length(ctls) - 3], qubit)); - } - else { + } else { Controlled CS([aux[Length(ctls) - 3]], (aux[Length(ctls) - 4], qubit)); } } @@ -918,23 +877,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled adjoint (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__s__adj(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { Adjoint CS(ctls[0], qubit); - } - elif Length(ctls) == 2 { + } elif Length(ctls) == 2 { Controlled Adjoint CS([ctls[0]], (ctls[1], qubit)); - } - else { + } else { use aux = Qubit[Length(ctls) - 2]; within { CollectControls(ctls, aux, 1 - (Length(ctls) % 2)); - } - apply { + } apply { if Length(ctls) % 2 != 0 { Controlled Adjoint CS([ctls[Length(ctls) - 1]], (aux[Length(ctls) - 3], qubit)); - } - else { + } else { Controlled Adjoint CS([aux[Length(ctls) - 3]], (aux[Length(ctls) - 4], qubit)); } } @@ -980,12 +934,10 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if (Length(ctls) == 0) { __quantum__qis__swap__body(qubit1, qubit2); - } - else { + } else { within { CNOT(qubit1, qubit2); - } - apply { + } apply { Controlled CNOT(ctls, (qubit2, qubit1)); } } @@ -1019,17 +971,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__t__body(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { CT(ctls[0], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { CT(aux[Length(ctls) - 2], qubit); } } @@ -1037,17 +986,14 @@ namespace Microsoft.Quantum.Intrinsic { controlled adjoint (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__t__adj(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { Adjoint CT(ctls[0], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 1]; within { CollectControls(ctls, aux, 0); AdjustForSingleControl(ctls, aux); - } - apply { + } apply { Adjoint CT(aux[Length(ctls) - 2], qubit); } } @@ -1078,23 +1024,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__x__body(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { __quantum__qis__cx__body(ctls[0], qubit); - } - elif Length(ctls) == 2 { + } elif Length(ctls) == 2 { __quantum__qis__ccx__body(ctls[0], ctls[1], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 2]; within { CollectControls(ctls, aux, 1 - (Length(ctls) % 2)); - } - apply { + } apply { if Length(ctls) % 2 != 0 { __quantum__qis__ccx__body(ctls[Length(ctls) - 1], aux[Length(ctls) - 3], qubit); - } - else { + } else { __quantum__qis__ccx__body(aux[Length(ctls) - 3], aux[Length(ctls) - 4], qubit); } } @@ -1127,23 +1068,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if (Length(ctls) == 0) { __quantum__qis__y__body(qubit); - } - elif (Length(ctls) == 1) { + } elif (Length(ctls) == 1) { __quantum__qis__cy__body(ctls[0], qubit); - } - elif (Length(ctls) == 2) { + } elif (Length(ctls) == 2) { CCY(ctls[0], ctls[1], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 2]; within { CollectControls(ctls, aux, 1 - (Length(ctls) % 2)); - } - apply { + } apply { if Length(ctls) % 2 != 0 { CCY(ctls[Length(ctls) - 1], aux[Length(ctls) - 3], qubit); - } - else { + } else { CCY(aux[Length(ctls) - 3], aux[Length(ctls) - 4], qubit); } } @@ -1176,23 +1112,18 @@ namespace Microsoft.Quantum.Intrinsic { controlled (ctls, ...) { if Length(ctls) == 0 { __quantum__qis__z__body(qubit); - } - elif Length(ctls) == 1 { + } elif Length(ctls) == 1 { __quantum__qis__cz__body(ctls[0], qubit); - } - elif Length(ctls) == 2 { + } elif Length(ctls) == 2 { CCZ(ctls[0], ctls[1], qubit); - } - else { + } else { use aux = Qubit[Length(ctls) - 2]; within { CollectControls(ctls, aux, 1 - (Length(ctls) % 2)); - } - apply { + } apply { if Length(ctls) % 2 != 0 { CCZ(ctls[Length(ctls) - 1], aux[Length(ctls) - 3], qubit); - } - else { + } else { CCZ(aux[Length(ctls) - 3], aux[Length(ctls) - 4], qubit); } } @@ -1212,7 +1143,7 @@ namespace Microsoft.Quantum.Intrinsic { /// The specific behavior of this function is simulator-dependent, /// but in most cases the given message will be written to the console. /// ``` - function Message (msg : String) : Unit { + function Message(msg : String) : Unit { body intrinsic; } diff --git a/library/std/math.qs b/library/std/math.qs index 7d37628f2e..09f89bbbb6 100644 --- a/library/std/math.qs +++ b/library/std/math.qs @@ -40,8 +40,7 @@ namespace Microsoft.Quantum.Math { /// /// # Output /// Returns a `Double` equal to 0.6931471805599453. - function LogOf2 () : Double - { + function LogOf2() : Double { 0.6931471805599453 } @@ -102,42 +101,36 @@ namespace Microsoft.Quantum.Math { /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. - function SignI (a : Int) : Int { - if (a < 0) { -1 } - elif (a > 0) { +1 } - else { 0 } + function SignI(a : Int) : Int { + if (a < 0) { -1 } elif (a > 0) { + 1 } else { 0 } } /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. - function SignD (a : Double) : Int { - if (a < 0.0) { -1 } - elif (a > 0.0) { +1 } - else { 0 } + function SignD(a : Double) : Int { + if (a < 0.0) { -1 } elif (a > 0.0) { + 1 } else { 0 } } /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. - function SignL (a : BigInt) : Int { - if (a < 0L) { -1 } - elif (a > 0L) { +1 } - else { 0 } + function SignL(a : BigInt) : Int { + if (a < 0L) { -1 } elif (a > 0L) { + 1 } else { 0 } } /// # Summary /// Returns the absolute value of an integer. - function AbsI (a : Int) : Int { + function AbsI(a : Int) : Int { a < 0 ? -a | a } /// # Summary /// Returns the absolute value of a double-precision floating-point number. - function AbsD (a : Double) : Double { + function AbsD(a : Double) : Double { a < 0.0 ? -a | a } /// # Summary - function AbsL (a : BigInt) : BigInt { + function AbsL(a : BigInt) : BigInt { a < 0L ? -a | a } @@ -155,19 +148,19 @@ namespace Microsoft.Quantum.Math { /// # Summary /// Returns the larger of two specified numbers. - function MaxL (a : BigInt, b : BigInt) : BigInt { + function MaxL(a : BigInt, b : BigInt) : BigInt { a > b ? a | b } /// # Summary /// Returns the smaller of two specified numbers. - function MinI (a : Int, b : Int) : Int { + function MinI(a : Int, b : Int) : Int { a < b ? a | b } /// # Summary /// Returns the smaller of two specified numbers. - function MinD (a : Double, b : Double) : Double { + function MinD(a : Double, b : Double) : Double { a < b ? a | b } @@ -186,7 +179,7 @@ namespace Microsoft.Quantum.Math { /// /// # Output /// The largest element of `values`. - function Max (values : Int[]) : Int { + function Max(values : Int[]) : Int { Fact(Length(values) > 0, "Array must contain at least one element."); mutable max = values[0]; for element in values[1...] { @@ -207,7 +200,7 @@ namespace Microsoft.Quantum.Math { /// /// # Output /// The smallest element of `values`. - function Min (values : Int[]) : Int { + function Min(values : Int[]) : Int { Fact(Length(values) > 0, "Array must contain at least one element."); mutable min = values[0]; for element in values[1...] { @@ -225,80 +218,80 @@ namespace Microsoft.Quantum.Math { /// # Summary /// Returns the angle whose cosine is the specified number. - function ArcCos (x : Double) : Double { + function ArcCos(x : Double) : Double { body intrinsic; } /// # Summary /// Returns the angle whose sine is the specified number. - function ArcSin (y : Double) : Double { + function ArcSin(y : Double) : Double { body intrinsic; } /// # Summary /// Returns the angle whose tangent is the specified number. - function ArcTan (d : Double) : Double { + function ArcTan(d : Double) : Double { body intrinsic; } /// # Summary /// Returns the angle whose tangent is the quotient of two specified numbers. - function ArcTan2 (y : Double, x : Double) : Double { + function ArcTan2(y : Double, x : Double) : Double { body intrinsic; } /// # Summary /// Returns the cosine of the specified angle. - function Cos (theta : Double) : Double { + function Cos(theta : Double) : Double { body intrinsic; } /// # Summary /// Returns the hyperbolic cosine of the specified angle. - function Cosh (d : Double) : Double { + function Cosh(d : Double) : Double { body intrinsic; } /// # Summary /// Returns the sine of the specified angle. - function Sin (theta : Double) : Double { + function Sin(theta : Double) : Double { body intrinsic; } /// # Summary /// Returns the hyperbolic sine of the specified angle. - function Sinh (d : Double) : Double { + function Sinh(d : Double) : Double { body intrinsic; } /// # Summary /// Returns the tangent of the specified angle. - function Tan (d : Double) : Double { + function Tan(d : Double) : Double { body intrinsic; } /// # Summary /// Returns the hyperbolic tangent of the specified angle. - function Tanh (d : Double) : Double { + function Tanh(d : Double) : Double { body intrinsic; } /// # Summary /// Computes the inverse hyperbolic cosine of a number. - function ArcCosh (x : Double) : Double { + function ArcCosh(x : Double) : Double { Log(x + Sqrt(x * x - 1.0)) } /// # Summary /// Computes the inverse hyperbolic sine of a number. - function ArcSinh (x : Double) : Double { + function ArcSinh(x : Double) : Double { Log(x + Sqrt(x * x + 1.0)) } /// # Summary /// Computes the inverse hyperbolic tangent of a number. - function ArcTanh (x : Double) : Double { + function ArcTanh(x : Double) : Double { Log((1.0 + x) / (1.0 - x)) * 0.5 } @@ -621,7 +614,8 @@ namespace Microsoft.Quantum.Math { /// Using process similar to this: https://nrich.maths.org/1397 function ContinuedFractionConvergentI( fraction : (Int, Int), - denominatorBound : Int) : (Int, Int) { + denominatorBound : Int + ) : (Int, Int) { Fact(denominatorBound > 0, "Denominator bound must be positive"); let (a, b) = fraction; @@ -651,7 +645,8 @@ namespace Microsoft.Quantum.Math { /// Using process similar to this: https://nrich.maths.org/1397 function ContinuedFractionConvergentL( fraction : (BigInt, BigInt), - denominatorBound : BigInt) : (BigInt, BigInt) { + denominatorBound : BigInt + ) : (BigInt, BigInt) { Fact(denominatorBound > 0L, "Denominator bound must be positive"); let (a, b) = fraction; @@ -694,8 +689,7 @@ namespace Microsoft.Quantum.Math { /// // which is a multiple of 2.4. /// let z = RealMod(3.6, 2.4, -1.2); /// ``` - function RealMod(value : Double, modulo : Double, minValue : Double) : Double - { + function RealMod(value : Double, modulo : Double, minValue : Double) : Double { let timesModuloInSegment = (value - minValue) / modulo; let fractionalPart = timesModuloInSegment - IntAsDouble(Truncate(timesModuloInSegment)); modulo * fractionalPart + minValue @@ -738,7 +732,7 @@ namespace Microsoft.Quantum.Math { /// # Summary /// For a non-zero integer `a`, returns the number of trailing zero bits /// in the binary representation of `a`. - function TrailingZeroCountI (a : Int) : Int { + function TrailingZeroCountI(a : Int) : Int { Fact(a != 0, "TrailingZeroCountI: `a` cannot be 0."); mutable count = 0; @@ -754,7 +748,7 @@ namespace Microsoft.Quantum.Math { /// # Summary /// For a non-zero integer `a`, returns the number of trailing zero bits /// in the binary representation of `a`. - function TrailingZeroCountL (a : BigInt) : Int { + function TrailingZeroCountL(a : BigInt) : Int { Fact(a != 0L, "TrailingZeroCountL: `a` cannot be 0."); mutable count = 0; @@ -769,7 +763,7 @@ namespace Microsoft.Quantum.Math { /// # Summary /// Returns the number of 1 bits in the binary representation of integer `n`. - function HammingWeightI (n : Int) : Int { + function HammingWeightI(n : Int) : Int { let i1 = n - ((n >>> 1) &&& 0x5555555555555555); let i2 = (i1 &&& 0x3333333333333333) + ((i1 >>> 2) &&& 0x3333333333333333); // Multiplication may overflow. See https://github.com/microsoft/qsharp/issues/828 @@ -803,10 +797,7 @@ namespace Microsoft.Quantum.Math { Fact(n >= 0, "The factorial is not defined for negative inputs."); Fact(n <= 20, "The largest factorial that can be stored as an Int is 20!. Use FactorialL or ApproximateFactorial."); - [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, - 39916800, 479001600, 6227020800, 87178291200, 1307674368000, - 20922789888000, 355687428096000, 6402373705728000, - 121645100408832000, 2432902008176640000][n] + [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000][n] } /// # Summary @@ -826,7 +817,7 @@ namespace Microsoft.Quantum.Math { Fact(n >= 0, "The factorial is not defined for negative inputs."); mutable result = 1L; - for i in 1 .. n { + for i in 1..n { set result *= IntAsBigInt(i); } result @@ -893,10 +884,14 @@ namespace Microsoft.Quantum.Math { // Here, we use the approximation described in Numerical Recipes in C. let coefficients = [ 57.1562356658629235, -59.5979603554754912, - 14.1360979747417471, -0.491913816097620199, 0.339946499848118887e-4, - 0.465236289270485756e-4, -0.983744753048795646e-4, 0.158088703224912494e-3, - -0.210264441724104883e-3, 0.217439618115212643e-3, -0.164318106536763890e-3, - 0.844182239838527433e-4, -0.261908384015814087e-4, 0.368991826595316234e-5 + 14.1360979747417471, -0.491913816097620199, + 0.339946499848118887e-4, + 0.465236289270485756e-4, -0.983744753048795646e-4, + 0.158088703224912494e-3, + -0.210264441724104883e-3, + 0.217439618115212643e-3, -0.164318106536763890e-3, + 0.844182239838527433e-4, -0.261908384015814087e-4, + 0.368991826595316234e-5 ]; Fact(x > 0.0, "Γ(x) not defined for x <= 0."); @@ -952,7 +947,7 @@ namespace Microsoft.Quantum.Math { if n < 171 { Floor(0.5 + ApproximateFactorial(n) / (ApproximateFactorial(k) * ApproximateFactorial(n - k))) } else { - Floor(0.5 + E()^(LogFactorialD(n) - LogFactorialD(k) - LogFactorialD(n - k))) + Floor(0.5 + E() ^ (LogFactorialD(n) - LogFactorialD(k) - LogFactorialD(n - k))) } } @@ -973,7 +968,7 @@ namespace Microsoft.Quantum.Math { /// /// # Output /// The squared 2-norm of `array`. - function SquaredNorm (array : Double[]) : Double { + function SquaredNorm(array : Double[]) : Double { mutable sum = 0.0; for element in array { set sum += element * element; @@ -994,17 +989,17 @@ namespace Microsoft.Quantum.Math { /// /// # Output /// The p-norm |x̄|ₚ. - function PNorm (p : Double, array : Double[]) : Double { + function PNorm(p : Double, array : Double[]) : Double { if p < 1.0 { fail "p must be >= 1.0"; } mutable sum = 0.0; for element in array { - set sum += AbsD(element)^p; + set sum += AbsD(element) ^ p; } - sum^(1.0 / p) + sum ^ (1.0 / p) } /// # Summary @@ -1023,7 +1018,7 @@ namespace Microsoft.Quantum.Math { /// /// # See Also /// - PNorm - function PNormalized (p : Double, array : Double[]) : Double[] { + function PNormalized(p : Double, array : Double[]) : Double[] { let norm = PNorm(p, array); if (norm == 0.0) { return array; @@ -1051,7 +1046,7 @@ namespace Microsoft.Quantum.Math { /// ```qsharp /// let imagUnit = Complex(0.0, 1.0); /// ``` - newtype Complex = (Real: Double, Imag: Double); + newtype Complex = (Real : Double, Imag : Double); /// # Summary /// Represents a complex number in polar form. @@ -1062,7 +1057,7 @@ namespace Microsoft.Quantum.Math { /// The absolute value r>0 of c. /// ## Argument /// The phase t ∈ ℝ of c. - newtype ComplexPolar = (Magnitude: Double, Argument: Double); + newtype ComplexPolar = (Magnitude : Double, Argument : Double); /// # Summary /// Returns the squared absolute value of a complex number of type @@ -1281,7 +1276,7 @@ namespace Microsoft.Quantum.Math { /// Note that this is a multi-valued function, but only one value is returned. internal function PowCAsCP(base : Complex, power : Complex) : ComplexPolar { let ((a, b), (c, d)) = (base!, power!); - let baseSqNorm = a*a + b*b; + let baseSqNorm = a * a + b * b; let baseNorm = Sqrt(baseSqNorm); let baseArg = ArgComplex(base); @@ -1294,7 +1289,7 @@ namespace Microsoft.Quantum.Math { // magnitude = 𝑒^((c⋅ln(baseNorm) - d⋅baseArg)) = baseNorm^c / 𝑒^(d⋅baseArg) // angle = d⋅ln(baseNorm) + c⋅baseArg - let magnitude = baseNorm^c / E()^(d * baseArg); + let magnitude = baseNorm ^ c / E() ^ (d * baseArg); let angle = d * Log(baseNorm) + c * baseArg; ComplexPolar(magnitude, angle) @@ -1382,7 +1377,7 @@ namespace Microsoft.Quantum.Math { /// # Remark /// The value can be computed as -2^(p-1), where p is the number of integer bits. function SmallestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { - -(2.0^IntAsDouble(integerBits - 1)) + -(2.0 ^ IntAsDouble(integerBits - 1)) } /// # Summary @@ -1398,7 +1393,7 @@ namespace Microsoft.Quantum.Math { /// The value can be computed as 2^(p-1) - 2^(-q), where p /// is the number of integer bits and q is the number of fractional bits. function LargestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { - 2.0^IntAsDouble(integerBits - 1) - 2.0^(-IntAsDouble(fractionalBits)) + 2.0 ^ IntAsDouble(integerBits - 1) - 2.0 ^ (-IntAsDouble(fractionalBits)) } } diff --git a/library/std/measurement.qs b/library/std/measurement.qs index d24dfbcec2..fc4e05326a 100644 --- a/library/std/measurement.qs +++ b/library/std/measurement.qs @@ -24,7 +24,7 @@ namespace Microsoft.Quantum.Measurement { /// # Remarks /// This operation does not reset the measured qubits to the |0⟩ state, /// leaving them in the state that corresponds to the measurement result. - operation MeasureAllZ (register : Qubit[]) : Result { + operation MeasureAllZ(register : Qubit[]) : Result { Measure(Repeated(PauliZ, Length(register)), register) } @@ -39,7 +39,7 @@ namespace Microsoft.Quantum.Measurement { /// # Remarks /// This operation does not reset the measured qubits to the |0⟩ state, /// leaving them in the state that corresponds to the measurement results. - operation MeasureEachZ (register : Qubit[]) : Result[] { + operation MeasureEachZ(register : Qubit[]) : Result[] { mutable results = []; for qubit in register { set results += [M(qubit)]; @@ -55,7 +55,7 @@ namespace Microsoft.Quantum.Measurement { /// An array of qubits to be measured. /// # Output /// An array of measurement results. - operation MResetEachZ (register : Qubit[]) : Result[] { + operation MResetEachZ(register : Qubit[]) : Result[] { mutable results = []; for qubit in register { set results += [MResetZ(qubit)]; @@ -79,7 +79,7 @@ namespace Microsoft.Quantum.Measurement { /// /// # Output /// The result of measuring `target` in the Pauli X basis. - operation MResetX (target : Qubit) : Result { + operation MResetX(target : Qubit) : Result { // Map the qubit's state from the Z-basis to the X-basis. // Then measure and reset the qubit. H(target); @@ -102,7 +102,7 @@ namespace Microsoft.Quantum.Measurement { /// /// # Output /// The result of measuring `target` in the Pauli Y basis. - operation MResetY (target : Qubit) : Result { + operation MResetY(target : Qubit) : Result { // Map the qubit's state from the Z-basis to the Y-basis. // Then measure and reset the qubit. // Note: this use HSadj instead of HSH since that is sufficient for measurement. @@ -127,7 +127,7 @@ namespace Microsoft.Quantum.Measurement { /// /// # Output /// The result of measuring `target` in the Pauli Z basis. - operation MResetZ (target : Qubit) : Result { + operation MResetZ(target : Qubit) : Result { __quantum__qis__mresetz__body(target) } diff --git a/library/std/re.qs b/library/std/re.qs index 09e05d0359..29b71bf13d 100644 --- a/library/std/re.qs +++ b/library/std/re.qs @@ -34,7 +34,7 @@ namespace Microsoft.Quantum.ResourceEstimation { /// `false` indicates if cached estimates have been incorporated into the overall costs /// and the code fragment should be skipped. @Config(Unrestricted) - function BeginEstimateCaching(name: String, variant: Int): Bool { + function BeginEstimateCaching(name : String, variant : Int) : Bool { body intrinsic; } @@ -42,7 +42,7 @@ namespace Microsoft.Quantum.ResourceEstimation { /// Instructs the resource estimator to stop estimates caching /// because the code fragment in consideration is over. This function /// is only available when using resource estimator execution target. - function EndEstimateCaching(): Unit { + function EndEstimateCaching() : Unit { body intrinsic; } @@ -116,14 +116,14 @@ namespace Microsoft.Quantum.ResourceEstimation { /// to physical resource estimates. Only PSSPCLayout() is supported at this time. /// ## arguments /// Operation takes these qubits as its arguments. - operation AccountForEstimates(estimates: (Int, Int)[], layout: Int, arguments: Qubit[]): Unit is Adj { + operation AccountForEstimates(estimates : (Int, Int)[], layout : Int, arguments : Qubit[]) : Unit is Adj { body ... { AccountForEstimatesInternal(estimates, layout, arguments); } adjoint self; } - internal operation AccountForEstimatesInternal(estimates: (Int, Int)[], layout: Int, arguments: Qubit[]): Unit { + internal operation AccountForEstimatesInternal(estimates : (Int, Int)[], layout : Int, arguments : Qubit[]) : Unit { body intrinsic; } diff --git a/library/std/unstable_arithmetic.qs b/library/std/unstable_arithmetic.qs index 0c6b045339..df1b7c00c9 100644 --- a/library/std/unstable_arithmetic.qs +++ b/library/std/unstable_arithmetic.qs @@ -22,7 +22,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// The second input qubit. /// ## z /// A qubit onto which the majority function will be applied. - operation MAJ (x : Qubit, y : Qubit, z : Qubit) : Unit is Adj + Ctl { + operation MAJ(x : Qubit, y : Qubit, z : Qubit) : Unit is Adj + Ctl { CNOT(z, y); CNOT(z, x); CCNOT(y, x, z); @@ -46,7 +46,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Remarks /// This operation is implemented in-place, without explicit allocation of /// additional auxiliary qubits. - operation ReflectAboutInteger (index : Int, reg : Qubit[]) : Unit is Adj + Ctl { + operation ReflectAboutInteger(index : Int, reg : Qubit[]) : Unit is Adj + Ctl { within { // Evaluation optimization for case index == 0 if index == 0 { @@ -94,7 +94,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Length(ys) = n > 0, c is a Int number, 0 ≤ c < 2ⁿ. /// NOTE: Use IncByIUsingIncByLE directly if the choice of implementation /// is important. - operation IncByI (c : Int, ys : Qubit[]) : Unit is Adj + Ctl { + operation IncByI(c : Int, ys : Qubit[]) : Unit is Adj + Ctl { IncByIUsingIncByLE(RippleCarryTTKIncByLE, c, ys); } @@ -106,7 +106,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Length(ys) = n > 0, c is a BigInt number, 0 ≤ c < 2ⁿ. /// NOTE: Use IncByLUsingIncByLE directly if the choice of implementation /// is important. - operation IncByL (c : BigInt, ys : Qubit[]) : Unit is Adj + Ctl { + operation IncByL(c : BigInt, ys : Qubit[]) : Unit is Adj + Ctl { IncByLUsingIncByLE(RippleCarryTTKIncByLE, c, ys); } @@ -118,7 +118,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// and Length(xs) ≤ Length(ys) = n. /// NOTE: Use operations like RippleCarryCGIncByLE directly if /// the choice of implementation is important. - operation IncByLE (xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { + operation IncByLE(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { RippleCarryTTKIncByLE(xs, ys); } @@ -131,7 +131,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Length(xs) = Length(ys) ≤ Length(zs) = n, assuming zs is 0-initialized. /// NOTE: Use operations like RippleCarryCGAddLE directly if /// the choice of implementation is important. - operation AddLE (xs : Qubit[], ys : Qubit[], zs : Qubit[]) : Unit is Adj { + operation AddLE(xs : Qubit[], ys : Qubit[], zs : Qubit[]) : Unit is Adj { RippleCarryCGAddLE(xs, ys, zs); } @@ -151,7 +151,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// "Quantum Addition Circuits and Unbounded Fan-Out" /// by Yasuhiro Takahashi, Seiichiro Tani, Noboru Kunihiro /// - operation RippleCarryTTKIncByLE (xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { + operation RippleCarryTTKIncByLE(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { let xsLen = Length(xs); let ysLen = Length(ys); @@ -166,9 +166,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { ApplyInnerTTKAdderNoCarry(xs, ys); } } - CNOT (xs[0], ys[0]); - } - elif xsLen + 1 == ysLen { + CNOT(xs[0], ys[0]); + } elif xsLen + 1 == ysLen { if xsLen > 1 { CNOT(xs[xsLen-1], ys[ysLen-1]); within { @@ -176,13 +175,11 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { } apply { ApplyInnerTTKAdderWithCarry(xs, ys); } - } - else { + } else { CCNOT(xs[0], ys[0], ys[1]); } CNOT(xs[0], ys[0]); - } - elif xsLen + 2 <= ysLen { + } elif xsLen + 2 <= ysLen { // Pad xs so that its length is one qubit shorter than ys. use padding = Qubit[ysLen - xsLen - 1]; RippleCarryTTKIncByLE(xs + padding, ys); @@ -203,7 +200,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Reference /// - [arXiv:1709.06648](https://arxiv.org/pdf/1709.06648.pdf) /// "Halving the cost of quantum addition" by Craig Gidney. - operation RippleCarryCGIncByLE (xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { + operation RippleCarryCGIncByLE(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { let xsLen = Length(xs); let ysLen = Length(ys); @@ -260,7 +257,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Reference /// - [arXiv:1709.06648](https://arxiv.org/pdf/1709.06648.pdf) /// "Halving the cost of quantum addition" by Craig Gidney. - operation RippleCarryCGAddLE (xs : Qubit[], ys : Qubit[], zs : Qubit[]) : Unit is Adj { + operation RippleCarryCGAddLE(xs : Qubit[], ys : Qubit[], zs : Qubit[]) : Unit is Adj { let xsLen = Length(xs); let zsLen = Length(zs); Fact(Length(ys) == xsLen, "Registers `xs` and `ys` must be of same length."); @@ -269,7 +266,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { // Since zs is zero-initialized, its bits at indexes higher than // xsLen remain unused as there will be no carry into them. let top = MinI(zsLen-2, xsLen-1); - for k in 0 .. top { + for k in 0..top { FullAdder(zs[k], xs[k], ys[k], zs[k + 1]); } @@ -301,7 +298,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { Fact(Length(ys) == xsLen, "Registers `xs` and `ys` must be of same length."); Fact(zsLen >= xsLen, "Register `zs` must be no shorter than register `xs`."); - if zsLen > xsLen { // with carry-out + if zsLen > xsLen { + // with carry-out // compute initial generate values for k in 0..xsLen - 1 { ApplyAndAssuming0Target(xs[k], ys[k], zs[k + 1]); @@ -322,7 +320,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { CNOT(ys[k], zs[k]); } } - } else { // xsLen == zsLen, so without carry-out + } else { + // xsLen == zsLen, so without carry-out LookAheadDKRSAddLE(Most(xs), Most(ys), zs); CNOT(Tail(xs), Tail(zs)); CNOT(Tail(ys), Tail(zs)); @@ -341,7 +340,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Reference /// - [arXiv:quant-ph/0008033](https://arxiv.org/abs/quant-ph/0008033) /// "Addition on a Quantum Computer" by Thomas G. Draper - operation FourierTDIncByLE (xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { + operation FourierTDIncByLE(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { within { ApplyQFT(ys); } apply { @@ -358,15 +357,16 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Description /// Computes ys += c modulo 2ⁿ, where ys is a little-endian register /// Length(ys) = n > 0, c is a BigInt number, 0 ≤ c < 2ⁿ. - operation IncByLUsingIncByLE ( + operation IncByLUsingIncByLE( adder : (Qubit[], Qubit[]) => Unit is Adj + Ctl, c : BigInt, - ys : Qubit[]) : Unit is Adj + Ctl { + ys : Qubit[] + ) : Unit is Adj + Ctl { let ysLen = Length(ys); Fact(ysLen > 0, "Length of `ys` must be at least 1."); Fact(c >= 0L, "Constant `c` must be non-negative."); - Fact(c < 2L^ysLen, "Constant `c` must be smaller than 2^Length(ys)."); + Fact(c < 2L ^ ysLen, "Constant `c` must be smaller than 2^Length(ys)."); if c != 0L { // If c has j trailing zeros, then the j least significant @@ -390,15 +390,16 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Description /// Computes ys += c modulo 2ⁿ, where ys is a little-endian register /// Length(ys) = n > 0, c is an Int number, 0 ≤ c < 2ⁿ. - operation IncByIUsingIncByLE ( + operation IncByIUsingIncByLE( adder : (Qubit[], Qubit[]) => Unit is Adj + Ctl, c : Int, - ys : Qubit[]) : Unit is Adj + Ctl { + ys : Qubit[] + ) : Unit is Adj + Ctl { let ysLen = Length(ys); Fact(ysLen > 0, "Length of `ys` must be at least 1."); Fact(c >= 0, "Constant `c` must be non-negative."); - Fact(c < 2^ysLen, "Constant `c` must be smaller than 2^Length(ys)."); + Fact(c < 2 ^ ysLen, "Constant `c` must be smaller than 2^Length(ys)."); if c != 0 { // If c has j trailing zeros than the j least significant @@ -436,7 +437,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { forwardAdder : (Qubit[], Qubit[], Qubit[]) => Unit is Adj, backwardAdder : (Qubit[], Qubit[], Qubit[]) => Unit is Adj, xs : Qubit[], - ys : Qubit[]) : Unit is Adj + Ctl { + ys : Qubit[] + ) : Unit is Adj + Ctl { body (...) { let n = Length(xs); @@ -537,11 +539,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes `if (c < x) { action(target) }`, that is, applies `action` to `target` /// if a BigInt value `c` is less than the little-endian qubit register `x` - operation ApplyIfLessL<'T> ( + operation ApplyIfLessL<'T>( action : 'T => Unit is Adj + Ctl, c : BigInt, x : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyActionIfGreaterThanOrEqualConstant(false, action, c + 1L, x, target); } @@ -549,11 +552,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes `if (c <= x) { action(target) }`, that is, applies `action` to `target` /// if a BigInt value `c` is less or equal to the little-endian qubit register `x` - operation ApplyIfLessOrEqualL<'T> ( + operation ApplyIfLessOrEqualL<'T>( action : 'T => Unit is Adj + Ctl, c : BigInt, x : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyActionIfGreaterThanOrEqualConstant(false, action, c, x, target); } @@ -561,11 +565,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes `if (c == x) { action(target) }`, that is, applies `action` to `target` /// if a BigInt value `c` is equal to the little-endian qubit register `x` - operation ApplyIfEqualL<'T> ( + operation ApplyIfEqualL<'T>( action : 'T => Unit is Adj + Ctl, c : BigInt, xs : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { let cBitSize = BitSizeL(c); let xLen = Length(xs); @@ -582,11 +587,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes `if (c >= x) { action(target) }`, that is, applies `action` to `target` /// if a BigInt value `c` is greater or equal to the little-endian qubit register `x` - operation ApplyIfGreaterOrEqualL<'T> ( + operation ApplyIfGreaterOrEqualL<'T>( action : 'T => Unit is Adj + Ctl, c : BigInt, x : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyActionIfGreaterThanOrEqualConstant(true, action, c + 1L, x, target); } @@ -594,11 +600,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes `if (c > x) { action(target) }`, that is, applies `action` to `target` /// if a BigInt value `c` is greater than the little-endian qubit register `x` - operation ApplyIfGreaterL<'T> ( + operation ApplyIfGreaterL<'T>( action : 'T => Unit is Adj + Ctl, c : BigInt, x : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyActionIfGreaterThanOrEqualConstant(true, action, c, x, target); } @@ -607,11 +614,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes `if x < y { action(target) }`, that is, applies `action` to `target` /// if register `x` is less than the register `y`. /// Both qubit registers should be in a little-endian format. - operation ApplyIfLessLE<'T> ( + operation ApplyIfLessLE<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyIfGreaterLE(action, y, x, target); } @@ -620,11 +628,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes `if x <= y { action(target) }`, that is, applies `action` to `target` /// if register `x` is less or equal to the register `y`. /// Both qubit registers should be in a little-endian format. - operation ApplyIfLessOrEqualLE<'T> ( + operation ApplyIfLessOrEqualLE<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { Fact(Length(x) > 0, "Bitwidth must be at least 1"); within { @@ -639,11 +648,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes `if x == y { action(target) }`, that is, applies `action` to `target` /// if register `x` is equal to the register `y`. /// Both qubit registers should be in a little-endian format. - operation ApplyIfEqualLE<'T> ( + operation ApplyIfEqualLE<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { Fact(Length(x) == Length(y), "x and y must be of same length"); within { @@ -660,11 +670,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes `if x >= y { action(target) }`, that is, applies `action` to `target` /// if register `x` is greater or equal to the register `y`. /// Both qubit registers should be in a little-endian format. - operation ApplyIfGreaterOrEqualLE<'T> ( + operation ApplyIfGreaterOrEqualLE<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { ApplyIfLessOrEqualLE(action, y, x, target); } @@ -673,11 +684,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes `if x > y { action(target) }`, that is, applies `action` to `target` /// if register `x` is greater than the register `y`. /// Both qubit registers should be in a little-endian format. - operation ApplyIfGreaterLE<'T> ( + operation ApplyIfGreaterLE<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { Fact(Length(x) > 0, "Bitwidth must be at least 1"); within { diff --git a/library/std/unstable_arithmetic_internal.qs b/library/std/unstable_arithmetic_internal.qs index 5a0fa365a2..d4622ef337 100644 --- a/library/std/unstable_arithmetic_internal.qs +++ b/library/std/unstable_arithmetic_internal.qs @@ -25,15 +25,13 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Addition Circuits and Unbounded Fan-Out", Quantum Information and /// Computation, Vol. 10, 2010. /// https://arxiv.org/abs/0910.2530 - internal operation ApplyOuterTTKAdder(xs : Qubit[], ys : Qubit[]) - : Unit is Adj + Ctl { - Fact(Length(xs) <= Length(ys), - "Input register ys must be at lease as long as xs." ); + internal operation ApplyOuterTTKAdder(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { + Fact(Length(xs) <= Length(ys), "Input register ys must be at lease as long as xs."); for i in 1..Length(xs)-1 { CNOT(xs[i], ys[i]); } for i in Length(xs)-2..-1..1 { - CNOT(xs[i], xs[i+1]); + CNOT(xs[i], xs[i + 1]); } } @@ -60,17 +58,15 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// The specified controlled operation makes use of symmetry and mutual /// cancellation of operations to improve on the default implementation /// that adds a control to every operation. - internal operation ApplyInnerTTKAdderNoCarry(xs : Qubit[], ys : Qubit[]) - : Unit is Adj + Ctl { + internal operation ApplyInnerTTKAdderNoCarry(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { body (...) { - (Controlled ApplyInnerTTKAdderNoCarry) ([], (xs, ys)); + (Controlled ApplyInnerTTKAdderNoCarry)([], (xs, ys)); } - controlled ( controls, ... ) { - Fact(Length(xs) == Length(ys), - "Input registers must have the same number of qubits." ); + controlled (controls, ...) { + Fact(Length(xs) == Length(ys), "Input registers must have the same number of qubits."); for idx in 0..Length(xs) - 2 { - CCNOT (xs[idx], ys[idx], xs[idx + 1]); + CCNOT(xs[idx], ys[idx], xs[idx + 1]); } for idx in Length(xs)-1..-1..1 { Controlled CNOT(controls, (xs[idx], ys[idx])); @@ -102,20 +98,18 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// The specified controlled operation makes use of symmetry and mutual /// cancellation of operations to improve on the default implementation /// that adds a control to every operation. - internal operation ApplyInnerTTKAdderWithCarry(xs : Qubit[], ys : Qubit[]) - : Unit is Adj + Ctl { + internal operation ApplyInnerTTKAdderWithCarry(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { body (...) { (Controlled ApplyInnerTTKAdderWithCarry)([], (xs, ys)); } - controlled ( controls, ... ) { - Fact(Length(xs)+1 == Length(ys), - "ys must be one qubit longer then xs." ); + controlled (controls, ...) { + Fact(Length(xs) + 1 == Length(ys), "ys must be one qubit longer then xs."); Fact(Length(xs) > 0, "Array should not be empty."); let nQubits = Length(xs); for idx in 0..nQubits - 2 { - CCNOT(xs[idx], ys[idx], xs[idx+1]); + CCNOT(xs[idx], ys[idx], xs[idx + 1]); } (Controlled CCNOT)(controls, (xs[nQubits-1], ys[nQubits-1], ys[nQubits])); for idx in nQubits - 1..-1..1 { @@ -127,8 +121,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Implements Half-adder. Adds qubit x to qubit y and sets carryOut appropriately - internal operation HalfAdderForInc(x : Qubit, y : Qubit, carryOut : Qubit) - : Unit is Adj + Ctl { + internal operation HalfAdderForInc(x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj + Ctl { body (...) { CCNOT(x, y, carryOut); CNOT(x, y); @@ -153,8 +146,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Implements Full-adder. Adds qubit carryIn and x to qubit y and sets carryOut appropriately. - internal operation FullAdderForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) - : Unit is Adj + Ctl { + internal operation FullAdderForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj + Ctl { body (...) { // TODO: cannot use `Carry` operation here CNOT(carryIn, x); @@ -180,8 +172,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { } // Computes carryOut := carryIn + x + y - internal operation FullAdder(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) - : Unit is Adj { + internal operation FullAdder(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj { CNOT(x, y); CNOT(x, carryIn); ApplyAndAssuming0Target(y, carryIn, carryOut); @@ -192,8 +183,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Computes carry bit for a full adder. - internal operation CarryForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) - : Unit is Adj + Ctl { + internal operation CarryForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj + Ctl { body (...) { CNOT(carryIn, x); CNOT(carryIn, y); @@ -213,8 +203,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// # Summary /// Uncomputes carry bit for a full adder. - internal operation UncarryForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) - : Unit is Adj + Ctl { + internal operation UncarryForInc(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj + Ctl { body (...) { CNOT(carryIn, carryOut); Adjoint ApplyAndAssuming0Target(x, y, carryOut); @@ -255,8 +244,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// [arXiv:1212.5069](https://arxiv.org/abs/1212.5069) /// doi:10.1103/PhysRevA.87.022328 @Config(Unrestricted) - internal operation ApplyAndAssuming0Target(control1 : Qubit, control2 : Qubit, target: Qubit) - : Unit is Adj { // NOTE: Eventually this operation will be public and intrinsic. + internal operation ApplyAndAssuming0Target(control1 : Qubit, control2 : Qubit, target : Qubit) : Unit is Adj { + // NOTE: Eventually this operation will be public and intrinsic. body (...) { if not CheckZero(target) { fail "ApplyAndAssuming0Target expects `target` to be in |0> state."; @@ -300,8 +289,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// [arXiv:1212.5069](https://arxiv.org/abs/1212.5069) /// doi:10.1103/PhysRevA.87.022328 @Config(Base) - internal operation ApplyAndAssuming0Target(control1 : Qubit, control2 : Qubit, target: Qubit) - : Unit is Adj { + internal operation ApplyAndAssuming0Target(control1 : Qubit, control2 : Qubit, target : Qubit) : Unit is Adj { H(target); T(target); CNOT(control1, target); @@ -309,8 +297,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { within { CNOT(target, control1); CNOT(target, control2); - } - apply { + } apply { Adjoint T(control1); Adjoint T(control2); T(target); @@ -323,12 +310,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Computes carries for the look-ahead adder internal operation ComputeCarries(ps : Qubit[], gs : Qubit[]) : Unit is Adj { let n = Length(gs); - Fact(Length(ps)+1 == n, "Register gs must be one qubit longer than register gs."); + Fact(Length(ps) + 1 == n, "Register gs must be one qubit longer than register gs."); let T = Floor(Lg(IntAsDouble(n))); use qs = Qubit[n - HammingWeightI(n) - T]; - let registerPartition = MappedOverRange(t -> Floor(IntAsDouble(n) / IntAsDouble(2^t)) - 1, 1..T - 1); + let registerPartition = MappedOverRange(t -> Floor(IntAsDouble(n) / IntAsDouble(2 ^ t)) - 1, 1..T - 1); let pWorkspace = [ps] + Partitioned(registerPartition, qs); within { @@ -383,11 +370,11 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let n = Length(gs); for t in 1..T { - let length = Floor(IntAsDouble(n) / IntAsDouble(2^t)) - 1; + let length = Floor(IntAsDouble(n) / IntAsDouble(2 ^ t)) - 1; let ps = pWorkspace[t - 1][0..2...]; for m in 0..length { - CCNOT(gs[2^t * m + 2^(t - 1) - 1], ps[m], gs[2^t * m + 2^t - 1]); + CCNOT(gs[2 ^ t * m + 2 ^ (t - 1) - 1], ps[m], gs[2 ^ t * m + 2 ^ t - 1]); } } } @@ -399,16 +386,16 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let start = Floor(Lg(IntAsDouble(2 * n) / 3.0)); for t in start..-1..1 { - let length = Floor(IntAsDouble(n - 2^(t - 1)) / IntAsDouble(2^t)); + let length = Floor(IntAsDouble(n - 2 ^ (t - 1)) / IntAsDouble(2 ^ t)); let ps = pWorkspace[t - 1][1..2...]; for m in 1..length { - CCNOT(gs[2^t * m - 1], ps[m - 1], gs[2^t * m + 2^(t - 1) - 1]); + CCNOT(gs[2 ^ t * m - 1], ps[m - 1], gs[2 ^ t * m + 2 ^ (t - 1) - 1]); } } } - internal operation PhaseGradient (qs : Qubit[]) : Unit is Adj + Ctl { + internal operation PhaseGradient(qs : Qubit[]) : Unit is Adj + Ctl { for i in IndexRange(qs) { R1Frac(1, i, qs[i]); } @@ -423,18 +410,19 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// (if `invertControl` is false). If `invertControl` is true, the `action` /// is applied in the opposite situation. internal operation ApplyActionIfGreaterThanOrEqualConstant<'T>( - invertControl: Bool, - action: 'T => Unit is Adj + Ctl, - c: BigInt, - x: Qubit[], - target: 'T) : Unit is Adj + Ctl { + invertControl : Bool, + action : 'T => Unit is Adj + Ctl, + c : BigInt, + x : Qubit[], + target : 'T + ) : Unit is Adj + Ctl { let bitWidth = Length(x); if c == 0L { if not invertControl { action(target); } - } elif c >= (2L^bitWidth) { + } elif c >= (2L ^ bitWidth) { if invertControl { action(target); } @@ -453,15 +441,12 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { use qs = Qubit[bitWidthNormalized - 1]; let cs1 = IsEmpty(qs) ? [] | [Head(xNormalized)] + Most(qs); - Fact(Length(cs1) == Length(qs), - "Arrays should be of the same length."); + Fact(Length(cs1) == Length(qs), "Arrays should be of the same length."); within { for i in 0..Length(cs1)-1 { - let op = - cNormalized &&& (1L <<< (i+1)) != 0L ? - ApplyAndAssuming0Target | ApplyOrAssuming0Target; - op(cs1[i], xNormalized[i+1], qs[i]); + let op = cNormalized &&& (1L <<< (i + 1)) != 0L ? ApplyAndAssuming0Target | ApplyOrAssuming0Target; + op(cs1[i], xNormalized[i + 1], qs[i]); } } apply { let control = IsEmpty(qs) ? Tail(x) | Tail(qs); @@ -480,12 +465,13 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// Applies `action` to `target` if the sum of `x` and `y` registers /// overflows, i.e. there's a carry out (if `invertControl` is false). /// If `invertControl` is true, the `action` is applied when there's no carry out. - internal operation ApplyActionIfSumOverflows<'T> ( + internal operation ApplyActionIfSumOverflows<'T>( action : 'T => Unit is Adj + Ctl, x : Qubit[], y : Qubit[], invertControl : Bool, - target : 'T) : Unit is Adj + Ctl { + target : 'T + ) : Unit is Adj + Ctl { let n = Length(x); Fact(n >= 1, "Registers must contain at least one qubit."); @@ -516,7 +502,8 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { internal operation CarryWith1CarryIn( x : Qubit, y : Qubit, - carryOut : Qubit) : Unit is Adj + Ctl { + carryOut : Qubit + ) : Unit is Adj + Ctl { body (...) { X(x); @@ -540,9 +527,10 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// qubit to be used in a multi-controlled scenarios. It provides /// controlled version that collects controls into one qubit /// by applying AND chain using auxiliary qubit array. - internal operation ApplyAsSinglyControlled<'TIn> ( - op : ( 'TIn => Unit is Adj + Ctl ), - input : 'TIn ) : Unit is Adj + Ctl { + internal operation ApplyAsSinglyControlled<'TIn>( + op : ('TIn => Unit is Adj + Ctl), + input : 'TIn + ) : Unit is Adj + Ctl { body (...) { op(input); @@ -559,7 +547,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { within { ApplyAndAssuming0Target(ctls[0], ctls[1], aux[0]); for i in 1..n-2 { - ApplyAndAssuming0Target(aux[i-1], ctls[i+1], aux[i]); + ApplyAndAssuming0Target(aux[i-1], ctls[i + 1], aux[i]); } } apply { Controlled op(aux[n-2..n-2], input); diff --git a/library/std/unstable_state_preparation.qs b/library/std/unstable_state_preparation.qs index f04688add3..197b280b37 100644 --- a/library/std/unstable_state_preparation.qs +++ b/library/std/unstable_state_preparation.qs @@ -115,11 +115,15 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { let coefficientsPadded = Padded(-2 ^ nQubits, ComplexPolar(0.0, 0.0), coefficients); let idxTarget = 0; // Determine what controls to apply - let rngControl = nQubits > 1 ? (1 .. (nQubits - 1)) | (1..0); + let rngControl = nQubits > 1 ? (1..(nQubits - 1)) | (1..0); // Note we use the reversed qubits array to get the endianness ordering that we expect // when corresponding qubit state to state vector index. Adjoint ApproximatelyUnprepareArbitraryState( - tolerance, coefficientsPadded, rngControl, idxTarget, Reversed(qubits) + tolerance, + coefficientsPadded, + rngControl, + idxTarget, + Reversed(qubits) ); } @@ -130,7 +134,7 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { coefficients : ComplexPolar[], rngControl : Range, idxTarget : Int, - register: Qubit[] + register : Qubit[] ) : Unit is Adj + Ctl { // For each 2D block, compute disentangling single-qubit rotation parameters @@ -201,7 +205,8 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { coefficients : Double[], pauli : Pauli, control : Qubit[], - target : Qubit) : Unit is Adj + Ctl { + target : Qubit + ) : Unit is Adj + Ctl { if pauli == PauliZ { ApproximatelyMultiplexZ(tolerance, coefficients, control, target); @@ -225,13 +230,14 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { /// # Summary /// Implementation step of arbitrary state preparation procedure. internal function StatePreparationSBMComputeCoefficients( - coefficients : ComplexPolar[]) : (Double[], Double[], ComplexPolar[]) { + coefficients : ComplexPolar[] + ) : (Double[], Double[], ComplexPolar[]) { mutable disentanglingZ = []; mutable disentanglingY = []; mutable newCoefficients = []; - for idxCoeff in 0 .. 2 .. Length(coefficients) - 1 { + for idxCoeff in 0..2..Length(coefficients) - 1 { let (rt, phi, theta) = BlochSphereCoordinates(coefficients[idxCoeff], coefficients[idxCoeff + 1]); set disentanglingZ += [0.5 * phi]; set disentanglingY += [0.5 * theta]; @@ -256,9 +262,10 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { /// /// # Output /// A tuple containing `(ComplexPolar(r, t), phi, theta)`. - internal function BlochSphereCoordinates ( + internal function BlochSphereCoordinates( a0 : ComplexPolar, - a1 : ComplexPolar) : (ComplexPolar, Double, Double) { + a1 : ComplexPolar + ) : (ComplexPolar, Double, Double) { let abs0 = AbsComplexPolar(a0); let abs1 = AbsComplexPolar(a1); @@ -314,7 +321,8 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { tolerance : Double, coefficients : Double[], control : Qubit[], - target : Qubit) : Unit is Adj + Ctl { + target : Qubit + ) : Unit is Adj + Ctl { body (...) { // pad coefficients length at tail to a power of 2. @@ -343,12 +351,12 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { // pad coefficients length to a power of 2. let coefficientsPadded = Padded(2 ^ (Length(control) + 1), 0.0, Padded(-2 ^ Length(control), 0.0, coefficients)); let (coefficients0, coefficients1) = MultiplexZCoefficients(coefficientsPadded); - ApproximatelyMultiplexZ(tolerance,coefficients0, control, target); - if AnyOutsideToleranceD(tolerance,coefficients1) { + ApproximatelyMultiplexZ(tolerance, coefficients0, control, target); + if AnyOutsideToleranceD(tolerance, coefficients1) { within { Controlled X(controlRegister, target); } apply { - ApproximatelyMultiplexZ(tolerance,coefficients1, control, target); + ApproximatelyMultiplexZ(tolerance, coefficients1, control, target); } } } @@ -361,7 +369,7 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { mutable coefficients0 = []; mutable coefficients1 = []; - for idxCoeff in 0 .. newCoefficientsLength - 1 { + for idxCoeff in 0..newCoefficientsLength - 1 { set coefficients0 += [0.5 * (coefficients[idxCoeff] + coefficients[idxCoeff + newCoefficientsLength])]; set coefficients1 += [0.5 * (coefficients[idxCoeff] - coefficients[idxCoeff + newCoefficientsLength])]; } diff --git a/library/std/unstable_table_lookup.qs b/library/std/unstable_table_lookup.qs index 5cb064528c..9258d5c437 100644 --- a/library/std/unstable_table_lookup.qs +++ b/library/std/unstable_table_lookup.qs @@ -52,11 +52,12 @@ namespace Microsoft.Quantum.Unstable.TableLookup { body (...) { let (N, n) = DimensionsForSelect(data, address); - if N == 1 { // base case + if N == 1 { + // base case WriteMemoryContents(Head(data), target); } else { let (most, tail) = MostAndTail(address[...n - 1]); - let parts = Partitioned([2^(n - 1)], data); + let parts = Partitioned([2 ^ (n - 1)], data); within { X(tail); @@ -106,13 +107,14 @@ namespace Microsoft.Quantum.Unstable.TableLookup { let (N, n) = DimensionsForSelect(data, address); if BeginEstimateCaching("Microsoft.Quantum.Unstable.TableLookup.SinglyControlledSelect", N) { - if N == 1 { // base case + if N == 1 { + // base case Controlled WriteMemoryContents([ctl], (Head(data), target)); } else { use helper = Qubit(); let (most, tail) = MostAndTail(address[...n - 1]); - let parts = Partitioned([2^(n - 1)], data); + let parts = Partitioned([2 ^ (n - 1)], data); within { X(tail); @@ -143,7 +145,8 @@ namespace Microsoft.Quantum.Unstable.TableLookup { let n = Ceiling(Lg(IntAsDouble(N))); Fact( Length(address) >= n, - $"address register is too small, requires at least {n} qubits"); + $"address register is too small, requires at least {n} qubits" + ); return (N, n); } @@ -154,7 +157,8 @@ namespace Microsoft.Quantum.Unstable.TableLookup { ) : Unit is Adj + Ctl { Fact( Length(value) == Length(target), - "number of data bits must equal number of target qubits"); + "number of data bits must equal number of target qubits" + ); ApplyPauliFromBitString(PauliX, true, value, target); } @@ -175,17 +179,17 @@ namespace Microsoft.Quantum.Unstable.TableLookup { let l = MinI(Floor(Lg(IntAsDouble(numBits))), numAddressBits - 1); Fact( l < numAddressBits, - $"l = {l} must be smaller than {numAddressBits}"); + $"l = {l} must be smaller than {numAddressBits}" + ); let res = Mapped(r -> r == One, ForEach(MResetX, target)); - let dataFixup = Chunks(2^l, Padded(-2^numAddressBits, false, - Mapped(MustBeFixed(res, _), data))); + let dataFixup = Chunks(2 ^ l, Padded(-2 ^ numAddressBits, false, Mapped(MustBeFixed(res, _), data))); let numAddressBitsFixup = numAddressBits - l; let selectParts = Partitioned([l], select); - let targetFixup = target[...2^l - 1]; + let targetFixup = target[...2 ^ l - 1]; within { EncodeUnary(selectParts[0], targetFixup); @@ -219,8 +223,8 @@ namespace Microsoft.Quantum.Unstable.TableLookup { target : Qubit[] ) : Unit is Adj { Fact( - Length(target) == 2^Length(input), - $"target register should be of length {2^Length(input)}, but is {Length(target)}" + Length(target) == 2 ^ Length(input), + $"target register should be of length {2 ^ Length(input)}, but is {Length(target)}" ); X(Head(target)); @@ -231,7 +235,7 @@ namespace Microsoft.Quantum.Unstable.TableLookup { CNOT(target[1], target[0]); } else { // targets are the first and second 2^i qubits of the target register - let split = Partitioned([2^i, 2^i], target); + let split = Partitioned([2 ^ i, 2 ^ i], target); for j in IndexRange(split[0]) { ApplyAndAssuming0Target(input[i], split[0][j], split[1][j]); CNOT(split[1][j], split[0][j]); @@ -242,8 +246,8 @@ namespace Microsoft.Quantum.Unstable.TableLookup { } internal newtype AndChain = ( - NGarbageQubits: Int, - Apply: Qubit[] => Unit is Adj + NGarbageQubits : Int, + Apply : Qubit[] => Unit is Adj ); internal function MakeAndChain(ctls : Qubit[], target : Qubit) : AndChain { diff --git a/samples/algorithms/BernsteinVazirani.qs b/samples/algorithms/BernsteinVazirani.qs index 70b983b996..7a640d5a40 100644 --- a/samples/algorithms/BernsteinVazirani.qs +++ b/samples/algorithms/BernsteinVazirani.qs @@ -44,7 +44,8 @@ namespace Sample { let decodedInteger = ResultArrayAsInt(decodedBitString); Fact( decodedInteger == integer, - $"Decoded integer {decodedInteger}, but expected {integer}."); + $"Decoded integer {decodedInteger}, but expected {integer}." + ); Message($"Successfully decoded bit string as int: {decodedInteger}"); set decodedIntegers += [decodedInteger]; @@ -78,8 +79,7 @@ namespace Sample { /// - [ *Ethan Bernstein and Umesh Vazirani*, /// SIAM J. Comput., 26(5), 1411–1473, 1997 ] /// (https://doi.org/10.1137/S0097539796300921) - operation BernsteinVazirani(Uf : ((Qubit[], Qubit) => Unit), n : Int) - : Result[] { + operation BernsteinVazirani(Uf : ((Qubit[], Qubit) => Unit), n : Int) : Result[] { // We allocate n + 1 clean qubits. Note that the function Uf is defined // on inputs of the form (x, y), where x has n bits and y has 1 bit. use queryRegister = Qubit[n]; @@ -135,20 +135,19 @@ namespace Sample { operation ApplyParityOperation( bitStringAsInt : Int, xRegister : Qubit[], - yQubit : Qubit) - : Unit { + yQubit : Qubit + ) : Unit { // `xRegister` muts have enough qubits to represent the integer. let requiredBits = BitSizeI(bitStringAsInt); let availableQubits = Length(xRegister); Fact( availableQubits >= requiredBits, - $"Integer value {bitStringAsInt} requires {requiredBits} bits to " + - $"be represented but the quantum register only has " + - $"{availableQubits} qubits"); + $"Integer value {bitStringAsInt} requires {requiredBits} bits to " + $"be represented but the quantum register only has " + $"{availableQubits} qubits" + ); // Apply the quantum operations that encode the bit string. for index in IndexRange(xRegister) { - if ((bitStringAsInt &&& 2^index) != 0) { + if ((bitStringAsInt &&& 2 ^ index) != 0) { CNOT(xRegister[index], yQubit); } } @@ -158,8 +157,7 @@ namespace Sample { /// Returns black-box operations (Qubit[], Qubit) => () of the form /// U_f |𝑥〉|𝑦〉 = |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉. /// We define 𝑓 by providing the bit string 𝑟⃗ as an integer. - operation EncodeIntegerAsParityOperation(bitStringAsInt : Int) - : (Qubit[], Qubit) => Unit { + operation EncodeIntegerAsParityOperation(bitStringAsInt : Int) : (Qubit[], Qubit) => Unit { return ApplyParityOperation(bitStringAsInt, _, _); } } diff --git a/samples/algorithms/BernsteinVaziraniNISQ.qs b/samples/algorithms/BernsteinVaziraniNISQ.qs index 5676057bd8..daeb059859 100644 --- a/samples/algorithms/BernsteinVaziraniNISQ.qs +++ b/samples/algorithms/BernsteinVaziraniNISQ.qs @@ -30,7 +30,9 @@ namespace Sample { let secretBitString = SecretBitStringAsBoolArray(); let parityOperation = EncodeBitStringAsParityOperation(secretBitString); let decodedBitString = BernsteinVazirani( - parityOperation, Length(secretBitString)); + parityOperation, + Length(secretBitString) + ); return decodedBitString; } @@ -60,8 +62,7 @@ namespace Sample { /// - [ *Ethan Bernstein and Umesh Vazirani*, /// SIAM J. Comput., 26(5), 1411–1473, 1997 ] /// (https://doi.org/10.1137/S0097539796300921) - operation BernsteinVazirani(Uf : ((Qubit[], Qubit) => Unit), n : Int) - : Result[] { + operation BernsteinVazirani(Uf : ((Qubit[], Qubit) => Unit), n : Int) : Result[] { // We allocate n + 1 clean qubits. Note that the function parameter Uf is defined // on inputs of the form (x, y), where x has n bits and y has 1 bit. use queryRegister = Qubit[n]; @@ -117,15 +118,15 @@ namespace Sample { operation ApplyParityOperation( bitStringAsBoolArray : Bool[], xRegister : Qubit[], - yQubit : Qubit) - : Unit { + yQubit : Qubit + ) : Unit { // `xRegister` muts have enough qubits to represent the integer. let requiredBits = Length(bitStringAsBoolArray); let availableQubits = Length(xRegister); Fact( availableQubits >= requiredBits, - $"The bitstring has {requiredBits} bits but the quantum register " + - $"only has {availableQubits} qubits"); + $"The bitstring has {requiredBits} bits but the quantum register " + $"only has {availableQubits} qubits" + ); // Apply the quantum operations that encode the bit string. for (index, bit) in Enumerated(bitStringAsBoolArray) { @@ -139,8 +140,7 @@ namespace Sample { /// This is a higher-order operation which returns an operation (Qubit[], Qubit) => () of the form /// U_f |𝑥〉|𝑦〉 = |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉. /// We define 𝑓 by providing the bit string 𝑟⃗ as an integer. - operation EncodeBitStringAsParityOperation(bitStringAsBoolArray : Bool[]) - : (Qubit[], Qubit) => Unit { + operation EncodeBitStringAsParityOperation(bitStringAsBoolArray : Bool[]) : (Qubit[], Qubit) => Unit { return ApplyParityOperation(bitStringAsBoolArray, _, _); } diff --git a/samples/algorithms/BitFlipCode.qs b/samples/algorithms/BitFlipCode.qs index 19b2308661..6b04ecac9d 100644 --- a/samples/algorithms/BitFlipCode.qs +++ b/samples/algorithms/BitFlipCode.qs @@ -117,16 +117,15 @@ namespace Sample { // Determine which of the three qubits has the error based on the // parity measurements. - let indexOfError = - if (parity01, parity12) == (One, Zero) { - 0 - } elif (parity01, parity12) == (One, One) { - 1 - } elif (parity01, parity12) == (Zero, One) { - 2 - } else { + let indexOfError = if (parity01, parity12) == (One, Zero) { + 0 + } elif (parity01, parity12) == (One, One) { + 1 + } elif (parity01, parity12) == (Zero, One) { + 2 + } else { -1 - }; + }; // If an error was detected, correct that qubit. if indexOfError > -1 { diff --git a/samples/algorithms/DeutschJozsa.qs b/samples/algorithms/DeutschJozsa.qs index 718a69b9bd..4c0b0f1f87 100644 --- a/samples/algorithms/DeutschJozsa.qs +++ b/samples/algorithms/DeutschJozsa.qs @@ -39,9 +39,7 @@ namespace Sample { for (name, fn, shouldBeConstant) in nameFunctionTypeTuples { let isConstant = DeutschJozsa(fn, 5); if (isConstant != shouldBeConstant) { - let shouldBeConstantStr = shouldBeConstant ? - "constant" | - "balanced"; + let shouldBeConstantStr = shouldBeConstant ? "constant" | "balanced"; fail $"{name} should be detected as {shouldBeConstantStr}"; } @@ -104,7 +102,7 @@ namespace Sample { // state so that they can be safely deallocated at the end of the block. // The loop also sets `result` to `true` if all measurement results are // `Zero`, i.e. if the function is a constant function, and sets - // `result` to `false` if not, which according to the assumption on 𝑓 + // `result` to `false` if not, which according to the assumption on 𝑓 // means that it must be balanced. mutable result = true; for q in queryRegister { @@ -131,7 +129,7 @@ namespace Sample { // A more complex constant Boolean function. // It applies X to every input basis vector. operation ConstantBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..(2^Length(args))-1 { + for i in 0..(2 ^ Length(args))-1 { ApplyControlledOnInt(i, X, args, target); } } @@ -139,7 +137,7 @@ namespace Sample { // A more complex balanced Boolean function. // It applies X to half of the input basis vectors. operation BalancedBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..2..(2^Length(args))-1 { + for i in 0..2..(2 ^ Length(args))-1 { ApplyControlledOnInt(i, X, args, target); } } diff --git a/samples/algorithms/Entanglement.qs b/samples/algorithms/Entanglement.qs index de63ed8804..dca96c80f7 100644 --- a/samples/algorithms/Entanglement.qs +++ b/samples/algorithms/Entanglement.qs @@ -14,7 +14,7 @@ namespace Sample { // Allocate the two qubits that will be entangled. use (q1, q2) = (Qubit(), Qubit()); - // Set the first qubit in superposition by calling the `H` operation, + // Set the first qubit in superposition by calling the `H` operation, // which applies a Hadamard transformation to the qubit. // Then, entangle the two qubits using the `CNOT` operation. H(q1); diff --git a/samples/algorithms/Grover.qs b/samples/algorithms/Grover.qs index 41410dba4b..007794ca5d 100644 --- a/samples/algorithms/Grover.qs +++ b/samples/algorithms/Grover.qs @@ -37,7 +37,8 @@ namespace Sample { operation GroverSearch( nQubits : Int, iterations : Int, - phaseOracle : Qubit[] => Unit) : Result[] { + phaseOracle : Qubit[] => Unit + ) : Result[] { use qubits = Qubit[nQubits]; diff --git a/samples/algorithms/HiddenShift.qs b/samples/algorithms/HiddenShift.qs index 32f9bf58b5..35d2caa852 100644 --- a/samples/algorithms/HiddenShift.qs +++ b/samples/algorithms/HiddenShift.qs @@ -31,11 +31,13 @@ namespace Sample { let hiddenShiftBitString = FindHiddenShift( BentFunction, register => ShiftedBentFunction(shift, register), - nQubits); + nQubits + ); let hiddenShift = ResultArrayAsInt(hiddenShiftBitString); Fact( hiddenShift == shift, - $"Found shift {hiddenShift}, but expected {shift}."); + $"Found shift {hiddenShift}, but expected {shift}." + ); Message($"Found {shift} successfully!"); set hiddenShifts += [hiddenShift]; } @@ -81,11 +83,11 @@ namespace Sample { /// - [*Martin Roetteler*, /// Proc. SODA 2010, ACM, pp. 448-457, 2010] /// (https://doi.org/10.1137/1.9781611973075.37) - operation FindHiddenShift ( + operation FindHiddenShift( Ufstar : (Qubit[] => Unit), Ug : (Qubit[] => Unit), - n : Int) - : Result[] { + n : Int + ) : Result[] { // We allocate n clean qubits. Note that the function Ufstar and Ug are // unitary operations on n qubits defined via phase encoding. use qubits = Qubit[n]; @@ -142,7 +144,7 @@ namespace Sample { operation BentFunction(register : Qubit[]) : Unit { Fact(Length(register) % 2 == 0, "Length of register must be even."); let u = Length(register) / 2; - let xs = register[0 .. u - 1]; + let xs = register[0..u - 1]; let ys = register[u...]; for index in 0..u-1 { CZ(xs[index], ys[index]); diff --git a/samples/algorithms/HiddenShiftNISQ.qs b/samples/algorithms/HiddenShiftNISQ.qs index 75d8cdd4ce..635248ac32 100644 --- a/samples/algorithms/HiddenShiftNISQ.qs +++ b/samples/algorithms/HiddenShiftNISQ.qs @@ -29,7 +29,8 @@ namespace Sample { let hiddenShiftBitString = FindHiddenShift( BentFunction, register => ShiftedBentFunction(shiftAsInt, register), - Length(shiftAsBoolArray)); + Length(shiftAsBoolArray) + ); return hiddenShiftBitString; } @@ -72,11 +73,11 @@ namespace Sample { /// - [*Martin Roetteler*, /// Proc. SODA 2010, ACM, pp. 448-457, 2010] /// (https://doi.org/10.1137/1.9781611973075.37) - operation FindHiddenShift ( + operation FindHiddenShift( Ufstar : (Qubit[] => Unit), Ug : (Qubit[] => Unit), - n : Int) - : Result[] { + n : Int + ) : Result[] { // We allocate n clean qubits. Note that the function Ufstar and Ug are // unitary operations on n qubits defined via phase encoding. use qubits = Qubit[n]; @@ -133,7 +134,7 @@ namespace Sample { operation BentFunction(register : Qubit[]) : Unit { Fact(Length(register) % 2 == 0, "Length of register must be even."); let u = Length(register) / 2; - let xs = register[0 .. u - 1]; + let xs = register[0..u - 1]; let ys = register[u...]; for index in 0..u-1 { CZ(xs[index], ys[index]); diff --git a/samples/algorithms/Measurement.qs b/samples/algorithms/Measurement.qs index 8a0f1959de..4f0d9ad15e 100644 --- a/samples/algorithms/Measurement.qs +++ b/samples/algorithms/Measurement.qs @@ -14,7 +14,7 @@ namespace Sample { open Microsoft.Quantum.Measurement; @EntryPoint() - operation Main () : (Result, Result[]) { + operation Main() : (Result, Result[]) { // The `M` operation performs a measurement of a single qubit in the // computational basis, also known as the Pauli Z basis. use q = Qubit(); diff --git a/samples/algorithms/PhaseFlipCode.qs b/samples/algorithms/PhaseFlipCode.qs index b70ece981f..5248d13bd3 100644 --- a/samples/algorithms/PhaseFlipCode.qs +++ b/samples/algorithms/PhaseFlipCode.qs @@ -138,16 +138,15 @@ namespace Sample { // Determine which of the three qubits is has the error based on the // parity measurements. - let indexOfError = - if (parity01, parity12) == (One, Zero) { - 0 - } elif (parity01, parity12) == (One, One) { - 1 - } elif (parity01, parity12) == (Zero, One) { - 2 - } else { + let indexOfError = if (parity01, parity12) == (One, Zero) { + 0 + } elif (parity01, parity12) == (One, One) { + 1 + } elif (parity01, parity12) == (Zero, One) { + 2 + } else { -1 - }; + }; // If an error was detected, correct that qubit. if indexOfError > -1 { diff --git a/samples/algorithms/QRNG.qs b/samples/algorithms/QRNG.qs index c04994e4cc..95b951a8e4 100644 --- a/samples/algorithms/QRNG.qs +++ b/samples/algorithms/QRNG.qs @@ -42,7 +42,7 @@ namespace Sample { // Allocate a qubit. use q = Qubit(); - // Set the qubit into superposition of 0 and 1 using the Hadamard + // Set the qubit into superposition of 0 and 1 using the Hadamard // operation `H`. H(q); diff --git a/samples/algorithms/RandomBit.qs b/samples/algorithms/RandomBit.qs index 66538329ee..4d4c119f2d 100644 --- a/samples/algorithms/RandomBit.qs +++ b/samples/algorithms/RandomBit.qs @@ -16,7 +16,7 @@ namespace Sample { // Set the qubit in superposition by applying a Hadamard transformation. H(qubit); - // Measure the qubit. There is a 50% probability of measuring either + // Measure the qubit. There is a 50% probability of measuring either // `Zero` or `One`. let result = M(qubit); diff --git a/samples/algorithms/Shor.qs b/samples/algorithms/Shor.qs index 787f168b7b..a991f815c0 100644 --- a/samples/algorithms/Shor.qs +++ b/samples/algorithms/Shor.qs @@ -64,30 +64,26 @@ namespace Sample { // Set the flag and factors values if the continued // fractions classical algorithm succeeds. - set (foundFactors, factors) = - MaybeFactorsFromPeriod(number, generator, period); + set (foundFactors, factors) = MaybeFactorsFromPeriod(number, generator, period); } // In this case, we guessed a divisor by accident. else { // Find divisor. let gcd = GreatestCommonDivisorI(number, generator); - Message($"We have guessed a divisor {gcd} by accident. " + - "No quantum computation was done."); + Message($"We have guessed a divisor {gcd} by accident. " + "No quantum computation was done."); // Set the flag `foundFactors` to true, indicating that we // succeeded in finding factors. set foundFactors = true; set factors = (gcd, number / gcd); } - set attempt = attempt+1; + set attempt = attempt + 1; if (attempt > 100) { fail "Failed to find factors: too many attempts!"; } - } - until foundFactors + } until foundFactors fixup { - Message("The estimated period did not yield a valid factor. " + - "Trying again."); + Message("The estimated period did not yield a valid factor. " + "Trying again."); } // Return the factorization @@ -116,8 +112,8 @@ namespace Sample { function MaybeFactorsFromPeriod( modulus : Int, generator : Int, - period : Int) - : (Bool, (Int, Int)) { + period : Int + ) : (Bool, (Int, Int)) { // Period finding reduces to factoring only if period is even if period % 2 == 0 { @@ -175,13 +171,14 @@ namespace Sample { modulus : Int, frequencyEstimate : Int, bitsPrecision : Int, - currentDivisor : Int) - : Int { + currentDivisor : Int + ) : Int { // Now we use the ContinuedFractionConvergentI function to recover s/r // from dyadic fraction k/2^bitsPrecision. let (numerator, period) = ContinuedFractionConvergentI( (frequencyEstimate, 2 ^ bitsPrecision), - modulus); + modulus + ); // ContinuedFractionConvergentI does not guarantee the signs of the // numerator and denominator. Here we make sure that both are positive @@ -189,9 +186,7 @@ namespace Sample { let (numeratorAbs, periodAbs) = (AbsI(numerator), AbsI(period)); // Compute and return the newly found divisor. - let period = - (periodAbs * currentDivisor) / - GreatestCommonDivisorI(currentDivisor, periodAbs); + let period = (periodAbs * currentDivisor) / GreatestCommonDivisorI(currentDivisor, periodAbs); Message($"Found period={period}"); return period; } @@ -215,7 +210,8 @@ namespace Sample { // valid. Fact( GreatestCommonDivisorI(generator, modulus) == 1, - "`generator` and `modulus` must be co-prime"); + "`generator` and `modulus` must be co-prime" + ); // Number of bits in the modulus with respect to which we are estimating // the period. @@ -234,9 +230,12 @@ namespace Sample { let frequencyEstimate = EstimateFrequency(generator, modulus, bitsize); if frequencyEstimate != 0 { return PeriodFromFrequency( - modulus, frequencyEstimate, bitsPrecision, 1); - } - else { + modulus, + frequencyEstimate, + bitsPrecision, + 1 + ); + } else { Message("The estimated frequency was 0, trying again."); return 1; } @@ -258,10 +257,9 @@ namespace Sample { /// /// # Output /// The numerator k of dyadic fraction k/2^bitsPrecision approximating s/r. - operation EstimateFrequency(generator : Int,modulus : Int, bitsize : Int) - : Int { + operation EstimateFrequency(generator : Int, modulus : Int, bitsize : Int) : Int { mutable frequencyEstimate = 0; - let bitsPrecision = 2 * bitsize + 1; + let bitsPrecision = 2 * bitsize + 1; Message($"Estimating frequency with bitsPrecision={bitsPrecision}."); // Allocate qubits for the superposition of eigenstates of the oracle @@ -281,7 +279,8 @@ namespace Sample { H(c); Controlled ApplyOrderFindingOracle( [c], - (generator, modulus, 1 <<< idx, eigenstateRegister)); + (generator, modulus, 1 <<< idx, eigenstateRegister) + ); R1Frac(frequencyEstimate, bitsPrecision-1-idx, c); H(c); if M(c) == One { @@ -316,10 +315,11 @@ namespace Sample { /// given power of the generator. The multiplication is performed modulo /// `modulus`. internal operation ApplyOrderFindingOracle( - generator : Int, modulus : Int, power : Int, target : Qubit[] - ) - : Unit - is Adj + Ctl { + generator : Int, + modulus : Int, + power : Int, + target : Qubit[] + ) : Unit is Adj + Ctl { // The oracle we use for order finding implements |x⟩ ↦ |x⋅a mod N⟩. We // also use `ExpModI` to compute a by which x must be multiplied. Also // note that we interpret target as unsigned integer in little-endian @@ -327,7 +327,8 @@ namespace Sample { ModularMultiplyByConstant( modulus, ExpModI(generator, power, modulus), - target); + target + ); } /// # Summary @@ -345,14 +346,14 @@ namespace Sample { /// Constant by which to multiply |𝑦⟩ /// ## y /// Quantum register of target - internal operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[]) - : Unit is Adj + Ctl { + internal operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[]) : Unit is Adj + Ctl { use qs = Qubit[Length(y)]; for idx in IndexRange(y) { let shiftedC = (c <<< idx) % modulus; Controlled ModularAddConstant( [y[idx]], - (modulus, shiftedC, qs)); + (modulus, shiftedC, qs) + ); } for idx in IndexRange(y) { SWAP(y[idx], qs[idx]); @@ -362,7 +363,8 @@ namespace Sample { let shiftedC = (invC <<< idx) % modulus; Controlled ModularAddConstant( [y[idx]], - (modulus, modulus - shiftedC, qs)); + (modulus, modulus - shiftedC, qs) + ); } } @@ -381,8 +383,7 @@ namespace Sample { /// Constant to add to |𝑦⟩ /// ## y /// Quantum register of target - internal operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[]) - : Unit is Adj + Ctl { + internal operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[]) : Unit is Adj + Ctl { body (...) { Controlled ModularAddConstant([], (modulus, c, y)); } diff --git a/samples/algorithms/SuperdenseCoding.qs b/samples/algorithms/SuperdenseCoding.qs index a9e87839cc..bcafeccb02 100644 --- a/samples/algorithms/SuperdenseCoding.qs +++ b/samples/algorithms/SuperdenseCoding.qs @@ -37,7 +37,8 @@ namespace Sample { operation CreateEntangledPair(q1 : Qubit, q2 : Qubit) : Unit { Fact( CheckAllZero([q1, q2]), - "Qubits are expected to be in the |00〉 state"); + "Qubits are expected to be in the |00〉 state" + ); H(q1); CNOT(q1, q2); diff --git a/samples/algorithms/Superposition.qs b/samples/algorithms/Superposition.qs index 5ed19e77b4..c00bb69255 100644 --- a/samples/algorithms/Superposition.qs +++ b/samples/algorithms/Superposition.qs @@ -15,7 +15,7 @@ namespace Sample { // Set the qubit in superposition by applying a Hadamard transformation. H(qubit); - // Measure the qubit. There is a 50% probability of measuring either + // Measure the qubit. There is a 50% probability of measuring either // `Zero` or `One`. let result = M(qubit); diff --git a/samples/algorithms/Teleportation.qs b/samples/algorithms/Teleportation.qs index 21c2e8e398..924c493ac0 100644 --- a/samples/algorithms/Teleportation.qs +++ b/samples/algorithms/Teleportation.qs @@ -15,7 +15,7 @@ namespace Sample { open Microsoft.Quantum.Measurement; @EntryPoint() - operation Main () : Result[] { + operation Main() : Result[] { // Allocate the message and target qubits. use (message, target) = (Qubit(), Qubit()); diff --git a/samples/estimation/Dynamics.qs b/samples/estimation/Dynamics.qs index 95d9832159..41558cb94c 100644 --- a/samples/estimation/Dynamics.qs +++ b/samples/estimation/Dynamics.qs @@ -50,39 +50,36 @@ namespace QuantumDynamics { let len1 = 3; let len2 = 3; - let valLength = 2*len1+len2+1; - mutable values = [0.0, size=valLength]; + let valLength = 2 * len1 + len2 + 1; + mutable values = [0.0, size = valLength]; - let val1 = J*p*dt; - let val2 = -g*p*dt; - let val3 = J*(1.0 - 3.0*p)*dt/2.0; - let val4 = g*(1.0 - 4.0*p)*dt/2.0; + let val1 = J * p * dt; + let val2 = -g * p * dt; + let val3 = J * (1.0 - 3.0 * p) * dt / 2.0; + let val4 = g * (1.0 - 4.0 * p) * dt / 2.0; for i in 0..len1 { if (i % 2 == 0) { set values w/= i <- val1; - } - else { + } else { set values w/= i <- val2; } } - for i in len1+1..len1+len2 { + for i in len1 + 1..len1 + len2 { if (i % 2 == 0) { set values w/= i <- val3; - } - else { + } else { set values w/= i <- val4; } } - for i in len1+len2+1..valLength-1 { + for i in len1 + len2 + 1..valLength-1 { if (i % 2 == 0) { set values w/= i <- val1; - } - else { + } else { set values w/= i <- val2; } } @@ -126,10 +123,11 @@ namespace QuantumDynamics { let r_end = dir ? m-2 | m-1; for row in 0..r_end { - for col in start..2..c_end { // Iterate through even or odd columns based on `grp` + for col in start..2..c_end { + // Iterate through even or odd columns based on `grp` - let row2 = dir ? row+1 | row; - let col2 = dir ? col | col+1; + let row2 = dir ? row + 1 | row; + let col2 = dir ? col | col + 1; Exp(P_op, theta, [qArr[row][col], qArr[row2][col2]]); } @@ -151,10 +149,10 @@ namespace QuantumDynamics { /// operation IsingModel2DSim(N1 : Int, N2 : Int, J : Double, g : Double, totTime : Double, dt : Double) : Unit { - use qs = Qubit[N1*N2]; + use qs = Qubit[N1 * N2]; let qubitArray = Chunks(N2, qs); // qubits are re-arranged to be in an N1 x N2 array - let p = 1.0 / (4.0 - 4.0^(1.0 / 3.0)); + let p = 1.0 / (4.0 - 4.0 ^ (1.0 / 3.0)); let t = Ceiling(totTime / dt); let seqLen = 10 * t + 1; @@ -162,7 +160,7 @@ namespace QuantumDynamics { let angSeq = SetAngleSequence(p, dt, J, g); for i in 0..seqLen - 1 { - let theta = (i==0 or i==seqLen-1) ? J*p*dt/2.0 | angSeq[i%10]; + let theta = (i == 0 or i == seqLen-1) ? J * p * dt / 2.0 | angSeq[i % 10]; // for even indexes if i % 2 == 0 { diff --git a/samples/estimation/EkeraHastadFactoring.qs b/samples/estimation/EkeraHastadFactoring.qs index 248c7529f8..1e39e66fca 100644 --- a/samples/estimation/EkeraHastadFactoring.qs +++ b/samples/estimation/EkeraHastadFactoring.qs @@ -184,11 +184,11 @@ namespace Microsoft.Quantum.Applications.Cryptography { } internal function LookupData(factor : BigInt, expLength : Int, mulLength : Int, base : BigInt, mod : BigInt, sign : Int, numBits : Int) : Bool[][] { - mutable data = [[false, size = numBits], size = 2^(expLength + mulLength)]; - for b in 0..2^mulLength - 1 { - for a in 0..2^expLength - 1 { - let idx = b * 2^expLength + a; - let value = ModulusL(factor * IntAsBigInt(b) * IntAsBigInt(sign) * (base^a), mod); + mutable data = [[false, size = numBits], size = 2 ^ (expLength + mulLength)]; + for b in 0..2 ^ mulLength - 1 { + for a in 0..2 ^ expLength - 1 { + let idx = b * 2 ^ expLength + a; + let value = ModulusL(factor * IntAsBigInt(b) * IntAsBigInt(sign) * (base ^ a), mod); set data w/= idx <- BigIntAsBoolArray(value, numBits); } } diff --git a/samples/estimation/Precalculated.qs b/samples/estimation/Precalculated.qs index 5e709fcc81..801e524ee7 100644 --- a/samples/estimation/Precalculated.qs +++ b/samples/estimation/Precalculated.qs @@ -17,9 +17,10 @@ namespace PrecalculatedEstimates { use qubits = Qubit[12581]; AccountForEstimates( - [TCount(12), RotationCount(12), RotationDepth(12), - CczCount(3731607428), MeasurementCount(1078154040)], - PSSPCLayout(), qubits); + [TCount(12), RotationCount(12), RotationDepth(12), CczCount(3731607428), MeasurementCount(1078154040)], + PSSPCLayout(), + qubits + ); } } diff --git a/samples/estimation/ShorRE.qs b/samples/estimation/ShorRE.qs index 4f3939ca69..f243a484f5 100644 --- a/samples/estimation/ShorRE.qs +++ b/samples/estimation/ShorRE.qs @@ -23,7 +23,7 @@ namespace Shors { // When chooseing parameters for `EstimateFrequency`, make sure that // generator and modules are not co-prime - let _ = EstimateFrequency(11, 2^bitsize - 1, bitsize); + let _ = EstimateFrequency(11, 2 ^ bitsize - 1, bitsize); } /// # Summary @@ -47,10 +47,9 @@ namespace Shors { generator : Int, modulus : Int, bitsize : Int - ) - : Int { + ) : Int { mutable frequencyEstimate = 0; - let bitsPrecision = 2 * bitsize + 1; + let bitsPrecision = 2 * bitsize + 1; // Allocate qubits for the superposition of eigenstates of // the oracle that is used in period finding. @@ -112,10 +111,11 @@ namespace Shors { /// given power of the generator. The multiplication is performed modulo /// `modulus`. internal operation ApplyOrderFindingOracle( - generator : Int, modulus : Int, power : Int, target : Qubit[] - ) - : Unit - is Adj + Ctl { + generator : Int, + modulus : Int, + power : Int, + target : Qubit[] + ) : Unit is Adj + Ctl { // The oracle we use for order finding implements |x⟩ ↦ |x⋅a mod N⟩. We // also use `ExpModI` to compute a by which x must be multiplied. Also // note that we interpret target as unsigned integer in little-endian @@ -123,7 +123,8 @@ namespace Shors { ModularMultiplyByConstant( modulus, ExpModI(generator, power, modulus), - target); + target + ); } /// # Summary @@ -141,14 +142,14 @@ namespace Shors { /// Constant by which to multiply |𝑦⟩ /// ## y /// Quantum register of target - internal operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[]) - : Unit is Adj + Ctl { + internal operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[]) : Unit is Adj + Ctl { use qs = Qubit[Length(y)]; for idx in IndexRange(y) { let shiftedC = (c <<< idx) % modulus; Controlled ModularAddConstant( [y[idx]], - (modulus, shiftedC, qs)); + (modulus, shiftedC, qs) + ); } for idx in IndexRange(y) { SWAP(y[idx], qs[idx]); @@ -158,7 +159,8 @@ namespace Shors { let shiftedC = (invC <<< idx) % modulus; Controlled ModularAddConstant( [y[idx]], - (modulus, modulus - shiftedC, qs)); + (modulus, modulus - shiftedC, qs) + ); } } @@ -177,8 +179,7 @@ namespace Shors { /// Constant to add to |𝑦⟩ /// ## y /// Quantum register of target - internal operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[]) - : Unit is Adj + Ctl { + internal operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[]) : Unit is Adj + Ctl { body (...) { Controlled ModularAddConstant([], (modulus, c, y)); } diff --git a/samples/estimation/df-chemistry/src/df_chemistry.qs b/samples/estimation/df-chemistry/src/df_chemistry.qs index 25e2e31220..50a54930c0 100644 --- a/samples/estimation/df-chemistry/src/df_chemistry.qs +++ b/samples/estimation/df-chemistry/src/df_chemistry.qs @@ -21,27 +21,27 @@ namespace Microsoft.Quantum.Applications.Chemistry { /// arXiv:2007.14460, p. 9, eq. 9 newtype DoubleFactorizedChemistryProblem = ( // Number of orbitals (N, p. 8) - NumOrbitals: Int, + NumOrbitals : Int, // one-body norm (ǁL⁽⁻¹⁾ǁ, p. 8, eq. 16) - OneBodyNorm: Double, + OneBodyNorm : Double, // one-body norm (¼∑ǁL⁽ʳ⁾ǁ², p. 8, eq. 16) - TwoBodyNorm: Double, + TwoBodyNorm : Double, // eigenvalues in the EVD of the one-electron Hamiltonian (λₖ, p. 54, eq. 67) - OneBodyEigenValues: Double[], + OneBodyEigenValues : Double[], // eigenvectors in the EVD of the one-electron Hamiltonian (Rₖ, p. 54, eq. 67) - OneBodyEigenVectors: Double[][], + OneBodyEigenVectors : Double[][], // norms inside Λ_SH (p. 56, eq. 77) - Lambdas: Double[], + Lambdas : Double[], // eigenvalues in the EVDs of the two-electron Hamiltonian for all r (λₖ⁽ʳ⁾, p. 56, eq. 77) - TwoBodyEigenValues: Double[][], + TwoBodyEigenValues : Double[][], // eigenvectors in the EVDs of the two-electron Hamiltonian for all r (R⁽ʳ⁾ₖ, p. 56, eq. 77) - TwoBodyEigenVectors: Double[][][], + TwoBodyEigenVectors : Double[][][], ); newtype DoubleFactorizedChemistryParameters = ( // Standard deviation (ΔE, p. 8, eq. 1) // Typically set to 0.001 - StandardDeviation: Double, + StandardDeviation : Double, ); /// # Summary @@ -50,7 +50,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { /// gradient technique (p. 55) operation DoubleFactorizedChemistry( problem : DoubleFactorizedChemistryProblem, - parameters: DoubleFactorizedChemistryParameters + parameters : DoubleFactorizedChemistryParameters ) : Unit { let constants = ComputeConstants(problem, parameters); @@ -86,25 +86,23 @@ namespace Microsoft.Quantum.Applications.Chemistry { /// electron operators, which are computed from the double factorized /// problem and parameters. internal newtype DoubleFactorizedChemistryConstants = ( - RotationAngleBitPrecision: Int, - StatePreparationBitPrecision: Int, - TargetError: Double + RotationAngleBitPrecision : Int, + StatePreparationBitPrecision : Int, + TargetError : Double ); internal function ComputeConstants( problem : DoubleFactorizedChemistryProblem, - parameters : DoubleFactorizedChemistryParameters) - : DoubleFactorizedChemistryConstants { + parameters : DoubleFactorizedChemistryParameters + ) : DoubleFactorizedChemistryConstants { let pj = 0.1; let barEpsilon = Sqrt(pj); let norm = problem::OneBodyNorm + problem::TwoBodyNorm; let epsilon = 0.1 * parameters::StandardDeviation / norm; - let RotationAngleBitPrecision = Ceiling(1.152 - + Lg(Sqrt((IntAsDouble((problem::NumOrbitals - 1) * 8) * PI() * norm) / parameters::StandardDeviation)) - + 0.5 * Lg(1.0 / barEpsilon)); + let RotationAngleBitPrecision = Ceiling(1.152 + Lg(Sqrt((IntAsDouble((problem::NumOrbitals - 1) * 8) * PI() * norm) / parameters::StandardDeviation)) + 0.5 * Lg(1.0 / barEpsilon)); let StatePreparationBitPrecision = Ceiling(Lg(1.0 / epsilon) + 2.5); - let TargetError = 2.0^IntAsDouble(1 - StatePreparationBitPrecision); + let TargetError = 2.0 ^ IntAsDouble(1 - StatePreparationBitPrecision); DoubleFactorizedChemistryConstants( RotationAngleBitPrecision, @@ -114,8 +112,8 @@ namespace Microsoft.Quantum.Applications.Chemistry { } internal newtype WalkStep = ( - NGarbageQubits: Int, - StepOp: (Qubit[], Qubit[], Qubit[], Qubit[]) => Unit + NGarbageQubits : Int, + StepOp : (Qubit[], Qubit[], Qubit[], Qubit[]) => Unit ); /// # Summary @@ -161,8 +159,8 @@ namespace Microsoft.Quantum.Applications.Chemistry { } internal newtype OneElectronOperator = ( - NGarbageQubits: Int, - Apply: (Qubit[], Qubit[], Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl + NGarbageQubits : Int, + Apply : (Qubit[], Qubit[], Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl ); /// # Summary @@ -235,8 +233,8 @@ namespace Microsoft.Quantum.Applications.Chemistry { } internal newtype TwoElectronOperator = ( - NGarbageQubits: Int, - Apply: (Qubit[], Qubit[], Qubit[], Qubit[]) => Unit is Ctl + NGarbageQubits : Int, + Apply : (Qubit[], Qubit[], Qubit[], Qubit[]) => Unit is Ctl ); /// # Summary @@ -330,7 +328,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { mutable bitstrings = []; let tau = 2.0 * PI(); - let preFactor = 2.0^IntAsDouble(precision); + let preFactor = 2.0 ^ IntAsDouble(precision); for eigenVector in eigenVectors { // Computes rotation angles for Majorana operator ($\vec u$ in p. 52, eq. 55) @@ -341,7 +339,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { // We apply MinD, such that rounding errors do not lead to // an argument for ArcCos which is larger than 1.0. (p. 52, eq. 56) let theta = sins == 0.0 ? 0.0 | 0.5 * ArcCos(MinD(eigenVector[index] / sins, 1.0)); - + // all angles as bit string let factor = theta / tau; set result += Reversed(IntAsBoolArray(IsNaN(factor) ? 0 | Floor(preFactor * factor), precision)); diff --git a/samples/estimation/df-chemistry/src/prepare.qs b/samples/estimation/df-chemistry/src/prepare.qs index f06edf9fd6..8349d745fb 100644 --- a/samples/estimation/df-chemistry/src/prepare.qs +++ b/samples/estimation/df-chemistry/src/prepare.qs @@ -22,7 +22,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { operation PrepareUniformSuperposition(numStates : Int, qs : Qubit[]) : Unit is Adj + Ctl { Fact(numStates >= 1, "numStates must be positive"); - Fact(numStates <= 2^Length(qs), $"numStates must be smaller or equal to {2^Length(qs)}"); + Fact(numStates <= 2 ^ Length(qs), $"numStates must be smaller or equal to {2 ^ Length(qs)}"); let qsAdjusted = qs[...Ceiling(Lg(IntAsDouble(numStates))) - 1]; @@ -52,14 +52,13 @@ namespace Microsoft.Quantum.Applications.Chemistry { } newtype PrepareArbitrarySuperposition = ( - NIndexQubits: Int, - NGarbageQubits: Int, - Prepare: (Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl, - PrepareWithSelect: ((Bool[][], Qubit[], Qubit[]) => Unit is Adj + Ctl, Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl + NIndexQubits : Int, + NGarbageQubits : Int, + Prepare : (Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl, + PrepareWithSelect : ((Bool[][], Qubit[], Qubit[]) => Unit is Adj + Ctl, Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl ); - function MakePrepareArbitrarySuperposition(targetError : Double, coefficients : Double[]) - : PrepareArbitrarySuperposition { + function MakePrepareArbitrarySuperposition(targetError : Double, coefficients : Double[]) : PrepareArbitrarySuperposition { let nBitsPrecision = -Ceiling(Lg(0.5 * targetError)) + 1; let positiveCoefficients = Mapped(AbsD, coefficients); let (keepCoeff, altIndex) = DiscretizedProbabilityDistribution(nBitsPrecision, positiveCoefficients); @@ -72,7 +71,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { return PrepareArbitrarySuperposition(nIndexQubits, nGarbageQubits, op, opWithSelect); } - function MakePrepareArbitrarySuperpositionWithData(targetError : Double, coefficients : Double[], data: Bool[][]) : PrepareArbitrarySuperposition { + function MakePrepareArbitrarySuperpositionWithData(targetError : Double, coefficients : Double[], data : Bool[][]) : PrepareArbitrarySuperposition { let nBitsPrecision = -Ceiling(Lg(0.5 * targetError)) + 1; let positiveCoefficients = Mapped(AbsD, coefficients); let (keepCoeff, altIndex) = DiscretizedProbabilityDistribution(nBitsPrecision, positiveCoefficients); @@ -101,12 +100,11 @@ namespace Microsoft.Quantum.Applications.Chemistry { (factor, pow) } - internal function ArbitrarySuperpositionRegisterLengths(targetError : Double, nCoefficients : Int) - : (Int, Int) { + internal function ArbitrarySuperpositionRegisterLengths(targetError : Double, nCoefficients : Int) : (Int, Int) { Fact(targetError > 0.0, "targetError must be positive"); Fact(nCoefficients > 0, "nCoefficients must be positive"); - let nBitsPrecision = -Ceiling(Lg(0.5*targetError)) + 1; + let nBitsPrecision = -Ceiling(Lg(0.5 * targetError)) + 1; let nIndexQubits = Ceiling(Lg(IntAsDouble(nCoefficients))); let nGarbageQubits = nIndexQubits + 2 * nBitsPrecision + 1; (nIndexQubits, nGarbageQubits) @@ -114,8 +112,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { // Computes discretized probability distribution as described in Section 3 // and Fig. 13 in [arXiv:1805.03662](https://arxiv.org/pdf/1805.03662.pdf) - internal function DiscretizedProbabilityDistribution(bitsPrecision: Int, coefficients: Double[]) - : (Int[], Int[]) { + internal function DiscretizedProbabilityDistribution(bitsPrecision : Int, coefficients : Double[]) : (Int[], Int[]) { let oneNorm = PNorm(1.0, coefficients); let nCoefficients = Length(coefficients); Fact(bitsPrecision <= 31, $"Bits of precision {bitsPrecision} unsupported. Max is 31."); @@ -135,7 +132,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { // Uniformly distribute excess bars across coefficients. for idx in 0..AbsI(bars) - 1 { - set keepCoeff w/= idx <- keepCoeff[idx] + (bars > 0 ? -1 | +1); + set keepCoeff w/= idx <- keepCoeff[idx] + (bars > 0 ? -1 | + 1); } mutable barSink = []; @@ -178,12 +175,17 @@ namespace Microsoft.Quantum.Applications.Chemistry { // Used in QuantumROM implementation. internal operation PrepareQuantumROMState( - nBitsPrecision: Int, nCoeffs: Int, nBitsIndices: Int, - keepCoeff: Int[], altIndex: Int[], data : Bool[][], - selectOperation: (Bool[][], Qubit[], Qubit[]) => Unit is Adj + Ctl, - indexRegister: Qubit[], dataQubits : Qubit[], garbageRegister: Qubit[] - ) - : Unit is Adj + Ctl { + nBitsPrecision : Int, + nCoeffs : Int, + nBitsIndices : Int, + keepCoeff : Int[], + altIndex : Int[], + data : Bool[][], + selectOperation : (Bool[][], Qubit[], Qubit[]) => Unit is Adj + Ctl, + indexRegister : Qubit[], + dataQubits : Qubit[], + garbageRegister : Qubit[] + ) : Unit is Adj + Ctl { let garbageIdx0 = nBitsIndices; let garbageIdx1 = garbageIdx0 + nBitsPrecision; let garbageIdx2 = garbageIdx1 + nBitsPrecision; @@ -202,10 +204,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { // Write bitstrings to altIndex and keepCoeff register. let target = keepCoeffRegister + altIndexRegister + dataRegister + altDataRegister; - let selectData = MappedOverRange(idx -> - IntAsBoolArray(keepCoeff[idx], Length(keepCoeffRegister)) + - IntAsBoolArray(altIndex[idx], Length(altIndexRegister)) + - (IsEmpty(data) ? [] | data[idx] + data[altIndex[idx]]), 0..nCoeffs - 1); + let selectData = MappedOverRange(idx -> IntAsBoolArray(keepCoeff[idx], Length(keepCoeffRegister)) + IntAsBoolArray(altIndex[idx], Length(altIndexRegister)) + (IsEmpty(data) ? [] | data[idx] + data[altIndex[idx]]), 0..nCoeffs - 1); selectOperation(selectData, indexRegister, target); // Perform comparison diff --git a/samples/language/Comments.qs b/samples/language/Comments.qs index 8ad7505fca..e8fe1d47d1 100644 --- a/samples/language/Comments.qs +++ b/samples/language/Comments.qs @@ -3,13 +3,13 @@ /// /// # Description /// Comments begin with two forward slashes (`//`) and continue until the -/// end of line. Comments may appear anywhere in the source code. +/// end of line. Comments may appear anywhere in the source code. /// Q# does not currently support block comments. /// Documentation comments, or doc comments, are denoted with three /// forward slashes (`///`) instead of two. namespace MyQuantumApp { open Microsoft.Quantum.Diagnostics; - + /// This is a doc-comment for the `Main` operation. @EntryPoint() operation Main() : Result[] { diff --git a/samples/language/ConditionalBranching.qs b/samples/language/ConditionalBranching.qs index dd63bb8f6e..2a4e030817 100644 --- a/samples/language/ConditionalBranching.qs +++ b/samples/language/ConditionalBranching.qs @@ -36,6 +36,6 @@ namespace MyQuantumApp { let fahrenheit = 40; // `if` can also be used as an expression, to conditionally return a value. - let absoluteValue = if fahrenheit > 0 { fahrenheit } else { fahrenheit * -1 }; + let absoluteValue = if fahrenheit > 0 { fahrenheit } else { fahrenheit * -1 }; } } \ No newline at end of file diff --git a/samples/language/EntryPoint.qs b/samples/language/EntryPoint.qs index 6aed799f25..4be7b7900f 100644 --- a/samples/language/EntryPoint.qs +++ b/samples/language/EntryPoint.qs @@ -3,7 +3,7 @@ /// /// # Description /// The `@EntryPoint()` attribute is used to designate a particular operation as -/// the entry point of a Q# program rather than requiring entry points to have +/// the entry point of a Q# program rather than requiring entry points to have // a particular name such as `main`, `Main`, or `__main__`. namespace MyQuantumApp { diff --git a/samples/language/ForLoops.qs b/samples/language/ForLoops.qs index 98c679ec3a..4c40d886d6 100644 --- a/samples/language/ForLoops.qs +++ b/samples/language/ForLoops.qs @@ -10,13 +10,13 @@ namespace MyQuantumApp { @EntryPoint() operation Main() : Unit { // For loop over `Range` - for i in 0..5 { } + for i in 0..5 {} // For loop over `Array` - for element in [10, 11, 12] { } + for element in [10, 11, 12] {} // For loop over array slice let array = [1.0, 2.0, 3.0, 4.0]; - for element in array[2...] { } + for element in array[2...] {} } } diff --git a/samples/language/LambdaExpression.qs b/samples/language/LambdaExpression.qs index a873e2d13b..26e9c64672 100644 --- a/samples/language/LambdaExpression.qs +++ b/samples/language/LambdaExpression.qs @@ -30,6 +30,6 @@ namespace MyQuantumApp { // `Map` takes a callable and applies it to all elements in // an array let incremented = Mapped(x -> x + 1, intArray); - + } } \ No newline at end of file diff --git a/samples/language/MultiFileProject/src/Main.qs b/samples/language/MultiFileProject/src/Main.qs index 0f30c50484..eaf598229c 100644 --- a/samples/language/MultiFileProject/src/Main.qs +++ b/samples/language/MultiFileProject/src/Main.qs @@ -2,18 +2,18 @@ /// Multi File Project /// /// # Description -/// Organizing code into multiple Q# source files is an important part of +/// Organizing code into multiple Q# source files is an important part of /// writing readable and maintainable code. In this project, we have `Main.qs`, /// and `Particle.qs`, which defines a new namespace for particle operations. /// The presence of a Q# manifest file (`qsharp.json`) tells the compiler /// to include all Q# files under `src/`. namespace MyQuantumApp { - open Particle; - @EntryPoint() - operation Main() : Unit { - let particleA = Particle(0, 0, 0); - let particleB = Particle(1, 1, 1); + open Particle; + @EntryPoint() + operation Main() : Unit { + let particleA = Particle(0, 0, 0); + let particleB = Particle(1, 1, 1); - let particleC = addParticles(particleA, particleB); - } + let particleC = addParticles(particleA, particleB); + } } diff --git a/samples/language/MultiFileProject/src/Particle.qs b/samples/language/MultiFileProject/src/Particle.qs index bbe73ef961..8f6947174b 100644 --- a/samples/language/MultiFileProject/src/Particle.qs +++ b/samples/language/MultiFileProject/src/Particle.qs @@ -1,9 +1,9 @@ namespace Particle { - newtype Particle = (x: Int, y: Int, z: Int); + newtype Particle = (x : Int, y : Int, z : Int); - function addParticles(a: Particle, b: Particle) : Particle { - let (x1, y1, z1) = a!; - let (x2, y2, z2) = b!; - return Particle(x1 + x2, y1 + y2, z1 + z2); - } + function addParticles(a : Particle, b : Particle) : Particle { + let (x1, y1, z1) = a!; + let (x2, y2, z2) = b!; + return Particle(x1 + x2, y1 + y2, z1 + z2); + } } diff --git a/samples/language/Namespaces.qs b/samples/language/Namespaces.qs index d80dcd66df..bdf0579d4c 100644 --- a/samples/language/Namespaces.qs +++ b/samples/language/Namespaces.qs @@ -10,7 +10,7 @@ namespace MyQuantumApp { // The following `open` directive is used to import all types and callables declared in the // Microsoft.Quantum.Diagnostics namespace. open Microsoft.Quantum.Diagnostics; - + @EntryPoint() operation Main() : Result[] { // `DumpMachine` is in the Microsoft.Quantum.Diagnostics namespace diff --git a/samples/language/Operations.qs b/samples/language/Operations.qs index 29840f8f9f..3a8b423e2a 100644 --- a/samples/language/Operations.qs +++ b/samples/language/Operations.qs @@ -1,19 +1,19 @@ /// # Sample -/// Operations +/// Operations /// /// # Description /// Operations are the basic building blocks of a Q# program. A Q# /// operation is a quantum subroutine. That is, it's a callable routine /// that contains quantum operations that modify the state of qubits. namespace MyQuantumApp { - + @EntryPoint() operation MeasureOneQubit() : Result { - // Allocate a qubit, by default it is in zero state - use q = Qubit(); + // Allocate a qubit, by default it is in zero state + use q = Qubit(); // We apply a Hadamard operation H to the state - // It now has a 50% chance of being measured 0 or 1 - H(q); + // It now has a 50% chance of being measured 0 or 1 + H(q); // Now we measure the qubit in Z-basis using the `M` operation. let result = M(q); // We reset the qubit before releasing it using the `Reset` operation. diff --git a/samples/language/Pauli.qs b/samples/language/Pauli.qs index 60a1c09d99..a7ee59fe12 100644 --- a/samples/language/Pauli.qs +++ b/samples/language/Pauli.qs @@ -8,10 +8,10 @@ namespace MyQuantumApp { @EntryPoint() operation Main() : Result { use q = Qubit(); - + // A `Pauli` can be declared as a literal. let pauliDimension = PauliX; - + // Measuring along a dimension returns a `Result`: let result = Measure([pauliDimension], [q]); diff --git a/samples/language/QuantumMemory.qs b/samples/language/QuantumMemory.qs index 044b273160..163d907ebc 100644 --- a/samples/language/QuantumMemory.qs +++ b/samples/language/QuantumMemory.qs @@ -4,7 +4,7 @@ /// # Description /// The primary quantum feature of Q# is its representation of qubits and qubit /// memory. Q# supports allocation of qubits, and differentiates between allocating -/// "clean" qubits and "dirty" qubits with the `use` and `borrow` keywords. +/// "clean" qubits and "dirty" qubits with the `use` and `borrow` keywords. /// Clean qubits are unentangled, whereas dirty qubits are in an unknown state /// and can potentially be entangled. namespace MyQuantumApp { diff --git a/samples/language/Qubit.qs b/samples/language/Qubit.qs index 854ac60349..db3afcb2ce 100644 --- a/samples/language/Qubit.qs +++ b/samples/language/Qubit.qs @@ -2,13 +2,13 @@ /// Qubit /// /// # Description -/// Q# uses the `Qubit` primitive type to represent quantum state. A qubit represents +/// Q# uses the `Qubit` primitive type to represent quantum state. A qubit represents /// the smallest addressable physical unit in a quantum computer. Qubits are long-lived, /// and accumulates transformations to quantum states. A Q# program has no ability to /// introspect into the state of a qubit, and thus is entirely agnostic about what a /// quantum state is or on how it is realized. Rather, a program can call operations /// such as Measure to learn information about the quantum state of the computation. -namespace MyQuantumApp { +namespace MyQuantumApp { open Microsoft.Quantum.Diagnostics; /// In the below code, all varibles have type annotations to showcase their type. @EntryPoint() diff --git a/samples/language/Range.qs b/samples/language/Range.qs index edf568f9bb..086b1d646a 100644 --- a/samples/language/Range.qs +++ b/samples/language/Range.qs @@ -38,7 +38,7 @@ namespace MyQuantumApp { // The array [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. mutable array = []; for i in 0..10 { - set array += [i^2]; + set array += [i ^ 2]; } // Ranges can be used to create array slices. diff --git a/samples/language/Result.qs b/samples/language/Result.qs index 97435f8637..bc31df74cb 100644 --- a/samples/language/Result.qs +++ b/samples/language/Result.qs @@ -22,7 +22,7 @@ namespace MyQuantumApp { // Measure the qubit. let measurement = M(q); - + // Reset the qubit. Reset(q); diff --git a/samples/language/ReturnStatement.qs b/samples/language/ReturnStatement.qs index 07505706d5..1ae6d924c3 100644 --- a/samples/language/ReturnStatement.qs +++ b/samples/language/ReturnStatement.qs @@ -3,7 +3,7 @@ /// /// # Description /// Return statements are a form of control flow statement that abort the current callable and -/// return control flow to the callee's scope with a given value. +/// return control flow to the callee's scope with a given value. namespace MyQuantumApp { @EntryPoint() operation Main() : Unit { diff --git a/samples/language/Specializations.qs b/samples/language/Specializations.qs index 6fd2016cc8..5d6b9a91a2 100644 --- a/samples/language/Specializations.qs +++ b/samples/language/Specializations.qs @@ -5,7 +5,7 @@ /// Q# allows specialized implementations. Operations in Q# can implicitly /// or explicitly define adjoint and/or controlled versions. /// Q# employs symbolic computation that can automatically generate the -/// corresponding adjoint and controlled implementations for a particular +/// corresponding adjoint and controlled implementations for a particular /// body implementation. namespace MyQuantumApp { @@ -13,19 +13,17 @@ namespace MyQuantumApp { /// generated for the `DoNothing` operation that declares supports for these /// specializations using the `is` keyword followed by the union of the supported /// specializations (`Adj + Ctl`). - operation DoNothing() : Unit - is Adj + Ctl { } + operation DoNothing() : Unit is Adj + Ctl {} - /// Here, the specializations hvae been explicitly defined. + /// Here, the specializations hvae been explicitly defined. /// In the following example, the declaration for an operation SWAP, /// which exchanges the state of two qubits q1 and q2, declares an /// explicit specialization for its adjoint version and its controlled /// version. While the implementations for Adjoint SWAP and Controlled - /// SWAP are thus user-defined, the compiler still needs to generate + /// SWAP are thus user-defined, the compiler still needs to generate /// the implementation for the combination of both functors (Controlled /// Adjoint SWAP, which is the same as Adjoint Controlled SWAP). - operation SWAP (q1 : Qubit, q2 : Qubit) : Unit - is Adj + Ctl { + operation SWAP(q1 : Qubit, q2 : Qubit) : Unit is Adj + Ctl { body (...) { CNOT(q1, q2); @@ -33,22 +31,22 @@ namespace MyQuantumApp { CNOT(q1, q2); } - adjoint (...) { + adjoint (...) { SWAP(q1, q2); } - controlled (cs, ...) { + controlled (cs, ...) { CNOT(q1, q2); Controlled CNOT(cs, (q2, q1)); - CNOT(q1, q2); - } + CNOT(q1, q2); + } } - /// The main function cannot be Adj or Ctl. + /// The main function cannot be Adj or Ctl. @EntryPoint() operation Main() : Unit { - // We invoke specializations using functors at the call site. + // We invoke specializations using functors at the call site. // In order to call these operations and their specializations, we need // to allocate some qubits. use (q1, q2) = (Qubit(), Qubit()); @@ -60,12 +58,12 @@ namespace MyQuantumApp { // We use the functor `Adjoint` on the operation `SWAP` to invoke the // adjoint specialization of `SWAP`. Adjoint SWAP(q1, q2); - + // Now,we will use the `Controlled` functor. To use this functor, we - // need some control qubits. + // need some control qubits. // The `Controlled` functor invokes the control specialization of the - // operation. Note that the control specialization has a different + // operation. Note that the control specialization has a different // signature than the regular operation: first, the control qubits; // second, the parameters for the regular operation. // For a singly controlled invocation, only pass one control qubit diff --git a/samples/language/Unit.qs b/samples/language/Unit.qs index 3a144aebfa..80b2b22a8b 100644 --- a/samples/language/Unit.qs +++ b/samples/language/Unit.qs @@ -4,7 +4,7 @@ /// # Description /// The `Unit` type is the singleton type whose only value is (). /// Functions implicitly return `Unit` if no explicit or implicit -/// return is specified. +/// return is specified. namespace MyQuantumApp { @EntryPoint() From e31fe375c1ac035275593dce93734752a748a481 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Sun, 24 Mar 2024 15:48:20 -0700 Subject: [PATCH 05/13] Unary plus minus support --- compiler/qsc_formatter/src/formatter.rs | 79 ++++++++++++++++++++----- 1 file changed, 63 insertions(+), 16 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index 32d8c962b8..9112e1deac 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -6,7 +6,7 @@ use qsc_frontend::{ keyword::Keyword, lex::{ concrete::{self, ConcreteToken, ConcreteTokenKind}, - cooked::{StringToken, TokenKind}, + cooked::{ClosedBinOp, StringToken, TokenKind}, Delim, InterpolatedEnding, InterpolatedStart, }, }; @@ -44,6 +44,7 @@ pub fn calculate_format_edits(code: &str) -> Vec { delim_newlines_stack: vec![], type_param_state: TypeParameterListState::NoState, spec_decl_state: SpecDeclState::NoState, + binary_plus_minus_state: BinaryPlusMinusState::NoState, }; // The sliding window used is over three adjacent tokens @@ -159,6 +160,12 @@ enum SpecDeclState { OnEllipse, } +enum BinaryPlusMinusState { + NoState, + LastTokenIsValue, + LeftIsBinaryPlusMinus, +} + /// Enum for a token's status as a delimiter. /// `<` and `>` are delimiters only with type-parameter lists, /// which is determined using the TypeParameterListState enum. @@ -202,6 +209,7 @@ struct Formatter<'a> { delim_newlines_stack: Vec, type_param_state: TypeParameterListState, spec_decl_state: SpecDeclState, + binary_plus_minus_state: BinaryPlusMinusState, } impl<'a> Formatter<'a> { @@ -227,6 +235,30 @@ impl<'a> Formatter<'a> { let (left_delim_state, right_delim_state) = self.update_type_param_state(&left.kind, &right.kind); + // Update binary_plus_minus_state + if let Syntax(cooked_left) = &left.kind { + if is_value_token_left(cooked_left, left_delim_state) { + self.binary_plus_minus_state = BinaryPlusMinusState::LastTokenIsValue; + } else if matches!( + cooked_left, + ClosedBinOp(ClosedBinOp::Plus | ClosedBinOp::Minus) + ) && matches!( + self.binary_plus_minus_state, + BinaryPlusMinusState::LastTokenIsValue + ) { + self.binary_plus_minus_state = BinaryPlusMinusState::LeftIsBinaryPlusMinus; + } else { + // Note that Comment tokens will skip this and won't + // update the state because they are not Syntax tokens. + self.binary_plus_minus_state = BinaryPlusMinusState::NoState; + } + } + + let is_left_binary_plus_minus = matches!( + self.binary_plus_minus_state, + BinaryPlusMinusState::LeftIsBinaryPlusMinus + ); + let newline_context = self.update_indent_level( left_delim_state, right_delim_state, @@ -257,12 +289,12 @@ impl<'a> Formatter<'a> { // else do nothing, preserving the user's spaces before the comment } (Syntax(cooked_left), Syntax(cooked_right)) => match (cooked_left, cooked_right) { - (ClosedBinOp(ClosedBinOp::Minus), _) | (_, ClosedBinOp(ClosedBinOp::Minus)) => { - // This case is used to ignore the spacing around a `-`. - // This is done because we currently don't have the architecture - // to be able to differentiate between the unary `-` and the binary `-` - // which would have different spacing rules. - } + // (ClosedBinOp(ClosedBinOp::Minus), _) | (_, ClosedBinOp(ClosedBinOp::Minus)) => { + // // This case is used to ignore the spacing around a `-`. + // // This is done because we currently don't have the architecture + // // to be able to differentiate between the unary `-` and the binary `-` + // // which would have different spacing rules. + // } (Semi, _) if matches!(newline_context, NewlineContext::Spaces) => { effect_single_space(left, whitespace, right, &mut edits); } @@ -397,7 +429,7 @@ impl<'a> Formatter<'a> { } (_, Open(Delim::Brace)) => { // Special-case braces to have a leading single space with values - if is_prefix(cooked_left) { + if is_prefix(cooked_left, is_left_binary_plus_minus) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -405,7 +437,8 @@ impl<'a> Formatter<'a> { } (_, _) if matches!(right_delim_state, Delimiter::Open) => { // Otherwise, all open delims have the same logic - if is_value_token_left(cooked_left, left_delim_state) || is_prefix(cooked_left) + if is_value_token_left(cooked_left, left_delim_state) + || is_prefix(cooked_left, is_left_binary_plus_minus) { // i.e. foo() or foo[3] effect_no_space(left, whitespace, right, &mut edits); @@ -428,7 +461,7 @@ impl<'a> Formatter<'a> { effect_single_space(left, whitespace, right, &mut edits); } (_, _) if is_value_token_right(cooked_right, right_delim_state) => { - if is_prefix(cooked_left) { + if is_prefix(cooked_left, is_left_binary_plus_minus) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -437,8 +470,16 @@ impl<'a> Formatter<'a> { (_, _) if is_suffix(cooked_right) => { effect_no_space(left, whitespace, right, &mut edits); } - (_, _) if is_prefix_with_space(cooked_right) => { - if is_prefix(cooked_left) { + (_, _) + if is_prefix_with_space( + cooked_right, + matches!( + self.binary_plus_minus_state, + BinaryPlusMinusState::LastTokenIsValue + ), + ) => + { + if is_prefix(cooked_left, is_left_binary_plus_minus) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -648,8 +689,14 @@ fn is_bin_op(cooked: &TokenKind) -> bool { ) } -fn is_prefix_with_space(cooked: &TokenKind) -> bool { - matches!(cooked, TokenKind::TildeTildeTilde) +fn is_prefix_with_space(cooked: &TokenKind, is_binary_plus_minus: bool) -> bool { + match &cooked { + TokenKind::ClosedBinOp(ClosedBinOp::Plus | ClosedBinOp::Minus) if !is_binary_plus_minus => { + true + } + TokenKind::TildeTildeTilde => true, + _ => false, + } } fn is_prefix_without_space(cooked: &TokenKind) -> bool { @@ -659,8 +706,8 @@ fn is_prefix_without_space(cooked: &TokenKind) -> bool { ) } -fn is_prefix(cooked: &TokenKind) -> bool { - is_prefix_with_space(cooked) +fn is_prefix(cooked: &TokenKind, is_binary_plus_minus: bool) -> bool { + is_prefix_with_space(cooked, is_binary_plus_minus) || is_prefix_without_space(cooked) || matches!(cooked, TokenKind::DotDotDot) } From 9e33d678ebcc788b758fa89bf93e8ac417e7be2b Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Sun, 24 Mar 2024 15:51:56 -0700 Subject: [PATCH 06/13] Revert "Unary plus minus support" This reverts commit e31fe375c1ac035275593dce93734752a748a481. --- compiler/qsc_formatter/src/formatter.rs | 79 +++++-------------------- 1 file changed, 16 insertions(+), 63 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index 9112e1deac..32d8c962b8 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -6,7 +6,7 @@ use qsc_frontend::{ keyword::Keyword, lex::{ concrete::{self, ConcreteToken, ConcreteTokenKind}, - cooked::{ClosedBinOp, StringToken, TokenKind}, + cooked::{StringToken, TokenKind}, Delim, InterpolatedEnding, InterpolatedStart, }, }; @@ -44,7 +44,6 @@ pub fn calculate_format_edits(code: &str) -> Vec { delim_newlines_stack: vec![], type_param_state: TypeParameterListState::NoState, spec_decl_state: SpecDeclState::NoState, - binary_plus_minus_state: BinaryPlusMinusState::NoState, }; // The sliding window used is over three adjacent tokens @@ -160,12 +159,6 @@ enum SpecDeclState { OnEllipse, } -enum BinaryPlusMinusState { - NoState, - LastTokenIsValue, - LeftIsBinaryPlusMinus, -} - /// Enum for a token's status as a delimiter. /// `<` and `>` are delimiters only with type-parameter lists, /// which is determined using the TypeParameterListState enum. @@ -209,7 +202,6 @@ struct Formatter<'a> { delim_newlines_stack: Vec, type_param_state: TypeParameterListState, spec_decl_state: SpecDeclState, - binary_plus_minus_state: BinaryPlusMinusState, } impl<'a> Formatter<'a> { @@ -235,30 +227,6 @@ impl<'a> Formatter<'a> { let (left_delim_state, right_delim_state) = self.update_type_param_state(&left.kind, &right.kind); - // Update binary_plus_minus_state - if let Syntax(cooked_left) = &left.kind { - if is_value_token_left(cooked_left, left_delim_state) { - self.binary_plus_minus_state = BinaryPlusMinusState::LastTokenIsValue; - } else if matches!( - cooked_left, - ClosedBinOp(ClosedBinOp::Plus | ClosedBinOp::Minus) - ) && matches!( - self.binary_plus_minus_state, - BinaryPlusMinusState::LastTokenIsValue - ) { - self.binary_plus_minus_state = BinaryPlusMinusState::LeftIsBinaryPlusMinus; - } else { - // Note that Comment tokens will skip this and won't - // update the state because they are not Syntax tokens. - self.binary_plus_minus_state = BinaryPlusMinusState::NoState; - } - } - - let is_left_binary_plus_minus = matches!( - self.binary_plus_minus_state, - BinaryPlusMinusState::LeftIsBinaryPlusMinus - ); - let newline_context = self.update_indent_level( left_delim_state, right_delim_state, @@ -289,12 +257,12 @@ impl<'a> Formatter<'a> { // else do nothing, preserving the user's spaces before the comment } (Syntax(cooked_left), Syntax(cooked_right)) => match (cooked_left, cooked_right) { - // (ClosedBinOp(ClosedBinOp::Minus), _) | (_, ClosedBinOp(ClosedBinOp::Minus)) => { - // // This case is used to ignore the spacing around a `-`. - // // This is done because we currently don't have the architecture - // // to be able to differentiate between the unary `-` and the binary `-` - // // which would have different spacing rules. - // } + (ClosedBinOp(ClosedBinOp::Minus), _) | (_, ClosedBinOp(ClosedBinOp::Minus)) => { + // This case is used to ignore the spacing around a `-`. + // This is done because we currently don't have the architecture + // to be able to differentiate between the unary `-` and the binary `-` + // which would have different spacing rules. + } (Semi, _) if matches!(newline_context, NewlineContext::Spaces) => { effect_single_space(left, whitespace, right, &mut edits); } @@ -429,7 +397,7 @@ impl<'a> Formatter<'a> { } (_, Open(Delim::Brace)) => { // Special-case braces to have a leading single space with values - if is_prefix(cooked_left, is_left_binary_plus_minus) { + if is_prefix(cooked_left) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -437,8 +405,7 @@ impl<'a> Formatter<'a> { } (_, _) if matches!(right_delim_state, Delimiter::Open) => { // Otherwise, all open delims have the same logic - if is_value_token_left(cooked_left, left_delim_state) - || is_prefix(cooked_left, is_left_binary_plus_minus) + if is_value_token_left(cooked_left, left_delim_state) || is_prefix(cooked_left) { // i.e. foo() or foo[3] effect_no_space(left, whitespace, right, &mut edits); @@ -461,7 +428,7 @@ impl<'a> Formatter<'a> { effect_single_space(left, whitespace, right, &mut edits); } (_, _) if is_value_token_right(cooked_right, right_delim_state) => { - if is_prefix(cooked_left, is_left_binary_plus_minus) { + if is_prefix(cooked_left) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -470,16 +437,8 @@ impl<'a> Formatter<'a> { (_, _) if is_suffix(cooked_right) => { effect_no_space(left, whitespace, right, &mut edits); } - (_, _) - if is_prefix_with_space( - cooked_right, - matches!( - self.binary_plus_minus_state, - BinaryPlusMinusState::LastTokenIsValue - ), - ) => - { - if is_prefix(cooked_left, is_left_binary_plus_minus) { + (_, _) if is_prefix_with_space(cooked_right) => { + if is_prefix(cooked_left) { effect_no_space(left, whitespace, right, &mut edits); } else { effect_single_space(left, whitespace, right, &mut edits); @@ -689,14 +648,8 @@ fn is_bin_op(cooked: &TokenKind) -> bool { ) } -fn is_prefix_with_space(cooked: &TokenKind, is_binary_plus_minus: bool) -> bool { - match &cooked { - TokenKind::ClosedBinOp(ClosedBinOp::Plus | ClosedBinOp::Minus) if !is_binary_plus_minus => { - true - } - TokenKind::TildeTildeTilde => true, - _ => false, - } +fn is_prefix_with_space(cooked: &TokenKind) -> bool { + matches!(cooked, TokenKind::TildeTildeTilde) } fn is_prefix_without_space(cooked: &TokenKind) -> bool { @@ -706,8 +659,8 @@ fn is_prefix_without_space(cooked: &TokenKind) -> bool { ) } -fn is_prefix(cooked: &TokenKind, is_binary_plus_minus: bool) -> bool { - is_prefix_with_space(cooked, is_binary_plus_minus) +fn is_prefix(cooked: &TokenKind) -> bool { + is_prefix_with_space(cooked) || is_prefix_without_space(cooked) || matches!(cooked, TokenKind::DotDotDot) } From 82e34a5755d5d387352ef36ec1cc42366638a539 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Mon, 25 Mar 2024 09:57:32 -0700 Subject: [PATCH 07/13] corrected `-` in samples/libraries --- library/core/qir.qs | 2 +- library/src/tests/resources/compare.qs | 6 ++-- library/src/tests/resources/qft_le.qs | 2 +- .../src/tests/resources/state_preparation.qs | 2 +- library/std/arrays.qs | 2 +- library/std/canon.qs | 14 +++++----- library/std/core.qs | 8 +++--- library/std/intrinsic.qs | 6 ++-- library/std/math.qs | 15 ++++++---- library/std/measurement.qs | 2 +- library/std/unstable_arithmetic.qs | 18 ++++++------ library/std/unstable_arithmetic_internal.qs | 28 +++++++++---------- samples/algorithms/BitFlipCode.qs | 2 +- samples/algorithms/DeutschJozsa.qs | 4 +-- samples/algorithms/HiddenShift.qs | 2 +- samples/algorithms/HiddenShiftNISQ.qs | 2 +- samples/algorithms/PhaseFlipCode.qs | 2 +- samples/algorithms/Shor.qs | 6 ++-- samples/estimation/Dynamics.qs | 10 +++---- .../df-chemistry/src/df_chemistry.qs | 2 +- samples/language/ConditionalBranching.qs | 2 +- samples/language/Ternary.qs | 2 +- 22 files changed, 72 insertions(+), 67 deletions(-) diff --git a/library/core/qir.qs b/library/core/qir.qs index c77b5b25ab..7000092342 100644 --- a/library/core/qir.qs +++ b/library/core/qir.qs @@ -15,7 +15,7 @@ namespace QIR.Runtime { fail "Cannot allocate qubit array with a negative length"; } mutable qs = []; - for _ in 0..size-1 { + for _ in 0..size - 1 { set qs += [__quantum__rt__qubit_allocate()]; } qs diff --git a/library/src/tests/resources/compare.qs b/library/src/tests/resources/compare.qs index 74baf92e3a..7697f3873a 100644 --- a/library/src/tests/resources/compare.qs +++ b/library/src/tests/resources/compare.qs @@ -16,7 +16,7 @@ namespace Test { for a in 0..2 ^ n + 1 { // We want b to have more bits sometimes... - for b in 0..2 ^ n-1 { + for b in 0..2 ^ n - 1 { ApplyXorInPlace(b, qs); quantumComparator(IntAsBigInt(a), qs, t); let actual = MResetZ(t) == One; @@ -40,8 +40,8 @@ namespace Test { use y = Qubit[n]; use t = Qubit(); - for a in 0..2 ^ n-1 { - for b in 0..2 ^ n-1 { + for a in 0..2 ^ n - 1 { + for b in 0..2 ^ n - 1 { ApplyXorInPlace(a, x); ApplyXorInPlace(b, y); quantumComparator(x, y, t); diff --git a/library/src/tests/resources/qft_le.qs b/library/src/tests/resources/qft_le.qs index ab229c7816..6e8b4c2837 100644 --- a/library/src/tests/resources/qft_le.qs +++ b/library/src/tests/resources/qft_le.qs @@ -84,6 +84,6 @@ namespace Test { operation TestQFT(n : Int) : Unit { Fact(n >= 1 and n <= 4, "Only have four tests for QFT."); let testOperations = [QFT1, QFT2, QFT3, QFT4]; - AssertOperationsEqualReferenced(n, testOperations[n-1], q => ApplyQFT(Reversed(q))); + AssertOperationsEqualReferenced(n, testOperations[n - 1], q => ApplyQFT(Reversed(q))); } } diff --git a/library/src/tests/resources/state_preparation.qs b/library/src/tests/resources/state_preparation.qs index 9332382975..268e105079 100644 --- a/library/src/tests/resources/state_preparation.qs +++ b/library/src/tests/resources/state_preparation.qs @@ -95,7 +95,7 @@ namespace Test { let n = 4; use qs = Qubit[n]; let bitsize = 2 ^ n; - for i in 0..bitsize-1 { + for i in 0..bitsize - 1 { mutable c = Repeated(0.0, bitsize); set c w/= i <- 1.0; PreparePureStateD(c, qs); diff --git a/library/std/arrays.qs b/library/std/arrays.qs index b8b8211ee7..beffbc38cc 100644 --- a/library/std/arrays.qs +++ b/library/std/arrays.qs @@ -1028,7 +1028,7 @@ namespace Microsoft.Quantum.Arrays { /// # Output /// An array containing the elements `array[Length(array) - 1]` .. `array[0]`. function Reversed<'T>(array : 'T[]) : 'T[] { - array[... -1...] + array[...-1...] } /// # Summary diff --git a/library/std/canon.qs b/library/std/canon.qs index 7371e9e3d3..8b1d62a345 100644 --- a/library/std/canon.qs +++ b/library/std/canon.qs @@ -259,7 +259,7 @@ namespace Microsoft.Quantum.Canon { /// \end{align} /// $$ operation ApplyCNOTChain(qubits : Qubit[]) : Unit is Adj + Ctl { - for i in 0..Length(qubits)-2 { + for i in 0..Length(qubits) - 2 { CNOT(qubits[i], qubits[i + 1]); } } @@ -310,7 +310,7 @@ namespace Microsoft.Quantum.Canon { /// ``` operation ApplyPauli(pauli : Pauli[], target : Qubit[]) : Unit is Adj + Ctl { Fact(Length(pauli) == Length(target), "`pauli` and `target` must be of the same length."); - for i in 0..Length(pauli)-1 { + for i in 0..Length(pauli) - 1 { ApplyP(pauli[i], target[i]); } } @@ -345,7 +345,7 @@ namespace Microsoft.Quantum.Canon { operation ApplyPauliFromBitString(pauli : Pauli, bitApply : Bool, bits : Bool[], qubits : Qubit[]) : Unit is Adj + Ctl { let nBits = Length(bits); Fact(nBits == Length(qubits), "Number of control bits must be equal to number of control qubits."); - for i in 0..nBits-1 { + for i in 0..nBits - 1 { if bits[i] == bitApply { ApplyP(pauli, qubits[i]); } @@ -388,7 +388,7 @@ namespace Microsoft.Quantum.Canon { Fact(numberState >= 0, "number must be non-negative"); Fact(BitSizeI(numberState) <= length, "Bit size of numberState must not exceed qubits length"); - for i in 0..length-1 { + for i in 0..length - 1 { // If we assume loop unrolling, 2^i will be optimized to a constant. if ((numberState &&& (1 <<< i)) != 0) == bitApply { ApplyP(pauli, qubits[i]); @@ -491,10 +491,10 @@ namespace Microsoft.Quantum.Canon { operation ApplyQFT(qs : Qubit[]) : Unit is Adj + Ctl { let length = Length(qs); Fact(length >= 1, "ApplyQFT: Length(qs) must be at least 1."); - for i in length-1..-1..0 { + for i in length - 1..-1..0 { H(qs[i]); - for j in 0..i-1 { - Controlled R1Frac([qs[i]], (1, j + 1, qs[i-j-1])); + for j in 0..i - 1 { + Controlled R1Frac([qs[i]], (1, j + 1, qs[i - j - 1])); } } } diff --git a/library/std/core.qs b/library/std/core.qs index 37ff549950..8442c91202 100644 --- a/library/std/core.qs +++ b/library/std/core.qs @@ -22,8 +22,8 @@ namespace Microsoft.Quantum.Core { function RangeStart(r : Range) : Int { r::Start } - - + + /// # Summary /// Returns the defined end value of the given range, /// which is not necessarily the last element in the sequence. @@ -45,8 +45,8 @@ namespace Microsoft.Quantum.Core { function RangeEnd(r : Range) : Int { r::End } - - + + /// # Summary /// Returns the integer that specifies how the next value of a range is calculated. /// diff --git a/library/std/intrinsic.qs b/library/std/intrinsic.qs index 23ade7e4cf..77ec1621dd 100644 --- a/library/std/intrinsic.qs +++ b/library/std/intrinsic.qs @@ -306,7 +306,7 @@ namespace Microsoft.Quantum.Intrinsic { within { H(aux); } apply { - for i in 0..Length(bases)-1 { + for i in 0..Length(bases) - 1 { EntangleForJointMeasure(bases[i], aux, qubits[i]); } } @@ -362,7 +362,7 @@ namespace Microsoft.Quantum.Intrinsic { within { H(aux); } apply { - for i in 0..Length(bases)-1 { + for i in 0..Length(bases) - 1 { EntangleForJointMeasure(bases[i], aux, qubits[i]); } } @@ -401,7 +401,7 @@ namespace Microsoft.Quantum.Intrinsic { Rz(theta, qubit); } else { // PauliI - ApplyGlobalPhase( - theta / 2.0); + ApplyGlobalPhase(-theta / 2.0); } } diff --git a/library/std/math.qs b/library/std/math.qs index 09f89bbbb6..470341d9d6 100644 --- a/library/std/math.qs +++ b/library/std/math.qs @@ -883,14 +883,19 @@ namespace Microsoft.Quantum.Math { function LogGammaD(x : Double) : Double { // Here, we use the approximation described in Numerical Recipes in C. let coefficients = [ - 57.1562356658629235, -59.5979603554754912, - 14.1360979747417471, -0.491913816097620199, + 57.1562356658629235, + -59.5979603554754912, + 14.1360979747417471, + -0.491913816097620199, 0.339946499848118887e-4, - 0.465236289270485756e-4, -0.983744753048795646e-4, + 0.465236289270485756e-4, + -0.983744753048795646e-4, 0.158088703224912494e-3, -0.210264441724104883e-3, - 0.217439618115212643e-3, -0.164318106536763890e-3, - 0.844182239838527433e-4, -0.261908384015814087e-4, + 0.217439618115212643e-3, + -0.164318106536763890e-3, + 0.844182239838527433e-4, + -0.261908384015814087e-4, 0.368991826595316234e-5 ]; diff --git a/library/std/measurement.qs b/library/std/measurement.qs index fc4e05326a..d55a54f11c 100644 --- a/library/std/measurement.qs +++ b/library/std/measurement.qs @@ -152,7 +152,7 @@ namespace Microsoft.Quantum.Measurement { Fact(nBits < 64, $"`Length(target)` must be less than 64, but was {nBits}."); mutable number = 0; - for i in 0..nBits-1 { + for i in 0..nBits - 1 { if (MResetZ(target[i]) == One) { set number |||= 1 <<< i; } diff --git a/library/std/unstable_arithmetic.qs b/library/std/unstable_arithmetic.qs index df1b7c00c9..a22aa32357 100644 --- a/library/std/unstable_arithmetic.qs +++ b/library/std/unstable_arithmetic.qs @@ -169,7 +169,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { CNOT(xs[0], ys[0]); } elif xsLen + 1 == ysLen { if xsLen > 1 { - CNOT(xs[xsLen-1], ys[ysLen-1]); + CNOT(xs[xsLen - 1], ys[ysLen - 1]); within { ApplyOuterTTKAdder(xs, ys); } apply { @@ -222,20 +222,20 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { within { ApplyAndAssuming0Target(xs[0], ys[0], carries[0]); } apply { - for i in 1..xsLen-2 { - CarryForInc(carries[i-1], xs[i], ys[i], carries[i]); + for i in 1..xsLen - 2 { + CarryForInc(carries[i - 1], xs[i], ys[i], carries[i]); } if xsLen == ysLen { within { - CNOT(carries[xsLen-2], xs[xsLen-1]); + CNOT(carries[xsLen - 2], xs[xsLen - 1]); } apply { - CNOT(xs[xsLen-1], ys[xsLen-1]); + CNOT(xs[xsLen - 1], ys[xsLen - 1]); } } else { - FullAdderForInc(carries[xsLen-2], xs[xsLen-1], ys[xsLen-1], ys[xsLen]); + FullAdderForInc(carries[xsLen - 2], xs[xsLen - 1], ys[xsLen - 1], ys[xsLen]); } - for i in xsLen-2..-1..1 { - UncarryForInc(carries[i-1], xs[i], ys[i], carries[i]); + for i in xsLen - 2..-1..1 { + UncarryForInc(carries[i - 1], xs[i], ys[i], carries[i]); } } CNOT(xs[0], ys[0]); @@ -265,7 +265,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { // Since zs is zero-initialized, its bits at indexes higher than // xsLen remain unused as there will be no carry into them. - let top = MinI(zsLen-2, xsLen-1); + let top = MinI(zsLen - 2, xsLen - 1); for k in 0..top { FullAdder(zs[k], xs[k], ys[k], zs[k + 1]); } diff --git a/library/std/unstable_arithmetic_internal.qs b/library/std/unstable_arithmetic_internal.qs index d4622ef337..c73f962d9e 100644 --- a/library/std/unstable_arithmetic_internal.qs +++ b/library/std/unstable_arithmetic_internal.qs @@ -27,10 +27,10 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { /// https://arxiv.org/abs/0910.2530 internal operation ApplyOuterTTKAdder(xs : Qubit[], ys : Qubit[]) : Unit is Adj + Ctl { Fact(Length(xs) <= Length(ys), "Input register ys must be at lease as long as xs."); - for i in 1..Length(xs)-1 { + for i in 1..Length(xs) - 1 { CNOT(xs[i], ys[i]); } - for i in Length(xs)-2..-1..1 { + for i in Length(xs) - 2..-1..1 { CNOT(xs[i], xs[i + 1]); } } @@ -68,7 +68,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { for idx in 0..Length(xs) - 2 { CCNOT(xs[idx], ys[idx], xs[idx + 1]); } - for idx in Length(xs)-1..-1..1 { + for idx in Length(xs) - 1..-1..1 { Controlled CNOT(controls, (xs[idx], ys[idx])); CCNOT(xs[idx - 1], ys[idx - 1], xs[idx]); } @@ -111,10 +111,10 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { for idx in 0..nQubits - 2 { CCNOT(xs[idx], ys[idx], xs[idx + 1]); } - (Controlled CCNOT)(controls, (xs[nQubits-1], ys[nQubits-1], ys[nQubits])); + (Controlled CCNOT)(controls, (xs[nQubits - 1], ys[nQubits - 1], ys[nQubits])); for idx in nQubits - 1..-1..1 { Controlled CNOT(controls, (xs[idx], ys[idx])); - CCNOT(xs[idx-1], ys[idx-1], xs[idx]); + CCNOT(xs[idx - 1], ys[idx - 1], xs[idx]); } } } @@ -444,7 +444,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { Fact(Length(cs1) == Length(qs), "Arrays should be of the same length."); within { - for i in 0..Length(cs1)-1 { + for i in 0..Length(cs1) - 1 { let op = cNormalized &&& (1L <<< (i + 1)) != 0L ? ApplyAndAssuming0Target | ApplyOrAssuming0Target; op(cs1[i], xNormalized[i + 1], qs[i]); } @@ -481,16 +481,16 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { within { CarryWith1CarryIn(x[0], y[0], carries[0]); - for i in 1..n-1 { - CarryForInc(carries[i-1], x[i], y[i], carries[i]); + for i in 1..n - 1 { + CarryForInc(carries[i - 1], x[i], y[i], carries[i]); } } apply { within { if invertControl { - X(carries[n-1]); + X(carries[n - 1]); } } apply { - Controlled action([carries[n-1]], target); + Controlled action([carries[n - 1]], target); } } } @@ -543,14 +543,14 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { } elif n == 1 { Controlled op(ctls, input); } else { - use aux = Qubit[n-1]; + use aux = Qubit[n - 1]; within { ApplyAndAssuming0Target(ctls[0], ctls[1], aux[0]); - for i in 1..n-2 { - ApplyAndAssuming0Target(aux[i-1], ctls[i + 1], aux[i]); + for i in 1..n - 2 { + ApplyAndAssuming0Target(aux[i - 1], ctls[i + 1], aux[i]); } } apply { - Controlled op(aux[n-2..n-2], input); + Controlled op(aux[n - 2..n - 2], input); } } } diff --git a/samples/algorithms/BitFlipCode.qs b/samples/algorithms/BitFlipCode.qs index 6b04ecac9d..1df7f24dbe 100644 --- a/samples/algorithms/BitFlipCode.qs +++ b/samples/algorithms/BitFlipCode.qs @@ -124,7 +124,7 @@ namespace Sample { } elif (parity01, parity12) == (Zero, One) { 2 } else { - -1 + -1 }; // If an error was detected, correct that qubit. diff --git a/samples/algorithms/DeutschJozsa.qs b/samples/algorithms/DeutschJozsa.qs index 4c0b0f1f87..af15212316 100644 --- a/samples/algorithms/DeutschJozsa.qs +++ b/samples/algorithms/DeutschJozsa.qs @@ -129,7 +129,7 @@ namespace Sample { // A more complex constant Boolean function. // It applies X to every input basis vector. operation ConstantBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..(2 ^ Length(args))-1 { + for i in 0..(2 ^ Length(args)) - 1 { ApplyControlledOnInt(i, X, args, target); } } @@ -137,7 +137,7 @@ namespace Sample { // A more complex balanced Boolean function. // It applies X to half of the input basis vectors. operation BalancedBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..2..(2 ^ Length(args))-1 { + for i in 0..2..(2 ^ Length(args)) - 1 { ApplyControlledOnInt(i, X, args, target); } } diff --git a/samples/algorithms/HiddenShift.qs b/samples/algorithms/HiddenShift.qs index 35d2caa852..f60888e4ea 100644 --- a/samples/algorithms/HiddenShift.qs +++ b/samples/algorithms/HiddenShift.qs @@ -146,7 +146,7 @@ namespace Sample { let u = Length(register) / 2; let xs = register[0..u - 1]; let ys = register[u...]; - for index in 0..u-1 { + for index in 0..u - 1 { CZ(xs[index], ys[index]); } } diff --git a/samples/algorithms/HiddenShiftNISQ.qs b/samples/algorithms/HiddenShiftNISQ.qs index 635248ac32..a5c0da2306 100644 --- a/samples/algorithms/HiddenShiftNISQ.qs +++ b/samples/algorithms/HiddenShiftNISQ.qs @@ -136,7 +136,7 @@ namespace Sample { let u = Length(register) / 2; let xs = register[0..u - 1]; let ys = register[u...]; - for index in 0..u-1 { + for index in 0..u - 1 { CZ(xs[index], ys[index]); } } diff --git a/samples/algorithms/PhaseFlipCode.qs b/samples/algorithms/PhaseFlipCode.qs index 5248d13bd3..0a052731fd 100644 --- a/samples/algorithms/PhaseFlipCode.qs +++ b/samples/algorithms/PhaseFlipCode.qs @@ -145,7 +145,7 @@ namespace Sample { } elif (parity01, parity12) == (Zero, One) { 2 } else { - -1 + -1 }; // If an error was detected, correct that qubit. diff --git a/samples/algorithms/Shor.qs b/samples/algorithms/Shor.qs index a991f815c0..f42d6036c5 100644 --- a/samples/algorithms/Shor.qs +++ b/samples/algorithms/Shor.qs @@ -275,17 +275,17 @@ namespace Sample { // Use phase estimation with a semiclassical Fourier transform to // estimate the frequency. use c = Qubit(); - for idx in bitsPrecision-1..-1..0 { + for idx in bitsPrecision - 1..-1..0 { H(c); Controlled ApplyOrderFindingOracle( [c], (generator, modulus, 1 <<< idx, eigenstateRegister) ); - R1Frac(frequencyEstimate, bitsPrecision-1-idx, c); + R1Frac(frequencyEstimate, bitsPrecision - 1 - idx, c); H(c); if M(c) == One { X(c); // Reset - set frequencyEstimate += 1 <<< (bitsPrecision-1-idx); + set frequencyEstimate += 1 <<< (bitsPrecision - 1 - idx); } } diff --git a/samples/estimation/Dynamics.qs b/samples/estimation/Dynamics.qs index 41558cb94c..5e31845c3c 100644 --- a/samples/estimation/Dynamics.qs +++ b/samples/estimation/Dynamics.qs @@ -76,7 +76,7 @@ namespace QuantumDynamics { } } - for i in len1 + len2 + 1..valLength-1 { + for i in len1 + len2 + 1..valLength - 1 { if (i % 2 == 0) { set values w/= i <- val1; } else { @@ -98,7 +98,7 @@ namespace QuantumDynamics { operation ApplyAllX(n : Int, qArr : Qubit[][], theta : Double) : Unit { // This applies `Rx` with an angle of `2.0 * theta` to all qubits in `qs` // using partial application - for row in 0..n-1 { + for row in 0..n - 1 { ApplyToEach(Rx(2.0 * theta, _), qArr[row]); } } @@ -119,8 +119,8 @@ namespace QuantumDynamics { operation ApplyDoubleZ(n : Int, m : Int, qArr : Qubit[][], theta : Double, dir : Bool, grp : Bool) : Unit { let start = grp ? 1 | 0; // Choose either odd or even indices based on group number let P_op = [PauliZ, PauliZ]; - let c_end = dir ? m-1 | m-2; - let r_end = dir ? m-2 | m-1; + let c_end = dir ? m - 1 | m - 2; + let r_end = dir ? m - 2 | m - 1; for row in 0..r_end { for col in start..2..c_end { @@ -160,7 +160,7 @@ namespace QuantumDynamics { let angSeq = SetAngleSequence(p, dt, J, g); for i in 0..seqLen - 1 { - let theta = (i == 0 or i == seqLen-1) ? J * p * dt / 2.0 | angSeq[i % 10]; + let theta = (i == 0 or i == seqLen - 1) ? J * p * dt / 2.0 | angSeq[i % 10]; // for even indexes if i % 2 == 0 { diff --git a/samples/estimation/df-chemistry/src/df_chemistry.qs b/samples/estimation/df-chemistry/src/df_chemistry.qs index 50a54930c0..ffbd5c04de 100644 --- a/samples/estimation/df-chemistry/src/df_chemistry.qs +++ b/samples/estimation/df-chemistry/src/df_chemistry.qs @@ -335,7 +335,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { mutable result = []; mutable sins = 1.0; - for index in 0..Length(eigenVector)-2 { + for index in 0..Length(eigenVector) - 2 { // We apply MinD, such that rounding errors do not lead to // an argument for ArcCos which is larger than 1.0. (p. 52, eq. 56) let theta = sins == 0.0 ? 0.0 | 0.5 * ArcCos(MinD(eigenVector[index] / sins, 1.0)); diff --git a/samples/language/ConditionalBranching.qs b/samples/language/ConditionalBranching.qs index 2a4e030817..876a3d9960 100644 --- a/samples/language/ConditionalBranching.qs +++ b/samples/language/ConditionalBranching.qs @@ -38,4 +38,4 @@ namespace MyQuantumApp { // `if` can also be used as an expression, to conditionally return a value. let absoluteValue = if fahrenheit > 0 { fahrenheit } else { fahrenheit * -1 }; } -} \ No newline at end of file +} diff --git a/samples/language/Ternary.qs b/samples/language/Ternary.qs index 2cd8d9ba9e..e89abf499f 100644 --- a/samples/language/Ternary.qs +++ b/samples/language/Ternary.qs @@ -17,4 +17,4 @@ namespace MyQuantumApp { // `fahrenheit * -1` if `fahrenheit` is negative. let absoluteValue = fahrenheit > 0 ? fahrenheit | fahrenheit * -1; } -} \ No newline at end of file +} From 645c87e08be1e1e02df71f2c29fb08965d226e0b Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Mon, 25 Mar 2024 10:19:56 -0700 Subject: [PATCH 08/13] update spans in debugger integration test --- vscode/test/suites/debugger/debugger.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vscode/test/suites/debugger/debugger.test.ts b/vscode/test/suites/debugger/debugger.test.ts index 848512bc53..724f76c100 100644 --- a/vscode/test/suites/debugger/debugger.test.ts +++ b/vscode/test/suites/debugger/debugger.test.ts @@ -375,10 +375,10 @@ suite("Q# Debugger Tests", function suite() { sourceReference: 0, adapterData: "qsharp-adapter-data", }, - line: 165, + line: 159, column: 13, name: "H ", - endLine: 165, + endLine: 159, endColumn: 44, }, { From 4b7561c5f1033138aa9a57933e530c5ea1ae4146 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Mon, 25 Mar 2024 10:40:42 -0700 Subject: [PATCH 09/13] updated spans in eval test --- compiler/qsc_eval/src/tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/qsc_eval/src/tests.rs b/compiler/qsc_eval/src/tests.rs index 9ff7984d61..aeedc5ec12 100644 --- a/compiler/qsc_eval/src/tests.rs +++ b/compiler/qsc_eval/src/tests.rs @@ -440,16 +440,16 @@ fn block_qubit_use_array_invalid_count_expr() { 0, ), span: Span { - lo: 1568, - hi: 1625, + lo: 1566, + hi: 1623, }, }, ), [ Frame { span: Span { - lo: 1568, - hi: 1625, + lo: 1566, + hi: 1623, }, id: StoreItemId { package: PackageId( From 0a8afbe4e3ca34a32e4308815ab599d31cd195b0 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Mon, 25 Mar 2024 16:48:01 -0700 Subject: [PATCH 10/13] manually updated the format of several sample/library files --- library/src/tests/resources/add_le.qs | 15 ++++++-- library/std/math.qs | 48 ++++++++++++++++++++++--- samples/algorithms/BernsteinVazirani.qs | 2 +- 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/library/src/tests/resources/add_le.qs b/library/src/tests/resources/add_le.qs index e9b8b6c522..86dc032365 100644 --- a/library/src/tests/resources/add_le.qs +++ b/library/src/tests/resources/add_le.qs @@ -26,9 +26,18 @@ namespace Test { let zActual = MeasureInteger(z); let zExpected = (xValue + yValue) % (1 <<< zLen); - Fact(xActual == xValue, $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); - Fact(yActual == yValue, $"{name}: Incorrect y={yActual}, expected={yValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); - Fact(zActual == zExpected, $"{name}: Incorrect z={zActual}, expected={zExpected}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}."); + Fact( + xActual == xValue, + $"{name}: Incorrect x={xActual}, expected={xValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}." + ); + Fact( + yActual == yValue, + $"{name}: Incorrect y={yActual}, expected={yValue}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}." + ); + Fact( + zActual == zExpected, + $"{name}: Incorrect z={zActual}, expected={zExpected}. |x|={xLen}, |y|={yLen}, |z|={zLen}, x={xValue}, y={yValue}." + ); ResetAll(x); ResetAll(y); diff --git a/library/std/math.qs b/library/std/math.qs index 470341d9d6..6cb36150db 100644 --- a/library/std/math.qs +++ b/library/std/math.qs @@ -102,19 +102,37 @@ namespace Microsoft.Quantum.Math { /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. function SignI(a : Int) : Int { - if (a < 0) { -1 } elif (a > 0) { + 1 } else { 0 } + if (a < 0) { + -1 + } elif (a > 0) { + + 1 + } else { + 0 + } } /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. function SignD(a : Double) : Int { - if (a < 0.0) { -1 } elif (a > 0.0) { + 1 } else { 0 } + if (a < 0.0) { + -1 + } elif (a > 0.0) { + + 1 + } else { + 0 + } } /// # Summary /// Returns -1, 0 or +1 that indicates the sign of a number. function SignL(a : BigInt) : Int { - if (a < 0L) { -1 } elif (a > 0L) { + 1 } else { 0 } + if (a < 0L) { + -1 + } elif (a > 0L) { + + 1 + } else { + 0 + } } /// # Summary @@ -797,7 +815,29 @@ namespace Microsoft.Quantum.Math { Fact(n >= 0, "The factorial is not defined for negative inputs."); Fact(n <= 20, "The largest factorial that can be stored as an Int is 20!. Use FactorialL or ApproximateFactorial."); - [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000][n] + [ + 1, + 1, + 2, + 6, + 24, + 120, + 720, + 5040, + 40320, + 362880, + 3628800, + 39916800, + 479001600, + 6227020800, + 87178291200, + 1307674368000, + 20922789888000, + 355687428096000, + 6402373705728000, + 121645100408832000, + 2432902008176640000 + ][n] } /// # Summary diff --git a/samples/algorithms/BernsteinVazirani.qs b/samples/algorithms/BernsteinVazirani.qs index 7a640d5a40..eae0e341d8 100644 --- a/samples/algorithms/BernsteinVazirani.qs +++ b/samples/algorithms/BernsteinVazirani.qs @@ -142,7 +142,7 @@ namespace Sample { let availableQubits = Length(xRegister); Fact( availableQubits >= requiredBits, - $"Integer value {bitStringAsInt} requires {requiredBits} bits to " + $"be represented but the quantum register only has " + $"{availableQubits} qubits" + $"Integer value {bitStringAsInt} requires {requiredBits} bits to be represented but the quantum register only has {availableQubits} qubits" ); // Apply the quantum operations that encode the bit string. From 251d5bea9e5055730a4de309202ff6a02e86fded Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Tue, 26 Mar 2024 10:15:32 -0700 Subject: [PATCH 11/13] no spacing around `^` --- compiler/qsc_formatter/src/formatter.rs | 7 +++++-- compiler/qsc_formatter/src/formatter/tests.rs | 14 ++++++++++++++ library/src/tests/resources/compare.qs | 8 ++++---- library/src/tests/resources/select.qs | 4 ++-- library/src/tests/resources/state_preparation.qs | 2 +- library/std/intrinsic.qs | 2 +- library/std/math.qs | 16 ++++++++-------- library/std/unstable_arithmetic.qs | 4 ++-- library/std/unstable_arithmetic_internal.qs | 12 ++++++------ library/std/unstable_state_preparation.qs | 6 +++--- library/std/unstable_table_lookup.qs | 14 +++++++------- samples/algorithms/BernsteinVazirani.qs | 2 +- samples/algorithms/DeutschJozsa.qs | 4 ++-- samples/algorithms/Shor.qs | 2 +- samples/estimation/Dynamics.qs | 2 +- samples/estimation/EkeraHastadFactoring.qs | 10 +++++----- samples/estimation/ShorRE.qs | 2 +- .../estimation/df-chemistry/src/df_chemistry.qs | 4 ++-- samples/estimation/df-chemistry/src/prepare.qs | 4 ++-- samples/language/ArithmeticOperators.qs | 12 ++++++------ samples/language/BigInt.qs | 2 +- samples/language/Int.qs | 2 +- samples/language/Range.qs | 2 +- 23 files changed, 77 insertions(+), 60 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter.rs b/compiler/qsc_formatter/src/formatter.rs index 32d8c962b8..9bb3816135 100644 --- a/compiler/qsc_formatter/src/formatter.rs +++ b/compiler/qsc_formatter/src/formatter.rs @@ -6,7 +6,7 @@ use qsc_frontend::{ keyword::Keyword, lex::{ concrete::{self, ConcreteToken, ConcreteTokenKind}, - cooked::{StringToken, TokenKind}, + cooked::{ClosedBinOp, StringToken, TokenKind}, Delim, InterpolatedEnding, InterpolatedStart, }, }; @@ -655,7 +655,10 @@ fn is_prefix_with_space(cooked: &TokenKind) -> bool { fn is_prefix_without_space(cooked: &TokenKind) -> bool { matches!( cooked, - TokenKind::ColonColon | TokenKind::Dot | TokenKind::DotDot + TokenKind::ColonColon + | TokenKind::Dot + | TokenKind::DotDot + | TokenKind::ClosedBinOp(ClosedBinOp::Caret) ) } diff --git a/compiler/qsc_formatter/src/formatter/tests.rs b/compiler/qsc_formatter/src/formatter/tests.rs index 1d8f9b9f66..e08818c04d 100644 --- a/compiler/qsc_formatter/src/formatter/tests.rs +++ b/compiler/qsc_formatter/src/formatter/tests.rs @@ -1048,6 +1048,20 @@ fn copy_operator_with_space_has_single_space() { ) } +#[test] +fn no_space_around_carrot() { + check( + indoc! {r#" + {} ^ {} + 1 ^ 2 + "#}, + &expect![[r#" + {}^{} + 1^2 + "#]], + ) +} + #[test] fn no_space_around_ellipse() { check( diff --git a/library/src/tests/resources/compare.qs b/library/src/tests/resources/compare.qs index 7697f3873a..1330691592 100644 --- a/library/src/tests/resources/compare.qs +++ b/library/src/tests/resources/compare.qs @@ -14,9 +14,9 @@ namespace Test { use qs = Qubit[n]; use t = Qubit(); - for a in 0..2 ^ n + 1 { + for a in 0..2^n + 1 { // We want b to have more bits sometimes... - for b in 0..2 ^ n - 1 { + for b in 0..2^n - 1 { ApplyXorInPlace(b, qs); quantumComparator(IntAsBigInt(a), qs, t); let actual = MResetZ(t) == One; @@ -40,8 +40,8 @@ namespace Test { use y = Qubit[n]; use t = Qubit(); - for a in 0..2 ^ n - 1 { - for b in 0..2 ^ n - 1 { + for a in 0..2^n - 1 { + for b in 0..2^n - 1 { ApplyXorInPlace(a, x); ApplyXorInPlace(b, y); quantumComparator(x, y, t); diff --git a/library/src/tests/resources/select.qs b/library/src/tests/resources/select.qs index ceb035e149..08087539ad 100644 --- a/library/src/tests/resources/select.qs +++ b/library/src/tests/resources/select.qs @@ -10,7 +10,7 @@ namespace Test { use temporaryRegister = Qubit[dataBits]; use dataRegister = Qubit[dataBits]; - let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), 2 ^ addressBits, 0); + let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), 2^addressBits, 0); for (index, expected) in Enumerated(data) { ApplyXorInPlace(index, addressRegister); @@ -32,7 +32,7 @@ namespace Test { for _ in 1..rounds { let addressBits = DrawRandomInt(2, 6); let dataBits = 10; - let numData = DrawRandomInt(2 ^ (addressBits - 1) + 1, 2 ^ addressBits - 1); + let numData = DrawRandomInt(2^(addressBits - 1) + 1, 2^addressBits - 1); let data = DrawMany(_ => DrawMany(_ => (DrawRandomInt(0, 1) == 1), dataBits, 0), numData, 0); diff --git a/library/src/tests/resources/state_preparation.qs b/library/src/tests/resources/state_preparation.qs index 268e105079..a6f573b734 100644 --- a/library/src/tests/resources/state_preparation.qs +++ b/library/src/tests/resources/state_preparation.qs @@ -94,7 +94,7 @@ namespace Test { operation TestEndianness() : Unit { let n = 4; use qs = Qubit[n]; - let bitsize = 2 ^ n; + let bitsize = 2^n; for i in 0..bitsize - 1 { mutable c = Repeated(0.0, bitsize); set c w/= i <- 1.0; diff --git a/library/std/intrinsic.qs b/library/std/intrinsic.qs index 77ec1621dd..dfaaf397eb 100644 --- a/library/std/intrinsic.qs +++ b/library/std/intrinsic.qs @@ -546,7 +546,7 @@ namespace Microsoft.Quantum.Intrinsic { operation RFrac(pauli : Pauli, numerator : Int, power : Int, qubit : Qubit) : Unit is Adj + Ctl { // Note that power must be converted to a double and used with 2.0 instead of 2 to allow for // negative exponents that result in a fractional denominator. - let angle = ((-2.0 * PI()) * IntAsDouble(numerator)) / (2.0 ^ IntAsDouble(power)); + let angle = ((-2.0 * PI()) * IntAsDouble(numerator)) / (2.0^IntAsDouble(power)); R(pauli, angle, qubit); } diff --git a/library/std/math.qs b/library/std/math.qs index 6cb36150db..fd59370132 100644 --- a/library/std/math.qs +++ b/library/std/math.qs @@ -895,8 +895,8 @@ namespace Microsoft.Quantum.Math { let absN = IntAsDouble(n); let a = Sqrt(2.0 * PI() * absN); - let b = (absN / E()) ^ absN; - let c = E() ^ (1.0 / (12.0 * absN) - (1.0 / (360.0 * (absN ^ 3.0)))); + let b = (absN / E())^absN; + let c = E()^(1.0 / (12.0 * absN) - (1.0 / (360.0 * (absN^3.0)))); a * b * c } @@ -992,7 +992,7 @@ namespace Microsoft.Quantum.Math { if n < 171 { Floor(0.5 + ApproximateFactorial(n) / (ApproximateFactorial(k) * ApproximateFactorial(n - k))) } else { - Floor(0.5 + E() ^ (LogFactorialD(n) - LogFactorialD(k) - LogFactorialD(n - k))) + Floor(0.5 + E()^(LogFactorialD(n) - LogFactorialD(k) - LogFactorialD(n - k))) } } @@ -1041,10 +1041,10 @@ namespace Microsoft.Quantum.Math { mutable sum = 0.0; for element in array { - set sum += AbsD(element) ^ p; + set sum += AbsD(element)^p; } - sum ^ (1.0 / p) + sum^(1.0 / p) } /// # Summary @@ -1334,7 +1334,7 @@ namespace Microsoft.Quantum.Math { // magnitude = 𝑒^((c⋅ln(baseNorm) - d⋅baseArg)) = baseNorm^c / 𝑒^(d⋅baseArg) // angle = d⋅ln(baseNorm) + c⋅baseArg - let magnitude = baseNorm ^ c / E() ^ (d * baseArg); + let magnitude = baseNorm^c / E()^(d * baseArg); let angle = d * Log(baseNorm) + c * baseArg; ComplexPolar(magnitude, angle) @@ -1422,7 +1422,7 @@ namespace Microsoft.Quantum.Math { /// # Remark /// The value can be computed as -2^(p-1), where p is the number of integer bits. function SmallestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { - -(2.0 ^ IntAsDouble(integerBits - 1)) + -(2.0^IntAsDouble(integerBits - 1)) } /// # Summary @@ -1438,7 +1438,7 @@ namespace Microsoft.Quantum.Math { /// The value can be computed as 2^(p-1) - 2^(-q), where p /// is the number of integer bits and q is the number of fractional bits. function LargestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { - 2.0 ^ IntAsDouble(integerBits - 1) - 2.0 ^ (-IntAsDouble(fractionalBits)) + 2.0^IntAsDouble(integerBits - 1) - 2.0^(-IntAsDouble(fractionalBits)) } } diff --git a/library/std/unstable_arithmetic.qs b/library/std/unstable_arithmetic.qs index a22aa32357..4841801318 100644 --- a/library/std/unstable_arithmetic.qs +++ b/library/std/unstable_arithmetic.qs @@ -366,7 +366,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let ysLen = Length(ys); Fact(ysLen > 0, "Length of `ys` must be at least 1."); Fact(c >= 0L, "Constant `c` must be non-negative."); - Fact(c < 2L ^ ysLen, "Constant `c` must be smaller than 2^Length(ys)."); + Fact(c < 2L^ysLen, "Constant `c` must be smaller than 2^Length(ys)."); if c != 0L { // If c has j trailing zeros, then the j least significant @@ -399,7 +399,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let ysLen = Length(ys); Fact(ysLen > 0, "Length of `ys` must be at least 1."); Fact(c >= 0, "Constant `c` must be non-negative."); - Fact(c < 2 ^ ysLen, "Constant `c` must be smaller than 2^Length(ys)."); + Fact(c < 2^ysLen, "Constant `c` must be smaller than 2^Length(ys)."); if c != 0 { // If c has j trailing zeros than the j least significant diff --git a/library/std/unstable_arithmetic_internal.qs b/library/std/unstable_arithmetic_internal.qs index c73f962d9e..317d7a048a 100644 --- a/library/std/unstable_arithmetic_internal.qs +++ b/library/std/unstable_arithmetic_internal.qs @@ -315,7 +315,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let T = Floor(Lg(IntAsDouble(n))); use qs = Qubit[n - HammingWeightI(n) - T]; - let registerPartition = MappedOverRange(t -> Floor(IntAsDouble(n) / IntAsDouble(2 ^ t)) - 1, 1..T - 1); + let registerPartition = MappedOverRange(t -> Floor(IntAsDouble(n) / IntAsDouble(2^t)) - 1, 1..T - 1); let pWorkspace = [ps] + Partitioned(registerPartition, qs); within { @@ -370,11 +370,11 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let n = Length(gs); for t in 1..T { - let length = Floor(IntAsDouble(n) / IntAsDouble(2 ^ t)) - 1; + let length = Floor(IntAsDouble(n) / IntAsDouble(2^t)) - 1; let ps = pWorkspace[t - 1][0..2...]; for m in 0..length { - CCNOT(gs[2 ^ t * m + 2 ^ (t - 1) - 1], ps[m], gs[2 ^ t * m + 2 ^ t - 1]); + CCNOT(gs[2^t * m + 2^(t - 1) - 1], ps[m], gs[2^t * m + 2^t - 1]); } } } @@ -386,11 +386,11 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { let start = Floor(Lg(IntAsDouble(2 * n) / 3.0)); for t in start..-1..1 { - let length = Floor(IntAsDouble(n - 2 ^ (t - 1)) / IntAsDouble(2 ^ t)); + let length = Floor(IntAsDouble(n - 2^(t - 1)) / IntAsDouble(2^t)); let ps = pWorkspace[t - 1][1..2...]; for m in 1..length { - CCNOT(gs[2 ^ t * m - 1], ps[m - 1], gs[2 ^ t * m + 2 ^ (t - 1) - 1]); + CCNOT(gs[2^t * m - 1], ps[m - 1], gs[2^t * m + 2^(t - 1) - 1]); } } } @@ -422,7 +422,7 @@ namespace Microsoft.Quantum.Unstable.Arithmetic { if not invertControl { action(target); } - } elif c >= (2L ^ bitWidth) { + } elif c >= (2L^bitWidth) { if invertControl { action(target); } diff --git a/library/std/unstable_state_preparation.qs b/library/std/unstable_state_preparation.qs index 197b280b37..cefe72bd78 100644 --- a/library/std/unstable_state_preparation.qs +++ b/library/std/unstable_state_preparation.qs @@ -112,7 +112,7 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { let nQubits = Length(qubits); // pad coefficients at tail length to a power of 2. - let coefficientsPadded = Padded(-2 ^ nQubits, ComplexPolar(0.0, 0.0), coefficients); + let coefficientsPadded = Padded(-2^nQubits, ComplexPolar(0.0, 0.0), coefficients); let idxTarget = 0; // Determine what controls to apply let rngControl = nQubits > 1 ? (1..(nQubits - 1)) | (1..0); @@ -326,7 +326,7 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { body (...) { // pad coefficients length at tail to a power of 2. - let coefficientsPadded = Padded(-2 ^ Length(control), 0.0, coefficients); + let coefficientsPadded = Padded(-2^Length(control), 0.0, coefficients); if Length(coefficientsPadded) == 1 { // Termination case @@ -349,7 +349,7 @@ namespace Microsoft.Quantum.Unstable.StatePreparation { controlled (controlRegister, ...) { // pad coefficients length to a power of 2. - let coefficientsPadded = Padded(2 ^ (Length(control) + 1), 0.0, Padded(-2 ^ Length(control), 0.0, coefficients)); + let coefficientsPadded = Padded(2^(Length(control) + 1), 0.0, Padded(-2^Length(control), 0.0, coefficients)); let (coefficients0, coefficients1) = MultiplexZCoefficients(coefficientsPadded); ApproximatelyMultiplexZ(tolerance, coefficients0, control, target); if AnyOutsideToleranceD(tolerance, coefficients1) { diff --git a/library/std/unstable_table_lookup.qs b/library/std/unstable_table_lookup.qs index 9258d5c437..1d9d9b9608 100644 --- a/library/std/unstable_table_lookup.qs +++ b/library/std/unstable_table_lookup.qs @@ -57,7 +57,7 @@ namespace Microsoft.Quantum.Unstable.TableLookup { WriteMemoryContents(Head(data), target); } else { let (most, tail) = MostAndTail(address[...n - 1]); - let parts = Partitioned([2 ^ (n - 1)], data); + let parts = Partitioned([2^(n - 1)], data); within { X(tail); @@ -114,7 +114,7 @@ namespace Microsoft.Quantum.Unstable.TableLookup { use helper = Qubit(); let (most, tail) = MostAndTail(address[...n - 1]); - let parts = Partitioned([2 ^ (n - 1)], data); + let parts = Partitioned([2^(n - 1)], data); within { X(tail); @@ -184,12 +184,12 @@ namespace Microsoft.Quantum.Unstable.TableLookup { let res = Mapped(r -> r == One, ForEach(MResetX, target)); - let dataFixup = Chunks(2 ^ l, Padded(-2 ^ numAddressBits, false, Mapped(MustBeFixed(res, _), data))); + let dataFixup = Chunks(2^l, Padded(-2^numAddressBits, false, Mapped(MustBeFixed(res, _), data))); let numAddressBitsFixup = numAddressBits - l; let selectParts = Partitioned([l], select); - let targetFixup = target[...2 ^ l - 1]; + let targetFixup = target[...2^l - 1]; within { EncodeUnary(selectParts[0], targetFixup); @@ -223,8 +223,8 @@ namespace Microsoft.Quantum.Unstable.TableLookup { target : Qubit[] ) : Unit is Adj { Fact( - Length(target) == 2 ^ Length(input), - $"target register should be of length {2 ^ Length(input)}, but is {Length(target)}" + Length(target) == 2^Length(input), + $"target register should be of length {2^Length(input)}, but is {Length(target)}" ); X(Head(target)); @@ -235,7 +235,7 @@ namespace Microsoft.Quantum.Unstable.TableLookup { CNOT(target[1], target[0]); } else { // targets are the first and second 2^i qubits of the target register - let split = Partitioned([2 ^ i, 2 ^ i], target); + let split = Partitioned([2^i, 2^i], target); for j in IndexRange(split[0]) { ApplyAndAssuming0Target(input[i], split[0][j], split[1][j]); CNOT(split[1][j], split[0][j]); diff --git a/samples/algorithms/BernsteinVazirani.qs b/samples/algorithms/BernsteinVazirani.qs index eae0e341d8..c0ed830db8 100644 --- a/samples/algorithms/BernsteinVazirani.qs +++ b/samples/algorithms/BernsteinVazirani.qs @@ -147,7 +147,7 @@ namespace Sample { // Apply the quantum operations that encode the bit string. for index in IndexRange(xRegister) { - if ((bitStringAsInt &&& 2 ^ index) != 0) { + if ((bitStringAsInt &&& 2^index) != 0) { CNOT(xRegister[index], yQubit); } } diff --git a/samples/algorithms/DeutschJozsa.qs b/samples/algorithms/DeutschJozsa.qs index af15212316..3ec9f1864d 100644 --- a/samples/algorithms/DeutschJozsa.qs +++ b/samples/algorithms/DeutschJozsa.qs @@ -129,7 +129,7 @@ namespace Sample { // A more complex constant Boolean function. // It applies X to every input basis vector. operation ConstantBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..(2 ^ Length(args)) - 1 { + for i in 0..(2^Length(args)) - 1 { ApplyControlledOnInt(i, X, args, target); } } @@ -137,7 +137,7 @@ namespace Sample { // A more complex balanced Boolean function. // It applies X to half of the input basis vectors. operation BalancedBoolF(args : Qubit[], target : Qubit) : Unit { - for i in 0..2..(2 ^ Length(args)) - 1 { + for i in 0..2..(2^Length(args)) - 1 { ApplyControlledOnInt(i, X, args, target); } } diff --git a/samples/algorithms/Shor.qs b/samples/algorithms/Shor.qs index f42d6036c5..bf1c354775 100644 --- a/samples/algorithms/Shor.qs +++ b/samples/algorithms/Shor.qs @@ -176,7 +176,7 @@ namespace Sample { // Now we use the ContinuedFractionConvergentI function to recover s/r // from dyadic fraction k/2^bitsPrecision. let (numerator, period) = ContinuedFractionConvergentI( - (frequencyEstimate, 2 ^ bitsPrecision), + (frequencyEstimate, 2^bitsPrecision), modulus ); diff --git a/samples/estimation/Dynamics.qs b/samples/estimation/Dynamics.qs index 5e31845c3c..a985c2edf7 100644 --- a/samples/estimation/Dynamics.qs +++ b/samples/estimation/Dynamics.qs @@ -152,7 +152,7 @@ namespace QuantumDynamics { use qs = Qubit[N1 * N2]; let qubitArray = Chunks(N2, qs); // qubits are re-arranged to be in an N1 x N2 array - let p = 1.0 / (4.0 - 4.0 ^ (1.0 / 3.0)); + let p = 1.0 / (4.0 - 4.0^(1.0 / 3.0)); let t = Ceiling(totTime / dt); let seqLen = 10 * t + 1; diff --git a/samples/estimation/EkeraHastadFactoring.qs b/samples/estimation/EkeraHastadFactoring.qs index 1e39e66fca..248c7529f8 100644 --- a/samples/estimation/EkeraHastadFactoring.qs +++ b/samples/estimation/EkeraHastadFactoring.qs @@ -184,11 +184,11 @@ namespace Microsoft.Quantum.Applications.Cryptography { } internal function LookupData(factor : BigInt, expLength : Int, mulLength : Int, base : BigInt, mod : BigInt, sign : Int, numBits : Int) : Bool[][] { - mutable data = [[false, size = numBits], size = 2 ^ (expLength + mulLength)]; - for b in 0..2 ^ mulLength - 1 { - for a in 0..2 ^ expLength - 1 { - let idx = b * 2 ^ expLength + a; - let value = ModulusL(factor * IntAsBigInt(b) * IntAsBigInt(sign) * (base ^ a), mod); + mutable data = [[false, size = numBits], size = 2^(expLength + mulLength)]; + for b in 0..2^mulLength - 1 { + for a in 0..2^expLength - 1 { + let idx = b * 2^expLength + a; + let value = ModulusL(factor * IntAsBigInt(b) * IntAsBigInt(sign) * (base^a), mod); set data w/= idx <- BigIntAsBoolArray(value, numBits); } } diff --git a/samples/estimation/ShorRE.qs b/samples/estimation/ShorRE.qs index f243a484f5..3bb148a160 100644 --- a/samples/estimation/ShorRE.qs +++ b/samples/estimation/ShorRE.qs @@ -23,7 +23,7 @@ namespace Shors { // When chooseing parameters for `EstimateFrequency`, make sure that // generator and modules are not co-prime - let _ = EstimateFrequency(11, 2 ^ bitsize - 1, bitsize); + let _ = EstimateFrequency(11, 2^bitsize - 1, bitsize); } /// # Summary diff --git a/samples/estimation/df-chemistry/src/df_chemistry.qs b/samples/estimation/df-chemistry/src/df_chemistry.qs index ffbd5c04de..69146b912f 100644 --- a/samples/estimation/df-chemistry/src/df_chemistry.qs +++ b/samples/estimation/df-chemistry/src/df_chemistry.qs @@ -102,7 +102,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { let RotationAngleBitPrecision = Ceiling(1.152 + Lg(Sqrt((IntAsDouble((problem::NumOrbitals - 1) * 8) * PI() * norm) / parameters::StandardDeviation)) + 0.5 * Lg(1.0 / barEpsilon)); let StatePreparationBitPrecision = Ceiling(Lg(1.0 / epsilon) + 2.5); - let TargetError = 2.0 ^ IntAsDouble(1 - StatePreparationBitPrecision); + let TargetError = 2.0^IntAsDouble(1 - StatePreparationBitPrecision); DoubleFactorizedChemistryConstants( RotationAngleBitPrecision, @@ -328,7 +328,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { mutable bitstrings = []; let tau = 2.0 * PI(); - let preFactor = 2.0 ^ IntAsDouble(precision); + let preFactor = 2.0^IntAsDouble(precision); for eigenVector in eigenVectors { // Computes rotation angles for Majorana operator ($\vec u$ in p. 52, eq. 55) diff --git a/samples/estimation/df-chemistry/src/prepare.qs b/samples/estimation/df-chemistry/src/prepare.qs index 8349d745fb..7bdc9a7d4e 100644 --- a/samples/estimation/df-chemistry/src/prepare.qs +++ b/samples/estimation/df-chemistry/src/prepare.qs @@ -22,7 +22,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { operation PrepareUniformSuperposition(numStates : Int, qs : Qubit[]) : Unit is Adj + Ctl { Fact(numStates >= 1, "numStates must be positive"); - Fact(numStates <= 2 ^ Length(qs), $"numStates must be smaller or equal to {2 ^ Length(qs)}"); + Fact(numStates <= 2^Length(qs), $"numStates must be smaller or equal to {2^Length(qs)}"); let qsAdjusted = qs[...Ceiling(Lg(IntAsDouble(numStates))) - 1]; @@ -119,7 +119,7 @@ namespace Microsoft.Quantum.Applications.Chemistry { Fact(nCoefficients > 1, "Cannot prepare state with less than 2 coefficients."); Fact(oneNorm != 0.0, "State must have at least one coefficient > 0"); - let barHeight = 2 ^ bitsPrecision - 1; + let barHeight = 2^bitsPrecision - 1; mutable altIndex = SequenceI(0, nCoefficients - 1); mutable keepCoeff = Mapped( diff --git a/samples/language/ArithmeticOperators.qs b/samples/language/ArithmeticOperators.qs index 6ca4977ba3..999255de42 100644 --- a/samples/language/ArithmeticOperators.qs +++ b/samples/language/ArithmeticOperators.qs @@ -67,21 +67,21 @@ namespace MyQuantumApp { // checked at runtime. // The integer value `81`. - let integer = 3 ^ 4; + let integer = 3^4; // The integer value `-81`. - let integer = -3 ^ 4; + let integer = -3^4; // The double value `256.0`. - let double = 16.0 ^ 2.0; + let double = 16.0^2.0; // The double value `-256.0`. - let double = -16.0 ^ 2.0; + let double = -16.0^2.0; // The double value `4.0`. - let double = 16.0 ^ 0.5; + let double = 16.0^0.5; // The double value `0.25`. - let double = 16.0 ^ -0.5; + let double = 16.0^ -0.5; } } diff --git a/samples/language/BigInt.qs b/samples/language/BigInt.qs index 210e1e2a1e..09d8e7047a 100644 --- a/samples/language/BigInt.qs +++ b/samples/language/BigInt.qs @@ -20,7 +20,7 @@ namespace MyQuantumApp { let foo = foo + 1L; let foo = foo % 2L; // `BigInt`s being raised to an exponent take an `Int` as the exponent. - let foo = foo ^ 2; + let foo = foo^2; return foo; } } diff --git a/samples/language/Int.qs b/samples/language/Int.qs index 730339783d..481838d7d9 100644 --- a/samples/language/Int.qs +++ b/samples/language/Int.qs @@ -18,7 +18,7 @@ namespace MyQuantumApp { // multiplication (*), division (/), modulo (%), and exponentiation (^). let foo = foo + 1; let foo = foo % 2; - let foo = foo ^ 2; + let foo = foo^2; return foo; } } \ No newline at end of file diff --git a/samples/language/Range.qs b/samples/language/Range.qs index 086b1d646a..edf568f9bb 100644 --- a/samples/language/Range.qs +++ b/samples/language/Range.qs @@ -38,7 +38,7 @@ namespace MyQuantumApp { // The array [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. mutable array = []; for i in 0..10 { - set array += [i ^ 2]; + set array += [i^2]; } // Ranges can be used to create array slices. From 92cb5cced9c57ee7fa0ad24c589615d97cc05b37 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Tue, 26 Mar 2024 10:16:09 -0700 Subject: [PATCH 12/13] remove format script --- format_all.ps1 | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 format_all.ps1 diff --git a/format_all.ps1 b/format_all.ps1 deleted file mode 100644 index b9077ab541..0000000000 --- a/format_all.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -Get-ChildItem -Recurse .\samples -Filter *.qs | -ForEach-Object { - #cargo run --bin qsc_formatter $_.FullName - .\target\release\qsc_formatter.exe $_.FullName -} - -Get-ChildItem -Recurse .\library -Filter *.qs | -ForEach-Object { - #cargo run --bin qsc_formatter $_.FullName - .\target\release\qsc_formatter.exe $_.FullName -} - From 7f7046a34fb1ca4b669c77944d77ac973a8a5181 Mon Sep 17 00:00:00 2001 From: Scott Carda Date: Tue, 26 Mar 2024 10:35:56 -0700 Subject: [PATCH 13/13] forgot to update a test --- compiler/qsc_formatter/src/formatter/tests.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/qsc_formatter/src/formatter/tests.rs b/compiler/qsc_formatter/src/formatter/tests.rs index e08818c04d..4afdcb1f7e 100644 --- a/compiler/qsc_formatter/src/formatter/tests.rs +++ b/compiler/qsc_formatter/src/formatter/tests.rs @@ -144,14 +144,12 @@ fn singe_space_around_arithmetic_bin_ops() { 1 * 2; 4 /2; 3% 2; - 2 ^ 3; "}, &expect![[r#" 1 + 2; 1 * 2; 4 / 2; 3 % 2; - 2 ^ 3; "#]], ); }