!ZJ      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                                                                        !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                           !!!!!!!!!!!!!!!!!!!!!!!!!!""""" " " " " """"""############# #!#"###$#%#&#'#(#)#*#+#,#-#.#/#0#1$2$3$4$5$6$7$8$9$:$;$<$=$>$?%@%A%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z%[%\%]%^%_%`%a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&''''((((((((((((((((((((((((((())))))))))))))))****************************************************** * + + + +++++++++++++++++++ +!+"+#+$+%+&+'+(+),*,+,,,-,.,/,0,1,2,3,4,5,6,7,8,9,:,;,<,=,>,?,@,A,B,C,D,E,F,G,H,I,2None =>?@ACHV XThe  type class is used to implement functions that have a variable number of arguments. It provides a family of type isomorphisms fun "E args -> res,where Gfun = a1 -> a2 -> ... -> an -> res, args = (a1, (a2, (..., (an, ()))))."Multiple curry: map a function (a [sub 1], (a[sub 2], ( &, ())) ! b to its curried form a [sub 1] ! a[sub 2] ! & ! b."Multiple uncurry: map a function a [sub 1] ! a[sub 2] ! & ! b to its uncurried form (a [sub 1], (a[sub 2], ( &, ())) ! b.%Often a low-level function, such as - or ., throws an error because of a failure of some low-level condition, such as "list too short". To produce error messages that are meaningful to user-level code, these functions do not have a hard-coded error message. Instead, they input a stub error message.FA meaningful error message typically consists of at least three parts:^the name of the user-level function where the error occurred, for example: "reverse_generic";swhat the function was doing when the error occurred, for example: "operation not permitted in reversible circuit";Ka specific low-level reason for the error, for example: "dynamic lifting".|Thus, a meaningful error message may be: "reverse_generic: operation not permitted in reversible circuit: dynamic lifting".The problem is that the three pieces of information are not usually present in the same place. The user-level function is often a wrapper function that performs several different mid-level operations (e.g., transforming, reversing). The mid-level function knows what operation was being performed when the error occurred, but often calls a lower-level function to do the actual work (e.g., encapsulating).Therefore, a stub error message is a function that inputs some lower-level reason for a failure (example: "list too short") and translates this into a higher-level error message (example: "qterm: shape of parameter does not data: list too short").Sometimes, the stub error message may also ignore the low-level message and completely replace it by a higher-level one. For example, a function that implements integers as bit lists may wish to report a problem with integers, rather than a problem with the underlying lists. The type  a b witnesses the fact that a and bL are the same type. In other words, this type is non-empty if and only if a = bh. This property is not guaranteed by the type system, but by the API, via the fact that the operators U, V, and W are the only exposed constructors for this type. The implementation of this type is deliberately hidden, as this is the only way to guarantee its defining property.Identity types are useful in certain situations. For example, they can be used to define a data type which is polymorphic in some type variable xC, and which has certain constructors that are only available when x7 is a particular type. For example, in the declaration Gdata ExampleType x = Constructor1 x | Constructor2 x (Identity x Bool), Constructor1 is available for all x, but  Constructor2 is only available when x = J.The identity monad. Using m = 2 gives useful special cases of monadic functions. kA string buffer holds a string that is optimized for fast concatenation. Note that this is an instance of   , and hence   operations (in particular N]) can be applied to string buffers. The following functions are synonyms of the respective  - functions, and are provided for convenience. {The type of bidirectional lists. This is similar to [a], but optimized for fast concatenation and appending on both sides. -The type of bit vectors. True = 1, False = 0.A  is just like an KE, except that it supports some additional efficient operations: to find the smallest unused key, to find the set of all keys ever used in the past, and to reserve a set of keys so that they will not be allocated. Moreover, it keeps track of the highest key ever used (whether or not it is still used in the current map).3Apply a function to a specified position in a list.7Overwrite an element at a specified position in a list.$Check whether a list has duplicates. string character replacement$: Replace the first occurrence of  character in string by  replacement.$Insert the elements of a list in an L (cf. M).%Insert the given key-value pair in a N`, but only if the given key is not already present. If the key is present, keep the old value.O Take two Ks m [sub 1] and m[sub 2], and form a new K whose domain is that of m[sub 2], and whose value at k is the pair (m [sub 1] ! k, m [sub 2] ! k$). It is an error if the domain of m)[sub 2] is not a subset of the domain of m[sub 1]. Take two K's with the same domain, and form a new KY whose values are pairs. It is an error if the two inputs don't have identical domains.Like E, but also takes an error message to use in case of domain mismatch.%Map a function over all values in an K.Monadic version of (. Map a function over all values in an K.Delete a key from the .Delete a list of keys from a .#Insert a new key-value pair in the . (Insert a list of key-value pairs in the ."Look up the value at a key in the  . Return P if not found.&Check whether the given key is in the . The empty . !Return the first free key in the %, but without actually using it yet.!Return the next k unused keys in the ', but without actually using them yet." Convert a  to an K.#*Return the smallest key never used in the .Q,Return the set of all keys ever used in the .$ A wire is dirty& if it is touched but currently free. RReserve a key in the . If the key is not free, do nothing. The key must have been used before; for example, this is the case if it was returned by $.%Reserve a set of keys in the . For any keys that are not free, do nothing. All keys must have been used before; for example, this is the case if they were returned by $.SUnreserve a key in the . If the key is currently used, do nothing. The key must have been reserved before, and (therefore) must have been used before.& Unreserve a list of keys in the . If any key is currently used, do nothing. All keys must have been reserved before, and (therefore) must have been used before.'Make an exact copy of the , except that the set of touched wires is initially set to the set of used wires. In other words, we mark all free and reserved wires as untouched.(Like *H, but also pass a loop counter to the function being iterated. Example: )loop_with_index 3 x f = f 2 (f 1 (f 0 x)))Monadic version of (. Thus,  loop_with_indexM 3 x0 fwill do the following: ?do x1 <- f 0 x0 x2 <- f 1 x1 x3 <- f 2 x2 return x3*Iterate a function n times. Example: loop 3 x f = f (f (f x))+Monadic version of *.,A right-to-left version of TT: Evaluate each action in the sequence from right to left, and collect the results.-Same as ,, but ignore the result..A "strict" version of UC, i.e., raises an error when the lists are not of the same length./Like .F, but also takes an explicit error message to use in case of failure.0A "right strict" version of UK, i.e., raises an error when the left list is shorter than the right one. 1 A version of 0F that also takes an explicit error message to use in case of failure.2A "strict" version of VC, i.e., raises an error when the lists are not of the same length.3A "right strict" version of VJ, i.e., raises an error when the right list is shorter than the left one.4A right-to-left version of /0r, which is also "right strict", i.e., raises an error when the right list is shorter than the left one. Example: -zipRightWithM f [a,b] [x,y] = [f a x, f b y],computed right-to-left.5Same as 4, but ignore the result.6FFold over two lists with state, and do it right-to-left. For example, 'foldRightPairM (w0, [1,2,3], [a,b,c]) fwill do the following: Mdo w1 <- f (w0, 3, c) w2 <- f (w1, 2, b) w3 <- f (w2, 1, a) return w37Like 6, but ignore the final result.83Combine right-to-left zipping and folding. Example: fold_right_zip f (w0, [a,b,c], [x,y,z]) = (w3, [a',b',c']) where f (w0,c,z) = (w1,c') f (w1,b,y) = (w2,b') f (w2,a,x) = (w3,a')9Monadic version of 8.:A "for" loop. Counts from a to b in increments of s.Standard notation:  6for i = a to b by s do commands end forOur notation: &for a b s $ \i -> do commands endfor;rMark the end of a "for"-loop. This command actually does nothing, but can be used to make the loop look prettier.<FIterate a parameter over a list of values. It can be used as follows: Rforeach [1,2,3,4] $ \n -> do <<<loop body depending on the parameter n>>> endfor.The loop body will get executed once for each n " {1,2,3,4}.=+Every monad is a functor. Input a function f : a ! b and output m f : m a ! m b.>?Remove an outer application of a monad from a monadic function.?Take two functions f : a ! b and g : c ! d, and return f " g : a " c ! c " d.@Monadic version of ?.ATake two functions f : a ! b and g : c ! d, and return f g : a c ! c d.BMonadic version of A.CA version of the W function that returns an X.DConvert an integer to a bit vector. The first argument is the length in bits, and the second argument the integer to be converted. The conversion is big-headian (or equivalently, little-tailian), i.e., the head of the list holds the integer's most significant digit.EConvert an integer to a bit vector. The first argument is the length in bits, and the second argument the integer to be converted. The conversion is little-headian (or equivalently, big-tailian), i.e., the head of the list holds the integer's least significant digit.FConvert a bit vector to an integer. The conversion is big-headian (or equivalently, little-tailian), i.e., the head of the list holds the integer's most significant digit. This function is unsigned, i.e., the integer returned is "e 0.G+Convert a bit vector to an integer, signed.H#Exclusive or operation on booleans.I&Exclusive or operation on bit vectors.J+A general list-to-string function. Example: ;string_of_list "{" ", " "}" "{}" show [1,2,3] = "{1, 2, 3}"KK b s: if b = Y , return s;, else the empty string. This function is for convenience.LConvert a List to a  .M Convert a   to a List.NFast concatenation of  s or string buffers.O The empty  .PConcatenate a list of  s.Q$Convert a string to a string buffer.R$Convert a string buffer to a string.SThe empty string buffer.T%Concatenate a list of string buffers.UWitness the fact that a=a.VWitness the fact that a=b implies b=a.WWitness the fact that a=b and b=c implies a=c.XThe identity function Z : a ! b, provided that a and b are the same type.V  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXV !"#$%&'*(8./0123+)45967,-:;<=>?@ABC DEFGHIJK LMNOP QRST UVWXNone>HVa A simplified Circ monad.cqA data structure to represent a "circuit under construction". This holds the data needed for circuit generation.eThe circuit so far.fThe next fresh wire.gThe type of gates.h No operation.iInitialization.jMulti-controlled not.k9The type of wires. A wire is determined by an integer ID.l*Get the wire acted upon by a gate, if any.m!Get the list of controls, if any.nEvaluate a circuit on a given initial state, and return the final state. A state is represented as a map from wires to booleans.oThe empty state.pRetrieve the next fresh wire.q&Increment the value of the fresh wire.rAdd a new gate to the circuit.s!Get the circuit out of the monad.tInitialize a new wire.u Add a multi-controlled not gate.v*Pretty-print a circuit as a list of gates.wPrint a gate as Quipper code.abcdfegjihklmnopqrstuvwkgjihlmncdfeoabpqrstuvwUnsafe =>?HV2U~+The type of algebraic boolean expressions. We represent boolean expressions using "and" and "xor" as the primitive connectives. Equivalently, we can regard booleans as the elements of the two-element field F6[sub 2], with operations "*" (times) and "+" (plus). An algebraic expression x1*x2*x3 + y1*y2*y3 + z1*z2 is encoded as {{x1,x2,x3},{y1,y2,y3},{z1,z2}}.In particular, {} == False == 0 and {{}} == True == 1.+Build the characteristic function of a set.-Get the set of elements whose images are odd.Split a list in the middle.Turn an Exp into a list of lists.Turn a list of lists into an Exp."The conjunction of two expression.The xor of two expressions.The expression "False".The expression "True".The negation of an expression.The expression x[sub n].(Get the variables used in an expression.@Evaluate the expression with respect to the given valuation. A  valuationD is a map from variables to booleans, i.e., a row in a truth table."Construct the list of all 2[super n"] valuations for a given list of n variables.Build the truth table for the given expression, on the given list of variables. The truth table is returned as a list of booleans in lexicographic order of valuations. For example, if 2 1 2 | exp F F | f1 F T | f2 T F | f3 T T | f4#then the output of the function is  [f1,f2,f3,f4].eReturn an expression realizing the given truth table. Uses variables starting with the given number.~~None >HLVzlI!The state monad corresponding to .|The state of the automaton. This contains in particular the current state, the past and future gates, and a fresh variable. For use with .All the wires in the circuit.1ID of the first gate in the future (starts at 1).Location of the controls.Location of the NOT gates.Gates left to explore.Gates already explored.sAlgebraic state of the wires. Also contains the size of the expression, so we don't have to recompute it each time.The next fresh wire.The output wires.Size of the circuit.A map from wires to pairs of s. The left member gives the ID of the first gate using the wire, and the right member gives the ID of the last gate using the wire.A set of gate IDs.The type of gate IDs.sInternal definition of a trace, for debugging purposes. This is a no-op, but can be replaced to turn on debugging.UChange a wire ID in a gate. The first two arguments are the old and the new wire ID.NFlip the control on the given wire (from positive to negative or vice versa).:Change a wire ID in a gate and flip the potential control.SSuppress gates acting on garbage wires, i.e., wires that are not in the input set. Like <, but packaged in a manner that is friendly for composition.-Get the set of all wires used by the circuit.0Get the set of wires initialized by the circuit.MGet the set of input wires, i.e., the ones that are used but not initialized.Compress the wire numbering.%Get the minimum of a set of gate IDs.%Get the maximum of a set of gate IDs.-Get the pair corresponding to the given wire.0Get the first gate using the wire in the future.?Get the last gate using the wire in the past. Return 0 if none. ws g g' w: Look for the next gate in ws corresponding to wire w, starting from g . Return g ' if none.=For each wire, find the set of gates placing a control on it.;For each wire, find the set of gates acting on it with NOT..Calculate the size of an algebraic expression.Given a list of sets of expressions, form the conjunction of every possible choice of one expression from each set. For example. cexp_list_and [{a,b}, {c,d}, {e,f}] = [a"'c"'e, a"'c"'f, a"'d"'e, a"'d"'f, b"'c"'e, b"'c"'f, b"'d"'e, b"'d"'f].+Evaluate a control with respect to a state.(Evaluate a gate with respect to a state.0The initial state for a given set of parameters. Construct an  out of an .Retrieve the state.Set the state.Create a fresh variable1Pull a new gate to be analyzed out of the future.Modify the future gates.JUpdate the future using the given parameter function. Return two sets of Xs that got modified: the first set concerns the controls, the second set the NOT gates.Store a gate in the past. Increase the  '@gateId@' (i.e., go forward).Get the set of all wires.Set the set of all wires.(Remove a gate from the set of all wires.5Get the algebraic representation of the set of wires.7Set the algebraic representation of the state of wires.3Update the database recording the controlled wires.,Update the database recording the NOT gates. Update the list of output wires.+Add a gate ID to the list of gates to skip.%Send a gate to the end of the future.0Place a gate at the given gate ID in the future.pairEqualExp m1 m2 ws#: returns a list of pairs of wires (x,y) such that m2 x = m1 x = m1 y.\From a set of expressions (annotated with sizes), prune the ones whose size is larger than n.DPerform a set of filters acting on one gate at a time, looking for:gates having no effect;8orphan NOT-gates (i.e. NOT gates negating an out-wire) ;/simple copy-cats (both positive and negative) ;hidden copy-cats.Return [) when the end of the circuit is reached, Y otherwise. {Shuffle the circuit by sending the CNOT gates as far as possible (i.e., until they hit a control, or to the end). Return [) when the end of the circuit is reached, Y otherwise. A more elementary version of _: shuffle the circuit by sending to the end all the NOT gates that can be sent there. Return [* when the end of the circuit is reached, Y otherwise.Run the monad until [ occurs. Strip the h gates from a list of gates.Wrapper around .Wrapper around .Wrapper around .sAuxiliary function. Simultaneously compute the maximum of the lengths of two lists, and their point-wise equality.1Get the list of initialized wires from a circuit.Do several passes of  until it reaches a fixed point.Do several passed of  followed with ! until it reaches a fixed point.KKNone 2>EHVX@P-The type of dynamic boxed circuits. The type  a( is the appropriate generalization of (, ao), in a setting that is dynamic rather than static (i.e., with dynamic lifting or "interactive measurement").The c monad describes a standard read-write computation, here specialized to the case where writes are s, prompts are 12s, and reads are J7s. Thus, a read-write computation can do three things:*terminate with a result. This is the case .write a single  and continue. This is the case .issue a prompt, which is a , then read a J#, then continue. This is the case .An ordered boxed circuit is a T together with an ordering on the input and output endpoints, or equivalently, an  together with a namespace.nA boxed circuit is a distinguished simple circuit (analogous to a main  function) together with a namespace. A name space is a map from names to subroutine bindings. These subroutines can reference each other; it is the programmer s responsibility to ensure there is no circular dependency, and no clash of names.A typed subroutine consists of:Ma low-level circuit, ordered to allow binding of incoming and outgoing wires;functions for structuring/destructuring the inputs and outputs to and from lists of wires (these functions being dynamically typed, since the input/output type may vary between subroutines);a 0, recording whether the circuit is controllable.SOne often wants to consider the inputs and outputs of a circuit as more structuredtyped than just lists of bits{qubits; for instance, a list of six qubits could be structured as a pair of triples, or a triple of pairs, or a six-bit %3.While for the most part this typing information is not included in low-level circuits, we need to consider it in hierarchical circuits, so that the information stored in a subroutine is sufficient to call the subroutine in a typed context.Specifically, the extra information needed consists of functions to destructure the input/output data as a list of typed wires, and restructure such a list of wires into a piece of data of the appropriate type. An ordered circuit is a j together with an ordering on (usually all, but potentially a subset of) the input and output endpoints._This extra information is required when a circuit is used within a larger circuit (e.g. via a p gate), to identify which wires of the sub-circuit should be bound to which wires of the surrounding circuit.A completed circuit  (a1,gs,a2,n) has an input arity a1, a list of gates gs, and an output arity a2. We also record n, the total number of wires used by the circuit. Because wires are allocated consecutively, this means that the wire id's used are [0..n-1].Recall that an ~ is a set of typed wires, and it determines the external interfaces at which circuits and gates can be connected. The type * stores the same information as the type z, but in a format that is more optimized for efficient updating. Additionally, it also stores the set of wires ever used.&The low-level representation of gates.!A named reversible quantum gate:  ^(m+n) -> ^(m+n). The second [] argument should be "generalized controls", i.e. wires not modified by the gate. The gate type is uniquely determined by: the name, the number of inputs, and the number of generalized controls. Gates that differ in one of these respects should be regarded as different gates.A named reversible quantum gate that also depends on a real parameter. This is typically used for phase and rotation gates. The gate name can contain '%' as a place holder for the parameter, e.g.,  "exp(-i%Z)"&. The remaining arguments are as for .Global phase gate: '1' -> '1';. The list of wires is just a hint for graphical rendering.Classical not:  -> .Generic classical gate 1 -> .Uncompute classical gate  -> 1T, asserting that the classical bit is in the state specified by the corresponding .Classical swap gate:  *  ->  * .Initialization:  -> . Measurement  ->  with an assertion that the qubit is already in a computational basis state. This kind of measurement loses no information, and is formally the inverse of .Initialization: J -> . Initialization: J -> . Termination of a A wire with assertion that the qubit is in the specified state:  * J -> 1.Termination of a ? wire with assertion that the bit is in the specified state:  * J -> 1. Measurement:  -> .Termination of a  wire without assertion:  -> 1Termination of a  wire without assertion:  -> 1Termination of a  wire, with a comment indicating what the observed state of that wire was. This is typically inserted in a circuit after a dynamic lifting is performed. Unlike u, this is in no way an assertion, but simply a record of observed behavior during a particular run of the algorithm.vReference to a subroutine, assumed to be bound to another circuit. Arbitrary input and output arities. The domain of a1 must include the range of ws1, and similarly for a2 and ws2.^A comment. Does nothing, but can be useful for marking a location or some wires in a circuit.A flag that indicates how many times a particular subroutine should be repeated. If non-zero, it implies some constraints on the type of the subroutine.An identifier for a subroutine. A boxed subroutine is currently identified by a pair of: the user-defined name of the subroutine; and a value uniquely identifying the type and shape of the argument.OFor now, we represent the shape as a string, because this gives an easy total \ instance, needed for Data.Map. However, in principle, one could also use a pair of a type representation and a shape term. The implementation of this may change later.A flag, to specify if the corresponding subroutine can be controlled. Either no control allowed, or all controls, or only classical. A flag that, if Y, indicates that the gate is controllable, but any further controls on the gate should be ignored. This is used, e.g., for circuits consisting of a basis change, some operation, and the inverse basis change. When controlling such a circuit, it is sufficient to control the middle operation, so the gates belonging to the basis change and its inverse will have the NoControlFlag set. A flag that, if Y&, indicates that the gate is inverted.yA time step is a small floating point number used as a parameter to certain gates, such as rotation gates or the [exp "iZt] gate.+A list of controlled wires, possibly empty.A signed item of type a.  x Y" represents a positive item, and  x [ represents a negative item.When used with wires in a circuit, a positive sign is used to represent a positive control, i.e., a filled dot, and a negative sign is used to represent a negative control, i.e., an empty dot.]An arity, also known as a typing context, is a map from a finite set of wires to wire types.1Wire type. A wire is either quantum or classical.Quantum wire. Classical wire.|Wire identifier. Wires are currently identified by an integer, but the users of this interface should be oblivious to this.-Extract the underlying item of a signed item.#Extract the sign of a signed item: Y is positive, and [ is negative.Compute the incoming and outgoing wires of a given gate (excluding controls, comments, and anchors). This essentially encodes the type information of the basic gates. If a wire is used multiple times as an input or output, then F also returns it multiple times; this enables run-time type checking. Note that  returns the logicalm wires, and therefore excludes things like labels, comments, and graphical anchors. This is in contrast to , which returns the  syntactic set of wires used by the gate.NReturn the controls of a gate (or an empty list if the gate has no controls). Return the   of a gate, or [ if it doesn't have one.Apply the given   to the given ). This means, if the first parameter is Y, set the gate's  B, otherwise do nothing. Throw an error if attempting to set the  ( on a gate that can't support this flag.=Reverse a gate. Throw an error if the gate is not reversible.3Return the set of wires used by a list of controls.SReturn the set of wires used by a gate (including controls, labels, and anchors). Unlike , the function  is used for printing, and therefore returns all wires that are syntactically used by the gate, irrespective of whether they have a logical meaning. Like  , except return a list of wires.!Check whether the given gate is well-formed and can be legally applied in the context of the given arity. If successful, return the updated arity resulting from the gate application. If unsuccessful, raise an error. Properties checked are:>that each gate has non-overlapping inputs, including controls;?that each gate has non-overlapping outputs, including controls;]that the inputs of the gate (including controls) are actually present in the current arity; Tthat the types of the inputs (excluding controls) match those of the current arity;wthat the outputs of the gate (excluding controls) don't conflict with any wires already existing in the current arity."Like #, but without type checking. This is potentially faster, but should only used in applications that have already been thoroughly tested or type-checked.#For now, we disable run-time type checking, because we have not yet implemented run-time types properly. Therefore, we define # to be a synonym for ".$Return an empty arity.%*Return a wire unused in the current arity.&Return the next k# wires unused in the current arity.'ZAdd a new typed wire to the current arity. This returns a new wire and the updated arity.(/Convert an extended arity to an ordinary arity.)8Return the smallest wire id nowhere used in the circuit.*-Return the set of all the wires in a circuit.+Reverse a gate list.,CReverse a circuit. Throw an error if the circuit is not reversible.-Set the   on all gates of a circuit.. Reverse an 2. Throw an error if the circuit is not reversible./ The trivial  on ([],).0Use a M to destructure a piece of (suitably typed) data into a list of typed wires.1Use a h to structure a list of typed wires (of the appropriate length/arity) into a piece of structured data.2Extract just the  from a .3The empty namespace.4<A function to display the names of all the subroutines in a .5 Construct an  from a 4 and an ordering on the input and output endpoints.6DReverse a simple boxed circuit, or throw an error if not reversible.7uTransforms a read-write computation into one that behaves identically, but also returns the list of gates generated.This is used as a building block, for example to allow a read-write computation to be run in a simulator while simultaneously using a static backend to print the list of generated gates.8!Extract the contents of a static  computation. A 5 computation is said to be static if it contains no > instructions, or in other words, no dynamic lifting. If an J instruction is encountered, issue an error message using the given stub.9Turn a static read-write computation into a list of gates, while also updating a namespace. "Static" means that the computation may not contain any ] operations. If it does, the message "dynamic lifting" is passed to the given error handler.6Important usage note: This function returns a triple (gates, ns, xg). The list of gates is generated lazily, and can be consumed one gate at a time. However, the values ns and xw are only computed at the end of the computation. Any function using them should not apply a strict pattern match to ns or xt, or else the whole list of gates will be generated in memory. For example, the following will blow up the memory: :(gates, ns, (a, n, x)) = gatelist_of_readwrite errmsg comp,whereas the following will work as intended: ;(gates, ns, ~(a, n, x)) = gatelist_of_readwrite errmsg comp:"Convert a dynamic boxed circuit to a static boxed circuit. The dynamic boxed circuit may not contain any dynamic liftings, since these cannot be performed in a static setting. In case any output liftings are encountered, try to issue a meaningful error via the given stub error message.;XConvert a boxed circuit to a dynamic boxed circuit. The latter, of course, contains no  instructions.]      !"#$%&'()*+,-./0123456789:;]      !"#$%&'()*+,-./0123456789:;None 2>@AHSVX1LTo transform Dynamic Boxed circuits, we require a Transformer to define the behavior on static gates, but we also require functions for what to do when a subroutine is defined, and for when a dynamic_lift operation occurs. This is all wrapped in the DynamicTransformer data type.QA "binding transformer" is a function from bindings to bindings. The semantics of any gate or circuit is ultimately a binding transformer, for some types a, b and some monad m`. We introduce an abbreviation for this type primarily as a convenience for the definition of }F, but also because this type can be completely hidden from user code.RCA circuit transformer is specified by defining a function of type R m a b#. This involves specifying a monad m, semantic domains a ='Qubit' and b:='Bit', and a semantic function for each gate, like this: my_transformer :: Transformer m a b my_transformer (T_Gate1 <parameters> f) = f $ <semantic function for gate 1> my_transformer (T_Gate2 <parameters> f) = f $ <semantic function for gate 2> my_transformer (T_Gate3 <parameters> f) = f $ <semantic function for gate 3> ...S The type Sj is used to define case distinctions over gates in the definition of transformers. For each kind of gate X), it contains a constructor of the form (T_X f). Here, X identifies the gate, and f8 is a higher-order function to pass the translation of X to.gdA list of signed values of type 'B_Endpoint'. This type is an abbreviation defined for convenience.hAA binding is a map from a set of wires to the disjoint union of a and b.iAn endpoint is either a qubit or a bitP. In a transformer, we have 'B_Endpoint Qubit Bit' = 'Qubit' + 'Bit'. The type i a b is the same as ] a b*, but we use more suggestive field names.l.Return the list of bound wires from a binding.mThe empty binding.n9Bind a wire to a value, and add it to the given bindings.o?Bind a qubit wire to a value, and add it to the given bindings.p=Bind a bit wire to a value, and add it to the given bindings.q6Retrieve the value of a wire from the given bindings. rvRetrieve the value of a qubit wire from the given bindings. Throws an error if the wire was bound to a classical bit.slRetrieve the value of a bit wire from the given bindings. Throws an error if the wire was bound to a qubit.t&Delete a wire from the given bindings.uLike nY, except bind a list of wires to a list of values. The lists must be of the same length.vLike o_, except bind a list of qubit wires to a list of values. The lists must be of the same length.wLike p], except bind a list of bit wires to a list of values. The lists must be of the same length.xLike q#, except retrieve a list of values.yLike r#, except retrieve a list of values.zLike s#, except retrieve a list of values.{Given a list of signed wires (controls), and a list of signed values, make a bindings from the wires to the values. Ignore the signs.|Like q<, but retrieve binding for all wires in a list of controls.}Turn a  into a SX. This is the function that actually handles the explicit bindings/unbindings required for the inputs and outputs of each gate. Effectively it gives a way, for each gate, of turning a semantic function into a binding transformer. Additionally, this function is passed a Namespace, so that the semantic function for T_Subroutine can use it.~Apply a R '-' to a  C%, and output the semantic function 'C' :: bindings -> bindings.Like ~, but for boxed circuits.The handling of subroutines will depend on the transformer. For "gate transformation" types of applications, one typically would like to leave the boxed structure intact. For "simulation" types of applications, one would generally recurse through the boxed structure.The difference is specified in the definition of the transformer within the semantic function of the Subroutine gate, whether to create another boxed gate or open the box.Same as , but specialized to when m is the identity operation.Like !, but for dynamic-boxed circuits."Write" operations can be thought of as gates, and so they are passed to the given transformer. The handling of "Read" operations is taken care of by the "lifting_function" of the DynamicTransformer. "Subroutine" operations call the O$ function of the DynamicTransformer.6LMPONQRSfedcba`_^]\[ZYXWVUTghikjlmnopqrstuvwxyz{|}~6ikjhlmnopqrstuvwxyzg{|Sfedcba`_^]\[ZYXWVUTRQ}~LMPON None>HVyExit with an error message after a command line error. This also outputs information on where to find command line help.(Parse a string to an integer, or return P on failure.0Parse a string to a list of integers, or return P on failure.Parse a string to a ^ , or return P on failure.In an association list, find the key that best matches the given string. If one key matches exactly, return the corresponding key-value pair. Otherwise, return a list of all key-value pairs whose key have the given string as a prefix. This list could be of length 0 (no match), 1 (unique match), or greater (ambiguous key). Note: the keys in the association list must be lower case. The input string is converted to lower case as well, resulting in case-insensitive matching.Pretty-print a list of possible values for a parameter. The first argument is the name of the parameter, and the second argument is its enumeration. None>HVSequentially try one or more IO computations, until one of them completes without an IO error. If all of them fail, re-throw the error from the last one. zoom pdffile(: Call a system-specific PDF viewer on pdffile file. The zoomE argument is out of 100 and may or may not be ignored by the viewer.Like , but specialized to Windows.Like , but specialized to Mac OS.Like , but specialized to Linux. None &'>HSVX3TA container type to hold a source of randomness. This can hold any instance of the _ class. None>HVp<A 44-matrix is represented as a 22-matrix of 22-matrices.$Represent a 22-matrix as a 4-tuple.WIn general, Pauli operators can commute, or anti-commute, so we need to add signs or i.4The generators of a stabilizer group require a sign.[The Pauli operators can be used to generate a stabilizer group for the Clifford operators."Returns a boolean as to whether a  is negative (i.e.. ).Returns the negation of a .Two signs can be multiplied.Two s can be multiplied. Extract a  embedded in a 8, or throw an error if the argument is not an embedded .FThe Levi-Civita symbol, for the permutations of three Pauli operators.,The Kronecker delta for two Pauli operators.The combination of the commutation and anti-commutation operators can be used to essentially multiply an (ordered) pair of Pauli operators.(Give the matrix for each Pauli operator.Scale a 2-by-2 matrix.PIf a matrix is Pauli, then return the Pauli operator, otherwise throw an error.'Matrix multiplication for 22-matrices.5Compute the transpose of a 22 complex-valued matrix.Return the matrix for Pauli-Y , which is iXZ.7The tensor product of two 22-matrices is a 44 matrix.QA controlled operation can be expressed with just the operation to be controlled.FTake the tensor of a pair of Pauli operators, and return a 44 matrix.Scale a 44 matrix.}If a matrix is the tensor product of two Pauli operators, then return the pair of Pauli operators, otherwise throw an error.'Matrix multiplication for 44 matrices.-The transpose of a 44 complex valued matrix.The tensor product IY can be defined by i(IX)(IZ).$$ None =>?HVVMA Clifford group circuit is implicitly simulated using a state monad over a .FThe minimal definition of a two-qubit unitary requires the actions on IX, XI, IZ, and ZI.FThe minimal definition of a two-qubit unitary requires the actions on IX, XI, IZ, and ZI.aA two-qubit (Clifford) unitary can be defined as a function acting on a pair of Pauli operators.<The minimal definition of a unitary requires the actions on X and Z.<The minimal definition of a unitary requires the actions on X and Z.LA (Clifford) unitary can be defined as a function acting on Pauli operators.DThe state of the system is a representation of a stabilizer tableau.+A qubit is defined as an integer reference.7Accessor function for the next_qubit field of a Tableau1Accessor function for the sign field of a Tableau4Accessor function for the tableau field of a Tableau4Accessor function for the de_sign field of a Tableau7Accessor function for the de_tableau field of a TableauJA local Map lookup function that throws an error if the key doesn't exist.An initial (empty) tableau.>A new qubit in the state |0#* or |1#* can be added to a tableau.The definition of a  can be constructed from a .It is possible to construct a  from a 22-matrix.SA unitary can be applied to a qubit in a given tableau. By folding through each row8Apply the unitary to the given column, in the given row.The definition of a  can be constructed from a .It is possible to construct a  from a 44-matrix.It is possible to construct a  from controlling a 22-matrix.JA two-qubit unitary can be applied to a pair of qubits in a given tableau.A measurement, in the computational basis, can be made of a qubit in the Tableau, returning the measurement result, and the resulting Tableau.JThis function reduces a tableau so that it contains either plus or minus Z[sub q2]. Note that it is only called in the case where Z[sub q:] is generated by the tableau (i.e., during measurement).Multiply the stabilizers for the two given rows, in the given tableau, and update the first row with the result of the multiplication.=Multiply row1 of the destabilizer by row2 of the stabilizer.  The Pauli X& operator is a Clifford group unitary.#We can (equivalently) define Pauli-X as a .&We can (equivalently) construct Pauli-X from a .&We can (equivalently) construct Pauli-X from a matrix. The Pauli Y&-operator is a Clifford group unitary.#We can (equivalently) define Pauli-Y as a .&We can (equivalently) construct Pauli-Y from a .&We can (equivalently) construct Pauli-Y from a matrix. The Pauli Z&-operator is a Clifford group unitary.#We can (equivalently) define Pauli-Z as a .&We can (equivalently) construct Pauli-Z from a .&We can (equivalently) construct Pauli-Z from a matrix..The Hadamard-gate is a Clifford group unitary.+We can (equivalently) define Hadamard as a .0We can (equivalently) construct Hadamard from a ._We can (equivalently) construct Hadamard from a matrix. Although rounding errors break this!!!+The phase-gate is a Clifford group unitary.-We can (equivalently) define phase gate as a .2We can (equivalently) construct phase gate from a .9We can (equivalently) construct phase gate from a matrix.+The phase-gate is a Clifford group unitary.-We can (equivalently) define phase gate as a .2We can (equivalently) construct phase gate from a .9We can (equivalently) construct phase gate from a matrix.7The controlled-not is a Clifford group 2-qubit unitary.'We can (equivalently) define CNot as a .,We can (equivalently) construct CNot from a .3We can (equivalently) construct CNot from a matrix.The controlled-Z% is a Clifford group 2-qubit unitary.(We can (equivalently) define controlled-Z as a .+We can (equivalently) construct controlled-Z from a .+We can (equivalently) construct controlled-Z from a matrix.Initialize a new qubit.Initialize multiple qubits.Apply a Pauli-X gate to the given qubit.Apply a Pauli-Y gate to the given qubit.Apply a Pauli-Z gate to the given qubit.)Apply a Hadamard gate to the given qubit.&Apply a phase gate to the given qubit. Apply a given  to the given qubit. Apply a controlled-X gate to the given qubits. Apply a controlled-Z gate to the given qubits. Apply a given  to the given qubits 3Measure the given qubit in the computational basis.!Measure the given list of qubits.BFor testing purposes, we can show the tableau during a simulation.Return the evaluated  for the given circuit.2Return the result of simulating the given circuit.BA swap gate can be defined in terms of three controlled-not gates. A controlled-ZI gate can (equivalently) be defined in terms of Hadamard and controlled-X.TEach of the four Bell states can be generated, indexed by a pair of boolean values.$Create a Bell state, and measure it.HA single-qubit operation can be controlled by a classical boolean value..A simple, single qubit, teleportation circuit.A wrapper around the teleportation circuit that initializes a qubit in the given boolean state, and measures the teleported qubit.Measure an equal superposition.@A tableau can be shown, by enumerating over the qubits in scope.\     \     None =>HVX Lifted version of '(:)' :: a -> [a] -> [a].Lifted version of  '[]' :: [a].Lifted version of ` :: [a] -> [a]. Lifted version of a :: [a] -> [a].!Lifted version of '(++)' :: [a] -> [a] -> [a]."Lifted version of b.#lifted version of c$lifted version of d%lifted version of V&Lifted version of 8'!Lifted version of the combinator e.(Lifted version of f :: String -> aN. Using it will make the circuit generation fail with the error described in g.)Lifted version of h :: (a,b) -> b  !"#$%&'()  !"#$%&'()None>HV#t*0Type for the monad encapsulating error messages.,Shortcut for 'Either String a'.-<Set an error message, to be thrown. Usage: -errorMsg "an error happened" .Make a ! computation error-message aware./RThrow the error that has been created, using the given string as a prefix. Usage: HextractQ "name of function: " $ do <<commands that may thow an error>>*+,-./,*+-./None>HV8 3 The monad.5 Shortcut to StateT LiftState ErrMsgQ.6State of the monad.8"How many times each name is bound.9The template prefix .:The name of the monad.;An empty state.<"Retrieve the state from the monad.=Set the state of the monad.>From * to 3.?From  to 3.@Get  out of 3ASet an error message.B0Increase the number of binds of a variable name.C0Decrease the number of binds of a variable name.D5Run a computation with a particular name being bound.E>Run a computation with a particular list of names being bound.F"Say whether a given name is bound.GSet the template prefix.HGet the template prefix.ISet the monad name.JGet the monad name.KMake a name out of a string.L+Make a name out of a string, monadic-style.M.Make any string into a string containing only  [0-9a-zA-Z_.].. For example, it replaces any occurrence of "+" with  "symb_plus_".NCTake a string and make it into a valid Haskell name starting with  "template_".O+Look for the corresponding "template" name.P,Make a the template version of a given name.Q2Print on the terminal a monadic, printable object.R!Project patterns out of a clause.SCCheck that the list is a non-empty repetition of the same element.TwReturns the length of the patterns in a list of clauses. Throw an error if the patterns do not have all the same size."34567:89;<=>?@ABCDEFGHIJKLMNOPQRST"67:89;534<=>?@ABCDEFGHIJKLMNOPQRSTNone >HSVX^CX Datatype to encode the notation  x <- expr.Z Expression[Variable name.\Constant name.]Literal.^ Application._Lambda abstraction.`Tuple.a If-then-else.bLet-construct.cCase distinctiondList: [...].ehardcoded constant for i.fhardcoded constant for j.gFirst-level declaration.iMatch term construct.k Patterns.lLiteral.mVariable name.nTuple.o Wildchar.pList as [...].qCons: h:t.r Literals.s Characters.t Integers.uReals.vmThere are no "guarded bodies". One net effect is to make the "where" construct equivalent to a simple "let".w A simple do: list of monadic let followed by a computation.x+Get the set of variable names in a pattern.ySubstitution in a i.zSubstitution in a g.{Substitution in an Z.|,Substitution of several variables in one go.}Downgrading TH literals to Z.~Downgrading TH literals to k.&Take a list of patterns coming from a where: section and output a list of fresh names for normalized letys. Also gives a mapping for substituting inside the expressions. Assume all names in the list of patterns are distinct.Build a let-expression out of pieces.Build a i out of a TH clauseTFrom a list of TH clauses, make a case-distinction wrapped in a lambda abstraction.Downgrade expressions.Downgrade match-constructs."Downgrade bodies into expressions.Downgrade patterns.#Downgrade first-level declarations.2Downgrade any declarations (including the ones in where -constructs).1Abstract syntax tree of the type of the function i.1Abstract syntax tree of the type of the function j.Upgrade literalsUpgrade patterns.Upgrade match-constructs.Upgrade declarations.Upgrade expressions.8Variable referring to the lifting function for integers.5Variable referring to the lifting function for reals.Lifting literals.Lifting patterns.Lifting match-constructs.Lifting declarations.!Lifting first-level declarations.Lifting expressions.Wmake a declaration into a template-declaration (by renaming with the template-prefix)..pretty-printing Template Haskell declarations.-Pretty-printing Template Haskell expressions.Pretty-printing expressions.WLift a list of declarations. The first argument is the name of the monad to lift into.NLift an expression. The first argument is the name of the monad to lift into.FXYZfedcba`_^]\[ghijkpoqnmlrutsvwxyz{|}~FvrutskpoqnmlijghZfedcba`_^]\[XYwxyz{|}~None>HVaW !"#$%&'()None =>?@ACHVn*In almost all instances, the standard form can also be deduced from the tupled form; the only exception is the unary case. The I class includes no new methods, adding just this functional dependency.While the methods of ! are always copied from those of v, they are renamed, so that use of these methods tells the type checker it can use the extra functional dependency.*This type class relates types of the form  t = (a,b,c,d)' ( tupled form ) to types of the form s = (a,(b,(c,(d,()))))S ( standard form ), and provides a way to convert between the two representations.=The tupled form can always be deduced from the standard form.For example, maps (a,(b,(c,(d,())))) to  (a,b,c,d).For example, maps  (a,b,c,d) to (a,(b,(c,(d,())))).None =>?HV` Types in the k class have an "origin", i.e., an element that can conveniently serve as the starting point for intervals.ZInputs any element of the type and outputs the corresponding "zero" element, for example: %zero ([1,2],3,True) = ([0,0],0,False)The  class contains types for which an interval of values can be specified by giving a lower bound and an upper bound. Intervals are specified as  min max, for example: =interval (0,0) (1,2) = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)].Takes a range (min,max5) and returns a list of all values with lower bound min and upper bound max. min max3: returns a list of all elements from the range (min,max'). This is actually just a synonym of . n k min max: returns every nth element from the range (min,max), starting with the k th element. g min max@: returns an infinite list of random samples from the range (min,max%), using the random number generator g. A variant of  that omits the min argument, and uses the  element of the type instead. A variant of  that omits the min argument, and uses the  element of the type instead. A variant of  that omits the min argument, and uses the  element of the type instead.ksamples every n0th element from the list, starting with element klsame as U*, but throw an error if length don't matchLists7-Tuples6-Tuples5-Tuples4-TuplesTriplesPairs0-tuples  None =>?HV A "control source" is anything that can be used as a control on a gate. The most common way to construct a control source is by using the 14, 15, and 16= operators. In addition, we provide the following instances:J. A boolean condition that is known at circuit generation time can be used as a control, which is then either trivial (the gate is generated) or inconsistent (the gate is not generated).. This includes the type 12/ (for a classical execution-time control) and 17k (for a quantum control). A wire can be used as a shorthand notation for a positive control on that wire.r. A control list is Quipper's internal representation of a control condition, and is trivially a control source.:A list of control sources can be used as a control source.!Convert a condition to a control.A ~ is Quipper's internal representation of the type of conjunctive controls, i.e., controls that can be constructed using the 14, 15, and 16 operators.JThe empty control list, corresponding to a condition that is always true..Add a single signed control to a control list.combine list1 list2J: Take the conjunction of two control lists. This is more efficient if list1 is small and list2 is large.Like $, but the first argument is of type  from the Quipper.Internal.Circuit module.Like #, but also return a value of type , or PE if the controls are inconsistent. This function is for convenience.Modify the given gate by applying the specified controls. If the total set of controls (i.e., those specified in the gate itself and those specified in the control list) is inconsistent, return P. If it is consistent, return the appropriately controlled version of the gate. Throw an error if the gate is of a kind that cannot be controlled.The "catch all" clause for y. This handles all gates that are not controllable. If the control condition is known at circuit generation time to be P, then we can just append the gate unconditionally. All other cases are errors.(Define whether a gate can be controlled.<Define whether an entire low-level circuit can be controlledNone2=>?HSVX`(Synonym for a bit list, for convenience.*Synonym for a qubit list, for convenience.A control consists of an  and a boolean (Y) = perform gate when control wire is 1; [j = perform gate when control wire is 0). Note that gates can be controlled by qubits and classical bits.+An endpoint in a circuit. This is either a  or a .HThe type of run-time classical bits (i.e., boolean wires in a circuit).The type of qubits. The  f monad encapsulates the type of quantum operations. For example, a quantum operation that inputs two s and outputs a  and a  has the following type: #(Qubit, Qubit) -> Circ (Qubit, Bit)mHolds the state during circuit construction. Currently this has four components: the output arity of the circuit currently being assembled, the current , the currently active  and  w, and a flag to determine whether comments are disabled. All gates that are appended will have the controls from the  added to them.n2A flag to indicate whether comments are disabled (Y) or enabled ([).o]Return a completely empty state, suitable to be the starting state for circuit construction.p7Prepare an initial state from the given extended arity.qGet the   monad's state.rSet the   monad's state.sPass a gate to the   monad. Note that this is a low-level monad access function, and does not update other parts of the monad's data. For a higher-level function, see t.u#Issue a prompt and receive a reply. Issue a RW_Subroutine primitivev-This is the universal "run" function for the  # monad. It takes as parameters a  0 computation, and an initial state. It outputs # computation for the result of the  " computation and the final state.wGet the x part of the   monad's state.ySet the x part of the   monad's state. Get the z part of the   monad's state. Set the z part of the   monad's state.{Get the | part of the   monad's state.}Set the | part of the   monad's state.~Get the  part of the   monad's state.Set the  part of the   monad's state.Get the  part of the   monad's state.Set the  part of the   monad's state. Extract a circuit from a monadic term, starting from the given arity. This is the "simple" extract function, which does not allow dynamic lifting. The [ argument is a stub error message to be used in case an illegal operation is encountered. NRun a monadic term in the initial arity, and extract a dynamic boxed circuit.1Extract the underlying low-level wire of a qubit./Extract the underlying low-level wire of a bit.Construct a qubit from a wire.Construct a bit from a wire.!Extract the underlying low-level  of an .!Extract the underlying low-level  of an .Break a list of s down into a list of s together with an . (Partial inverse to .) Create an  from a low-level  and .Create a list of s from a list of s together with an /, assuming all wires are present in the arity.?Bind a qubit wire to a value, and add it to the given bindings.=Bind a bit wire to a value, and add it to the given bindings.vRetrieve the value of a qubit wire from the given bindings. Throws an error if the wire was bound to a classical bit.mRetrieve the value of a bit wire from the given bindings. Throws an error if the wire was bound to a qubit.9Add a single signed qubit as a control to a control list.7Add a single signed bit as a control to a control list.; name circ in_struct out_struct is_classically_controllable: if name not already bound, binds it to circ.. Note: when there s an existing value, does not check that it s equal to circ.  namespace : Add each subroutine from the  namespaceJ to the current circuit, unless a subroutine of that name already exists. name circ: if name4 not already bound, binds it to the main circuit of circ8, and additionally provides any missing subroutines of circ.tApply the specified low-level gate to the current circuit, using the current controls, and updating the monad state accordingly. This includes run-time well-formedness checks. This is a helper function and is not directly accessible by user code. Apply a NOT gate to a qubit.!Apply a Hadamard gate."(An alternate name for the Hadamard gate.#MApply a multiple-not gate, as specified by a list of booleans and qubits: 1qmultinot_list [(True,q1), (False,q2), (True,q3)] applies a not gate to q1 and q3 , but not to q2.$Like #4, but applies to classical bits instead of qubits. %Apply a Pauli X gate.&Apply a Pauli Y gate.'Apply a Pauli Z gate.(Apply a Clifford S-gate.)Apply the inverse of an S-gate.*Apply a T = "S gate.+Apply the inverse of a T-gate.,Apply a Clifford E = HS[sup 3][sup 3] gate.  [image E.png]>This gate is the unique Clifford operator with the properties E = I, EXE { = Y, EYE { = Z, and EZE { = Xv. It is a convenient gate for calculations. For example, every Clifford operator can be uniquely written of the formE[sup a]X[sup b]S[sup c][sup d],where a, b, c, and d0 are taken modulo 3, 2, 4, and 8, respectively.-Apply the inverse of an E-gate..Apply the scalar  = [exp i/4], as a single-qubit gate./Apply a V = "XV gate. This is by definition the following gate (see also Nielsen and Chuang, p.182): [image V.png]0Apply the inverse of a V-gate.1Apply a SWAP gate.2Apply a classical SWAP gate.3Apply an [exp "iZt] gate. The timestep t is a parameter.4Apply a rotation by angle 2i/2[sup n ] about the z-axis.[image rGate.png]5Apply a W gate. The W7 gate is self-inverse and diagonalizes the SWAP gate.  [image W.png]The arguments are such that  pgate_W |0#* |0#* = |00#* gate_W |0#* |1#* = (|01#*+|10#*) / "2 gate_W |1#* |0#* = (|01#*-|10#*) / "2 gate_W |1#* |1#* = |11#*.In circuit diagrams, W&[sub 1] denotes the "left" qubit, and W#[sub 2] denotes the "right" qubit.6 Apply an iX0 gate. This gate is used similarly to the Pauli X gate, but with two advantages:the doubly-controlled iX* gate can be implemented in the Clifford+T gate base with T -count 4 (the doubly-controlled X gate requires T -count 7);the iX*-gate has determinant 1, and therefore an n-times controlled iX) gate can be implemented in the Clifford+T gate base with no ancillas.In particular, the iX; gate can be used to implement an additional control with T-count 8, like this:[image iX.png]7 Apply a "iX gate. This is the inverse of 6.8!Apply a global phase change [exp it], where typically t " [0,2]. This gate is uninteresting if not controlled; however, it has non-trivial effect if it is used as a controlled gate.9Like 8|, except the gate is also "anchored" at a particular bit or qubit. This is strictly for graphical presentation purposes, to provide a hint for where the gate should be printed in a circuit diagram. Backends are free to ignore this hint altogether. The anchor is not actually an input to the gate, and it is legal for the anchoring qubit to also be used as a control control.:Apply a generic quantum gate to a given list of qubits and a given list of generalized controls. The generalized controls are really inputs to the gate, but are guaranteed not to be modified if they are in a computational basis state.;Like :, but produce a named gate that also depends on a real parameter. This is typically used for rotations or phase gates parameterized by an angle. The name can contain '%' as a place holder for the parameter, for example  "exp(-i%Z)".<$Apply a NOT gate to a classical bit.=Apply a NOT gate to a qubit.>Apply a Hadamard gate.?(An alternate name for the Hadamard gate.@Apply a qmultinot_list9 gate, as specified by a list of booleans and qubits: 1qmultinot_list [(True,q1), (False,q2), (True,q3)] applies a not gate to q1 and q3 , but not to q2.ALike @4, but applies to classical bits instead of qubits. BApply a Pauli X gate.CApply a Pauli Y gate.DApply a Pauli Z gate.EApply a Clifford S-gate.FApply the inverse of an S-gate.GApply a T = "S gate.HApply the inverse of a T-gate.IApply a Clifford E = HS[sup 3][sup 3] gate.  [image E.png]>This gate is the unique Clifford operator with the properties E = I, EXE { = Y, EYE { = Z, and EZE { = Xv. It is a convenient gate for calculations. For example, every Clifford operator can be uniquely written of the formE[sup a]X[sup b]S[sup c][sup d],where a, b, c, and d0 are taken modulo 3, 2, 4, and 8, respectively.JApply the inverse of an E-gate.KApply the scalar  = [exp i/4], as a single-qubit gate.LApply a V = "XV gate. This is by definition the following gate (see also Nielsen and Chuang, p.182): [image V.png]MApply the inverse of a V-gate.NApply a SWAP gate.OApply a classical SWAP gate.PApply an [exp "iZt] gate. The timestep t is a parameter.QApply a rotation by angle 2i/2[sup n ] about the z-axis.[image rGate.png]RApply a W gate. The W7 gate is self-inverse and diagonalizes the SWAP gate.  [image W.png]The arguments are such that  pgate_W |0#* |0#* = |00#* gate_W |0#* |1#* = (|01#*+|10#*) / "2 gate_W |1#* |0#* = (|01#*-|10#*) / "2 gate_W |1#* |1#* = |11#*.In circuit diagrams, W&[sub 1] denotes the "left" qubit, and W#[sub 2] denotes the "right" qubit.S Apply an iX0 gate. This gate is used similarly to the Pauli X gate, but with two advantages:the doubly-controlled iX* gate can be implemented in the Clifford+T gate base with T -count 4 (the doubly-controlled X gate requires T -count 7);the iX*-gate has determinant 1, and therefore an n-times controlled iX) gate can be implemented in the Clifford+T gate base with no ancillas.In particular, the iX; gate can be used to implement an additional control with T-count 8, like this:[image iX.png]T Apply a "iX gate. This is the inverse of S.UApply a generic quantum gate to a given list of qubits and a given list of generalized controls. The generalized controls are really inputs to the gate, but are guaranteed not to be modified if they are in a computational basis state.VLike U, but produce a named gate that also depends on a real parameter. This is typically used for rotations or phase gates parameterized by an angle. The name can contain '%' as a place holder for the parameter, for example  "exp(-i%Z)".W$Apply a NOT gate to a classical bit.X3Generate a new qubit, initialized to the parameter J.Y*Terminate a qubit asserted to be in state b. We note that the assertion is relative to the precision: when gates in a circuit are implemented up to some precision  (either due to physical limitations, or due to decomposition into a discrete gate base), the assertion may only hold up to a corresponding precision as well.ZDiscard a qubit destructively.[sGenerate a new qubit, initialized from a classical bit. Note that the classical bit is simultaneously terminated. \Unprepare a qubit asserted to be in a computational basis state. This is the same as a measurement, but must only be applied to qubits that are already known to be in one of the states |0#* or |1#*, and not in superposition. This operation is rarely (perhaps never?) used in any quantum algorithms, but we include it for consistency reasons, because it is formally the inverse of [.]4Apply a measurement gate (turns a qubit into a bit).^BGenerate a new classical bit, initialized to a boolean parameter b._Terminate a classical  asserted to be in state J.`Terminate a classical ; with a comment indicating what the observed state of the  was, in this particular dynamic run of the circuit. This is typically used to terminate a wire right after a dynamic lifting has been performed. It is not intended to be a user-level operation.It is important to note that a > gate does not, in any way, represent an assertion. Unlike a K gate, which asserts that the classical bit will have the stated value at every run of the circuit, the J gate simply records that the classical bit had the stated value at some  particular run of the circuit.*Operationally (e.g., in a simulator), the ] gate can be interpreted in multiple ways. In the simplest case, it is just treated like a  gate, and the boolean comment ignored. Alternatively, it can be treated as a post-selection gate: if the actual value does not equal the stated value, the entire computation is aborted. Normally,  gates should appear in the output , not the inputY of simulators; therefore, the details of the behavior of any particular simulator on a $ gate are implementation dependent.a&Discard a classical bit destructively.b-Return the "exclusive or" of a list of bits. c&Test equality of two bits, and return Y iff they are equal. dIf a is Y, then return b, else return c.e3Return the negation of its input. Note that unlike < or WG, this gate does not alter its input, but returns a newly created bit.f)Return the conjunction of a list of bits.g)Return the disjunction of a list of bits.hApply a named classical gate. This is used to define all of the above classical gates, but should not usually be directly used by user code.ii name w inputs7: Uncompute a named classical gate. This asserts that w6 is in the state determined by the gate type and the inputs, then uncomputes wH in a reversible way. This rarely used gate is formally the inverse of h.jInsert a subroutine gate with specified name, and input/output output types, and attach it to the given endpoints. Return the new endpoints.Note that the [] and  arguments are used as a pattern: for the locations/types of wires of the subroutine; the [] argument (and output) specify what is attached in the current circuit. The two aspects of this pattern that are respected are: the lingeringness of any inputs; and the number and types of wires.3For instance (assuming for simplicity that all wires are qubits), if the patterns given are inputs [1,3,5], outputs [1,3,4] , and the actual inputs specified are [20,21,25], then the output wires produced might be e.g. [20,21,23], [20,21,36], or [20,21,8], depending on the next available free wire.More subtly, if the patterns given are inputs [1,2,3], outputs [3,7,8,1] , and the inputs given are [10,5,4], then the outputs will be [4,x,y ,10], where x, y are two fresh wires.[Note that lingering wires may change type, for e.g. subroutines that include measurements.UIt is currently assumed that all these lists are linear, i.e. contain no duplicates.kLook up the specified subroutine in the namespace, and apply it to the specified inputs, or throw an error if they are not appropriately typed.KThe input/output types of this function are determined dynamically by the  stored with the subroutine.lInsert a comment in the circuit. This is not a gate, and has no effect, except to mark a spot in the circuit. The comment has two parts: a string (possibly empty), and a list of labelled wires (possibly empty). This is a low-level function. Users should use 18 instead.mRDisable labels and comments for a block of code. The intended usage is like this: ,without_comments $ do { <<<code block>>> }This is sometimes useful in situations where code is being re-used, for example when one function is implemented in terms of another, but should not inherit comments from it. It is also useful in the definition of recursive function, where a comment should only be applied at the outermost level. Finally, it can be used to suppress comments from parts of circuits for presentation purposes.n Convert a  (boolean circuit output) to a J (boolean parameter).For use in algorithms that require the output of a measurement to be used as a circuit-generation parameter. This is the case, for example, for sieving methods, and also for some iterative algorithms.Note that this is not a gate, but a meta-operation. The input consists of classical circuit endpoints (whose values are known at circuit execution time), and the output is a boolean parameter (whose value is known at circuit generation time). The use of this operation implies an interleaving between circuit execution and circuit generation. It is therefore a (physically) expensive operation and should be used sparingly. Using the n operation interrupts the batch mode operation of the quantum device (where circuits are generated ahead of time), and forces interactive operation (the quantum device must wait for the next portion of the circuit to be generated). This operation is especially expensive if the current circuit contains unmeasured qubits; in this case, the qubits must be preserved while the quantum device remains on standby.Also note that this operation is not supported in all contexts. It is an error, for example, to use this operation in a circuit that is going to be reversed, or in the body of a boxed subroutine. Also, not all output devices (such as circuit viewers) support this operation.o-Generate a new qubit initialized to |+#* when b=[ and |"#* when b=Y.pYGenerate a new qubit initialized to one of |0#*, |1#*, |+#*, |"#*, depending on a character c which is '0', '1', '+', or '-'.qxGenerate a list of qubits initialized to a sequence of |0#*, |1#*, |+#*, |"#*, defined by a string argument e.g. "00+0+++".r A version of X that operates on lists. s A version of Y that operates on lists. We initialize left-to-right and terminate right-to-left, as this leads to more symmetric and readable circuits, more stable under reversal.Note: if the left argument to sZ is longer than the right argument, then it is truncated. So the first argument can be ( [F). It is an error if the left argument is shorter than the right one.t A version of ^ for lists.uConvenient wrapper around 19 and 1:J. This can be used to introduce an ancilla with a local scope, like this: >with_ancilla $ \h -> do { <<<code block using ancilla h>>> }The ancilla will be initialized to |0#* at the beginning of the block, and it is the programmer's responsibility to ensure that it will be returned to state |0#* at the end of the block.A block created with u: is controllable, provided that the body is controllable.vXA syntax for "if"-style (classical and quantum) controls. This can be used as follows: ?gate1 with_controls <<controls>> $ do { gate2 gate3 } gate4The specified controls will be applied to gate2 and gate3. It is an error to specify a control for a gate that cannot be controlled (such as measurement).w8An infix operator to apply the given controls to a gate: gate `controlled` <<controls>>*It also works with functional-style gates: (result <- gate `controlled` <<controls>>MThe infix operator is left associative, so it can be applied multiple times: Dresult <- gate `controlled` <<controls1>> `controlled` <<controls2>>The latter is equivalent to <result <- gate `controlled` <<controls1>> .&&. <<controls2>>xGApply a block of gates while temporarily suspending the application of controls. This can be used to omit controls on gates where they are known to be unnecessary. This is a relatively low-level function and should not normally be called directly by user code. Instead, it is safer to use a higher-level function such as 1;. However, the xR operator is useful in certain situations, e.g., it can be used to preserve the   when defining transformers.Usage: 'without_controls $ do <<code block>>or: without_controls (gate)(Note that all controls specified in the  surrounding code are disabled within the x" block. This is even true if the x block appears in a subroutine, and the subroutine is later called in a controlled context. On the other hand, it is possible to specify controls inside the x block. Consider this example: my_subcircuit = do gate1 without_controls $ do { gate2 gate3 `controlled` <<controls1>> } gate4 my_circuit = do my_subcircuit `controlled` <<controls2>>In this example, controls 1 will be applied to gate 3, controls 2 will be applied to gates 1 and 4, and no controls will be applied to gate 2.yApply x if   is Y, otherwise do nothing.z3Generate a new qubit, initialized to the parameter JH, that is guaranteed to be used as an ancilla and terminated with { . Deprecated.{-Terminate an ancilla asserted to be in state b . Deprecated.|The identity transformer. This just maps a low-level circuits to the corresponding circuit-generating function. It can also be used as a building block in other transformers, to define "catch-all" clauses for gates that don't need to be transformed.pThe identity transformer can be enriched with a dynamic lifting operation, so as to define a DynamicTransformer}CThe identity DynamicTransformer uses the built in do_read operationFWe can define a dynamic transformer with a "constant" lifting function~Append the entire circuit cL to the current circuit, using the given bindings. Return the new bindings.Append the entire circuit c to the current circuit, using the given bindings, and return the new bindings. Also, add to the current namespace state any subroutines of c! that are not already provided."Append the entire dynamic circuit c to the current circuit, using the given bindings, and return the new bindings. Also, add to the current namespace state any subroutines of c that are not already provided. Similar to  2, except we take the current output arity of the current circuit and make that the input arity of the extracted circuit. Therefore, endpoints defined in the current context can be used in fV. This is a low-level operator, intended for the construction of primitives, such as 1< or 1;U, where the inner block can re-use some variables without declaring them explicitly.cWe also reuse the namespace of the current context, to avoid recomputation of shared subroutines. As a special feature, also return the set of "dirty" wires, i.e., wires that were used during the execution of the body, but are free at the end.Intermediate between   and o: we build the circuit in the namespace of the current circuit, to avoid recomputing any shared subroutines. Append the ` to the end of the current circuit, using the identity binding. This means, the input wires of  mustD be endpoints in the current circuits. This typically happens when  was obtained from " in the current context, or when ? is the inverse of a circuit that has just been applied using . iNote that this is a low-level function, intended for the construction of user-level primitives such as 1< and 1;, and 1=. uses t& to do the appending, so the current  and   are respected. However, it does not pass through the transformer interface, and therefore low-level wire id's will be exactly preserved.Reverse an encapsulated circuitAn encapsulated circuit is a circuit together with data structures holding the input endpoints and output endpoints. The type of the encapsulated circuit depends on the type of data in the endpoints, so functions to encapsulate and unencapsulate circuits are provided in Quipper.Internal.Generic.Perform the computation in the body, but temporarily reserve a set of wires. These wires must be initially free, and they must not be used by the body (i.e., the body must respect reserved wires).       !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  k    !"%&'()*+,-./013456789#$:;<2=>?BCDEFGHIJKLMNPQRST@AUVWOXYZ[\]^_a`bcdefghijlmnopqrstuvwxyz{|}~ w2Unsafe =>?@AHVH2 a s means that a; is a data structure that can be labelled with the format sJ. A "format" is a string, or a data structure with strings at the leaves.:Recursively label a data structure with the given format. 6A monad to provide a convenient syntax for specifying  instances. Computations in this monad have access to a read-only "current index list", and they output a binding from wires to strings.iAn index list is something that can be appended to a string. We consider subscript indices of the form "[i]", dotted indices of the form ".i", and perhaps arbitrary suffixes. A complication is that we want consecutive subscript indices to be combined, as in "[i,j,k]". We therefore need a special data structure to hold an index list "under construction".An index list consists of a string and a list of current subscripts. For efficiency, the list of subscripts is reversed, i.e., the most recent subscript is at the head of the list."Convert an index list to a string.The empty index list.$Append a subscript to an index list.'Append a dotted index to an index list.!Get the current string and index.Output a binding for a label3Run a subcomputation with a new current index list.aExtract a labelling from a label monad computation. This is the run function of the label monad.:Label a wire with the given name, using the current index.^Run a subcomputation with a subscript index appended to the current index list. Sample usage: %with_index "0" $ do <<<labelings>>>Run a subcomputation with a dotted index appended to the current index list. Sample usage: /with_dotted_index "left" $ do <<<labelings>>>Like c, except the order of the arguments is reversed. This is intended to be used as an infix operator: <<<labeling>>> `indexed` "0"Like c, except the order of the arguments is reversed. This is intended to be used as an infix operator: &<<<labeling>>> `dotted_indexed` "left" Do nothing.FGiven a data structure and a format, return a list of labelled wires.Insert a comment in the circuit. This is not a gate, and has no effect, except to mark a spot in the circuit. How the comment is displayed depends on the printing backend.Label qubits in the circuit. This is not a gate, and has no effect, except to make the circuit more readable. How the labels are displayed depends on the printing backend. This can take several different forms. Examples:Label q as q and r as r: label (q,r) ("q", "r")Label a, b, and c as a, b, and c, respectively: label [a,b,c] ["a", "b", "c"]Label q as x[0] and r as x[1]: label (q,r) "x"Label a, b, and c as x[0], x[1], x[2]: label [a,b,c] "x"Combine  and  in a single command.>None 12>HVIpNone,=>?@ACHVXr8The type operator  converts  to  and  to .A type to represent a " leaf, for the sole purpose that  will show it as "C".A type to represent a " leaf, for the sole purpose that  will show it as "Q". The class  consists of the two types  and . It is primarily used for convenience, in those cases (such as the arithmetic library) where some class instance should be defined for the cases  and , but not for general M. It is also used, e.g., in the definition of the 'Quipper.(./=.)' operator., is a convenience type class that combines  and ., is a convenience type class that combines  and .The # type class is almost identical to v, except that it contains one additional piece of information that allows the type checker to prove the implications QCDataPlus qc implies QShape (BType qc) (QType qc) (CType qc) QCDataPlus qc implies QData (QType qc) QCDataPlus qc implies CData (CType qc) QCDataPlus qc implies BData (BType qc)SThis is sometimes useful, for example, in the context of a function that inputs a *, measures all the qubits, and returns a . However, the additional information for the type checker comes at a price, which is drastically increased compilation time. Therefore  should only be used when  is insufficient.The  class allows the definition of generic functions that can operate on quantum data of any "shape", for example, nested tuples or lists of qubits.DIn general, there are three kinds of data: quantum inputs (such as ), classical inputs (such as &), and classical parameters (such as J). For example, a  can be initialized from a J; a " can be measured, resulting in a ', etc. For this reason, the type class - establishes a relation between three types: qaA data structure having  at the leaves.ca&A data structure of the same shape as qa , having  at the leaves.ba&A data structure of the same shape as qa , having J at the leaves.Some functions input a classical parameter for the sole purpose of establishing the "shape" of a piece of data. The shape refers to qualities of a data structure, such as the length of a list, which are not uniquely determined by the type. For example, two different lists of length 5 have the same shape. When performing a generic operation, such as reversing a circuit, it is often necessary to specify the shape of the inputs, but not the actual inputs.EIn the common case where one only needs to declare one of the types qa, ca, or ba", one of the simpler type classes , , or  can be used.The J type class contains homogeneous data types built up from leaves of type J.The J type class contains homogeneous data types built up from leaves of type .The J type class contains homogeneous data types built up from leaves of type .The type operator  xS converts a classical, quantum, or boolean type to a homogeneous type with leaves x. More precisely, the type  x a$ represents the substitution [nobr a [x / , x / ]]. For example: AHType x (Qubit, [Qubit]) = (x, [x]) HType x (Qubit, Bit) = (x, x)*There is a very subtle difference between  x a and  x x a.. Although these two types are equal for all x and a., the type checker cannot actually prove that  x x a$ is homogeneous from the assumption  a. It can, however, prove that  x a is homogeneous. Therefore / (or the slightly more efficient special cases , , O) should always be used to create a homogeneous type from a heterogeneous one.The type operator p converts a classical, quantum, or heterogeneous type to a homogeneous boolean type. More precisely, the type  a$ represents the substitution [nobr a [J / , J / w]]. It can be applied to both homogeneous and heterogeneous types, and always yields a homogeneous type. For example: IBType (Qubit, [Qubit]) = (Bool, [Bool]) BType (Qubit, Bit) = (Bool, Bool)The type operator f converts a classical or heterogeneous type to a homogeneous quantum type. More precisely, the type  a# represents the substitution [nobr a [ / w]]. It can be applied to both homogeneous and heterogeneous types, and always yields a homogeneous type. For example: ECType (Qubit, [Qubit]) = (Bit, [Bit]) CType (Qubit, Bit) = (Bit, Bit)The type operator f converts a classical or heterogeneous type to a homogeneous quantum type. More precisely, the type  a# represents the substitution [nobr a [ / x]]. It can be applied to both homogeneous and heterogeneous types, and always yields a homogeneous type. For example: IQType (Bit, [Bit]) = (Qubit, [Qubit]) QType (Qubit, Bit) = (Qubit, Qubit) is a subclass of 6 consisting of simple types. We say that a data type t% is "simple" if any two elements of tT have the same number of leaves. For example, tuples are simple, but lists are not.fProduce a term of the given shape. This term will contain well-defined data constructors, but may be  at the leaves.The L type class contains heterogeneous data types built up from leaves of type  and . It is the basis for several generic operations that apply to classical and quantum data, such as copying, transformers, simulation, and heterogeneous versions of qterm and qdiscard. and F are interrelated, in the sense that the following implications hold: =QData qa implies QCData qa CData ca implies QCData ca:Implications in the converse direction also hold whenever qc is a fixed known type: tQCData qc implies QData (QType qc) QCData qc implies CData (CType qc) QCData qc implies BData (BType qc)PHowever, the type checker cannot prove the above implication in the case where qcW is a type variable; for this, the more flexible (but more computationally expensive)  class can be used.Map two functions f and g? over all the leaves of a heterogeneous data structure. Apply f to all the leaves at  positions, and g to all the leaves at : positions. The first argument is a shape type parameter.8Example (ignoring the monad for the sake of simplicity): Kqcdata_mapM (qubit, bit, [qubit]) f g (x,y,[z,w]) = (f x, g y, [f z, f w]).For data types that have a sense of direction, the mapping should preferably be performed from left to right, but this property is not guaranteed and may change without notice. Zip two heterogeneous data structures together, to obtain a new data structure of the same shape, whose elements are pairs of the corresponding elements of the input data structures. The zipping is strict@, meaning that both input data structure must have exactly the same shape (same length of lists, etc). The first five arguments are shape type parameters, representing the shape of the data structure, the two leaf types of the first data structure, and the two leaf types of the second data structure, respectively.Example: qcdata_zip (bit, [qubit]) int bool char string (True, [2,3]) ("b", ['c', 'd']) = ((True, "b"), [(2,'c'), (3,'d')]) where the shape parameters are: int = dummy :: Int bool = dummy :: Bool char = dummy :: Char string = dummy :: String The A argument is a stub error message to be used in case of failure.sIt is sometimes convenient to have a boolean parameter with some aspect of its shape indeterminate. The function 8 takes such a boolean parameter, as well as a piece of E, and attempts to set the shape of the former to that of the latter.bThe kinds of promotions that are allowed depend on the data type. For example, for simple types,  has no work to do and should just return the first argument. For types that are not simple, but where no promotion is desired (e.g.  ?),  should check that the shapes of the first and second argument agree, and throw an error otherwise. For lists, we allow a longer list to be promoted to a shorter one, but not the other way around. For quantum integers, we allow an integer of indeterminate length to be promoted to a determinate length, but we do not allow a determinate length to be changed to another determinate length.The A argument is a stub error message to be used in case of failure. The type  ba$ represents the substitution [nobr ba [ / J]]. For example:  6QTypeB (Bool, Bool, [Bool]) = (Qubit, Qubit, [Qubit]).FAn instance of this must be defined for each new kind of quantum data. The type  x y a$ represents the substitution [nobr a [x / , y / ]]. For example: /QCType x y (Qubit, Bit, [Qubit]) = (x, y, [x]).GAn instance of this must be defined for each new kind of quantum data.'A dummy term of any type. This term is B and must never be evaluated. Its only purpose is to hold a type.A dummy term of type -. It can be used in shape parameters (e.g., 1@,), as well as shape type parameters (e.g., ).A dummy term of type -. It can be used in shape parameters (e.g., 1@,), as well as shape type parameters (e.g., ).A dummy term of type J.mConvert a piece of homogeneous quantum data to a shape type parameter. This is guaranteed to never evaluate x", and returns an undefined value.oConvert a piece of homogeneous classical data to a shape type parameter. This is guaranteed to never evaluate x", and returns an undefined value.mConvert a piece of homogeneous boolean data to a shape type parameter. This is guaranteed to never evaluate xJ, and returns an undefined value. Do not confuse this with the function 1A, which creates a shape value.4A dummy term of the same type as the given term. If x :: a, then  x :: a%. This is guaranteed not to evaluate x", and returns an undefined value.Map a function fz over all the leaves of a data structure. The first argument is a dummy shape parameter: its value is ignored, but its type8 is used to determine the shape of the data to map over.8Example (ignoring the monad for the sake of simplicity): Aqdata_mapM (leaf, [leaf]) f (x,[y,z,w]) = (f x, [f y, f z, f w]).For data types that have a sense of direction, the mapping should preferably be performed from left to right, but this property is not guaranteed and may change without notice.(Zip two data structures with leaf types x and yM together, to obtain a new data structure of the same shape with leaf type (x, y). The first three arguments are dummy shape type parameters, representing the shape type and the two leaf types, respectively.The A argument is a stub error message to be used in case of failure.qSometimes, it is possible to have a boolean parameter with some aspect of its shape indeterminate. The function ~ takes such a boolean parameter, as well as a piece of quantum data, and sets the shape of the former to that of the latter.Indeterminate shapes can be used with certain operations, such as controlling and terminating, where some aspect of the shape of the parameter can be determined from the context in which it is used. This is useful, e.g., for quantum integers, where one may want to specify a control condition by an integer literal such as 17, without having to specify the number of bits. Thus, we can write, e.g., gate `controlled` qi .==. 17instead of the more cumbersome 6gate `controlled` qi .==. (intm (qdint_length qi) 17).]Another useful application of this arises in the use of infinite lists of booleans (such as [[..]?), to specify a control condition for a finite list of qubits.Because this function is used as a building block, we also pass an error message to be used in case of failure. This will hopefully make it clearer to the user which operation caused the error.The inverse of ): Take a data structure with leaf type (x, yE), and return two data structures of the same shape with leaf types x and yb, respectively. The first three arguments are dummy shape type parameters, analogous to those of .LMap a function over every leaf in a data structure. Non-monadic version of .>Visit every leaf in a data structure, updating an accumulator.}Map a function over every leaf in a data structure, while also updating an accumulator. This combines the functionality of  and .Monadic version of A: Visit every leaf in a data structure, updating an accumulator.Monadic version of : Map a function over every leaf in a data structure, while also updating an accumulator. This combines the functionality of  and .Return a list of leaves of the given homogeneous data structure. The first argument is a dummy shape type parameter, and is only used for its type.JThe leaves are ordered in some deterministic, but arbitrary way. It is guaranteed that when two data structures of the same shape type and shape (same length of lists etc) are sequentialized, the leaves will be ordered the same way. No other property of the order is guaranteed, In particular, it might change without notice. Take a specimen homogeneous data structure to specify the "shape" desired (length of lists, etc); then reads the given list of leaves in as a piece of homogeneous data of the same shape. The ordering of the leaves is assumed to be the same as that which  produces for the given shape.XA "length mismatch" error occurs if the list does not have exactly the required length.1Please note that, by contrast with the function , the first argument is a shape term parameter, not a shape type parameter. It is used to decide where the qubits should go in the data structure.Combine a shape type argument q, a leaf type argument a, and a shape size argument x into a single shape argument qx. Note:qI captures only the type, but not the size of the data. Only the type of q is used; its value can be undefined. This is sufficient to determine the depth of leaves in a data structure, but not their number.xG captures only the size of the data, but not its type. In particular, x& may have leaves of non-atomic types. xJ must consist of well-defined constructors up to the depth of leaves of q), but the values at the actual leaves of x may be undefined.  The output qx combines the type of q with the size of xe, and can therefore be used both as a shape type and a shape value. Note that the actual leaves of qx will be  and , which are synonyms for . Example: q = undefined :: ([Qubit], [[Qubit]]) x = ([undefined, 0], [[undefined], [0, 1]]) qdata_makeshape qc a x = ([qubit, qubit], [[qubit], [qubit, qubit]])where a :: Int.Like , except the leaves are visited in exactly the opposite order. This is used primarily for cosmetic reasons: For example, when initializing a bunch of ancillas, and then terminating them, the circuit will look more symmetric if they are terminated in the opposite order.Like (, except take a piece of classical data.The inverse of : Take a data structure whose leaves are pairs, and return two data structures of the same shape, collecting all the left components and all the right components, respectively. The first five arguments are shape type parameters, analogous to those of .Map two functions f and g; over the leaves of a heterogeneous data structure. Apply f to all the leaves at  positions, and g to all the leaves at $ positions. Non-monadic version of .qVisit every leaf in a data structure, updating an accumulator. This function requires two accumulator functions f and g, to be used at  positions and  positions, respectively.}Map a function over every leaf in a data structure, while also updating an accumulator. This combines the functionality of  and .Monadic version of t: Visit every leaf in a data structure, updating an accumulator. This function requires two accumulator functions f and g, to be used at  positions and  positions, respectively.Monadic version of : Map a function over every leaf in a data structure, while also updating an accumulator. This combines the functionality of  and .Return a list of leaves of the given heterogeneous data structure. The first argument is a dummy shape type parameter, and is only used for its type. Leaves in qubit positions and bit positions are returned, respectively, as the left or right components of a disjoint union.IThe leaves are ordered in some deterministic, but arbitrary way. It is guaranteed that when two data structures of the same shape type and shape (same length of lists etc) are sequentialized, the leaves will be ordered the same way. No other property of the order is guaranteed, In particular, it might change without notice.ETake a specimen heterogeneous data structure to specify the "shape" desired (length of lists, etc); then reads the given list of leaves in as a piece of heterogeneous data of the same shape. The ordering of the leaves, and the division of the leaves into qubit and bit positions, is assumed to be the same as that which  produces for the given shape.A "length mismatch" error occurs if the list does not have exactly the required length. A "shape mismatch" error occurs if the list contains an k entry corresponding to a  position in the shape, or an j entry corresponding to a  position.1Please note that, by contrast with the function , the first argument is a shape term parameter, not a shape type parameter. It is used to decide where the qubits and bits should go in the data structure. Combine a shape type argument q, two leaf type arguments a and b, and a shape size argument x into a single shape argument qx. Note:qI captures only the type, but not the size of the data. Only the type of q is used; its value can be undefined. This is sufficient to determine the depth of leaves in a data structure, but not their number.xG captures only the size of the data, but not its type. In particular, x& may have leaves of non-atomic types. xJ must consist of well-defined constructors up to the depth of leaves of q), but the values at the actual leaves of x may be undefined.  The output qx combines the type of q with the size of xe, and can therefore be used both as a shape type and a shape value. Note that the actual leaves of qx will be  and , which are synonyms for . Example: qc = undefined :: ([Qubit], [[Bit]]) x = ([undefined, (0,False)], [[undefined], [Just 2, Nothing]]) qcdata_makeshape qc a b x = ([qubit, qubit], [[bit], [bit, bit]])where a ::  (Int,Bool), b ::  (Maybe Int). Like , except the leaves are visited in exactly the opposite order. This is used primarily for cosmetic reasons: For example, when initializing a bunch of ancillas, and then terminating them, the circuit will look more symmetric if they are terminated in the opposite order.  Turn any w into a string uniquely identifying its type and shape. The current implementation assumes that appropriately unique  instances are defined for all .:   :   None=>?@ACHSVX]0The 0 type class is similar to the < type class, except that the result type is guarded by the  2 monad. It provides a family of type isomorphisms fun "E args -> Circ res,where Lfun = a1 -> a2 -> ... -> an -> Circ res, args = (a1, (a2, (..., (an, ())))).The benefit of having Circk in the result type is that it ensures that the result type is not itself a function type, and therefore fun has a unique arity n. Then args and res are uniquely determined by funB, which can be used to write higher-order operators that consume fun( of any arity and "do the right thing".3Initialize a qubit from a boolean parameter. More generally, initialize a data structure of qubits from a corresponding data structure of boolean parameters. Examples: Zq <- qinit False (q0, q1) <- qinit (True, False) [q0, q1, q2] <- qinit [True, False, True]4Terminate a qubit, asserting its state to equal the boolean parameter. More generally, terminate a data structure of qubits, asserting that their state is as given by a data structure of booleans parameters. Examples: Tqterm False q qterm (False, False) (q0, q1) qterm [False, False, False] [q0, q1, q2]In some cases, it is permissible for some aspect of the parameter's shape to be underspecified, e.g., a longer than necessary list, or an integer of indeterminate length. It is therefore possible, for example, to write: Uqterm 17 qa -- when qa :: QDInt, qterm [False..] qa -- when qa :: [Qubit].oThe rules for when a boolean argument can be "promoted" in this way are specific to each individual data type.5Discard a qubit, ignoring its state. This can leave the quantum system in a mixed state, so is not a reversible operation. More generally, discard all the qubits in a quantum data structure. Examples: 2qdiscard q qdiscard (q0, q1) qdiscard [q0, q1, q2]6 Initialize a  (boolean input) from a J (boolean parameter). More generally, initialize the a data structure of Bits from a corresponding data structure of Bools. Examples: Zb <- cinit False (b0, b1) <- cinit (True, False) [b0, b1, b2] <- cinit [True, False, True]7 Terminate a *, asserting its state to equal the given J. More generally, terminate a data structure of Bits, asserting that their state is as given by a data structure of Bools. Examples: Tcterm False b cterm (False, False) (b0, b1) cterm [False, False, False] [b0, b1, b2]In some cases, it is permissible for some aspect of the parameter's shape to be underspecified, e.g., a longer than necessary list, or an integer of indeterminate length. It is therefore possible, for example, to write: Rcterm 17 ca -- when ca :: CInt, cterm [False..] ca -- when ca :: [Bit].oThe rules for when a boolean argument can be "promoted" in this way are specific to each individual data type.8 Discard a , ignoring its state. This can leave the system in a mixed state, so is not a reversible operation. More generally, discard all the Bits in a data structure. Examples: 2cdiscard b cdiscard (b0, b1) cdiscard [b0, b1, b2]9Heterogeneous version of 3|. Please note that the type of the result of this function cannot be inferred from the type of the argument. For example,  x <- qc_init FalseBis ambiguous, unless it can be inferred from the context whether x is a  or a `. If the type cannot be inferred from the context, it needs to be stated explicitly, like this:  x <- qc_init False :: Circ QubitAlternatively, :% can be used to fix a specific type.: A version of 9* that uses a shape type parameter. The first argument is the shape type parameter, and the second argument is a data structure containing boolean initializers. The shape type argument determines which booleans are used to initialize qubits, and which ones are used to initialize classical bits.Example: >(x,y) <- qc_init_with_shape (bit,[qubit]) (True, [False,True])This will assign to x+ a classical bit initialized to 1, and to y? a list of two qubits initialized to |0#* and |1#*, respectively.;Heterogeneous version of 4. <Heterogeneous version of 5.= Measure a , resulting in a . More generally, measure all the Qubits in a quantum data structure, resulting in a corresponding data structure of Bits. This is not a reversible operation. Examples: Pb <- measure q (b0, b1) <- measure (q0, q1) [b0, b1, b2] <- measure [q0, q1, q2]> Prepare a  initialized from a z. More generally, prepare a data structure of Qubits, initialized from a corresponding data structure of Bits. Examples: Pq <- prepare b (q0, q1) <- prepare (b0, b1) [q0, q1, q2] <- prepare [b0, b1, b2]?Heterogeneous version of =l. Given a heterogeneous data structure, measure all of its qubits, and leave any classical bits unchanged.@Heterogeneous version of >q. Given a heterogeneous data structure, prepare qubits from all classical bits, and leave any qubits unchanged.ALike 8, except the gate is also "anchored" at a qubit, a bit, or more generally at some quantum data. The anchor is only used as a hint for graphical display. The gate, which is a zero-qubit gate, will potentially be displayed near the anchor(s).BAApply a Hadamard gate to every qubit in a quantum data structure.CImperative version of B.DApply a swap gate to two qubits. More generally, apply swap gates to every corresponding pair of qubits in two pieces of quantum data.EApply a swap gate to two qubits. More generally, apply swap gates to every corresponding pair of qubits in two pieces of quantum data.FApply a controlled-not gate to every corresponding pair of quantum or classical bits in two pieces of QCData. The first argument is the target and the second the (positive) control. For now, we require both pieces of QCData to have the same type, i.e., classical bits can be controlled only by classical bits and quantum bits can be controlled only by quantum bits.Example: .((a',b'), (x,y)) <- controlled_not (a,b) (x,y)is equivalent to 7a' <- qnot a `controlled` x b' <- qnot b `controlled` yGImperative version of F. Apply a controlled-not gate to every corresponding pair of quantum or classical bits in two pieces of QCData. The first argument is the target and the second the (positive) control.H A version of F6 where the control consists of boolean data. Example: 1bool_controlled_not (q, r, s) (True, True, False)negates q and r , but not s.I A version of G6 where the control consists of boolean data. Example: 4bool_controlled_not_at (q, r, s) (True, True, False)negates q and r , but not s.J.Negate all qubits in a quantum data structure.K.Negate all qubits in a quantum data structure.LmInitialize a new piece of quantum data, as a copy of a given piece. Returns both the original and the copy.MGiven two pieces of quantum data, assumed equal (w.r.t. the computational basis), terminate the second piece (and return the first, unmodified). This is the inverse of L`, in the sense that the following sequence of instructions behaves like the identity function: @(orig, copy) <- qc_copy_fun orig orig <- qc_uncopy_fun orig copyNCreate a fresh copy of a piece of quantum data. Note: copying is performed via a controlled-not operation, and is not cloning. This is similar to L9, except it returns only the copy, and not the original.O1"Uncopy" a piece of quantum data; i.e. terminate copy, assuming it's a copy of orig. This is the inverse of N_, in the sense that the following sequence of instructions behaves like the identity function: b <- qc_copy a qc_uncopy a bPIf a is Y, return a copy of b, else return a copy of c. Here b and c5 can be any data structures consisting of Bits, but b and co must be of the same type and shape (for example, if they are lists, they must be of equal length). Examples: output <- cgate_if a b c (out0, out1) <- cgate_if a (b0, b1) (c0, c1) [out0, out1, out2] <- cgate_if a [b0, b1, b2] [c0, c1, c2]QQN is an if-then-else function for classical circuits. It is a wrapper around P , intended to be used like this: Oresult <- circ_if <<<condition>>> ( <<then-part>>> )( <<<else-part>>> )Unlike Pr, this is a meta-operation, i.e., the bodies of the "then" and "else" parts can be circuit building operations. bWhat makes this different from the usual boolean "if-then-else" is that the condition is of type _, i.e., it is only known at circuit execution time. Therefore the generated circuit contains both the "then" and "else" parts, suitably controlled. Precondition: the "then" and "else" parts must be of the same type and shape.R<Define a new functional-style gate of the given name. Like T, except that the generated gate is extended with "generalized controls". The generalized controls are additional inputs to the gate that are guaranteed not to be modified if they are in a computational basis state. They are rendered in a special way in circuit diagrams. Usage: amy_new_gate :: (Qubit,Qubit) -> Qubit -> Circ (Qubit,Qubit) my_new_gate = extended_named_gate "Q"NThis defines a new gate with name "Q", two inputs, and one generalized input.SLike R2, except defines an imperative style gate. Usage: _my_new_gate_at :: (Qubit,Qubit) -> Qubit -> Circ () my_new_gate_at = extended_named_gate_at "Q"NThis defines a new gate with name "Q", two inputs, and one generalized input.T<Define a new functional-style gate of the given name. Usage: Cmy_unary_gate :: Qubit -> Circ Qubit my_unary_gate = named_gate "Q" Wmy_binary_gate :: (Qubit, Qubit) -> Circ (Qubit, Qubit) my_binary_gate = named_gate "R"This defines a new unary gate and a new binary gate, which will be rendered as "Q" and "R", respectively, in circuit diagrams. U<Define a new imperative-style gate of the given name. Usage: Imy_unary_gate_at :: Qubit -> Circ () my_unary_gate_at = named_gate_at "Q" Tmy_binary_gate_at :: (Qubit, Qubit) -> Circ () my_binary_gate_at = named_gate_at "R"This defines a new unary gate and a new binary gate, which will be rendered as "Q" and "R", respectively, in circuit diagrams. VDefine a new functional-style gate of the given name, and parameterized by a real-valued parameter. This is typically used for rotations or phase gates that are parameterized by an angle. The name can contain '%' as a place holder for the parameter. Usage: Umy_unary_gate :: Qubit -> Circ Qubit my_unary_gate = named_rotation "exp(-i%Z)" 0.123 nmy_binary_gate :: TimeStep -> (Qubit, Qubit) -> Circ (Qubit, Qubit) my_binary_gate t = named_rotation "Q(%)" tWDefine a new imperative-style gate of the given name, and parameterized by a real-valued parameter. This is typically used for rotations or phase gates that are parameterized by an angle. The name can contain '%' as a place holder for the parameter. Usage: Xmy_unary_gate_at :: Qubit -> Circ () my_unary_gate_at = named_rotation "exp(-i%Z)" 0.123 hmy_binary_gate_at :: TimeStep -> (Qubit, Qubit) -> Circ () my_binary_gate_at t = named_rotation "Q(%)" tX Convert a  (boolean circuit output) to a Jt (boolean parameter). More generally, convert a data structure of Bits to a corresponding data structure of Bools.For use in algorithms that require the output of a measurement to be used as a circuit-generation parameter. This is the case, for example, for sieving methods, and also for some iterative algorithms.Note that this is not a gate, but a meta-operation. The input consists of classical circuit endpoints (whose values are known at circuit execution time), and the output is a boolean parameter (whose value is known at circuit generation time). The use of this operation implies an interleaving between circuit execution and circuit generation. It is therefore a (physically) expensive operation and should be used sparingly. Using the X operation interrupts the batch mode operation of the quantum device (where circuits are generated ahead of time), and forces interactive operation (the quantum device must wait for the next portion of the circuit to be generated). This operation is especially expensive if the current circuit contains unmeasured qubits; in this case, the qubits must be preserved while the quantum device remains on standby.Also note that this operation is not supported in all contexts. It is an error, for example, to use this operation in a circuit that is going to be reversed, or in the body of a boxed subroutine. Also, not all output devices (such as circuit viewers) support this operation.YAMap a single qubit gate across every qubit in the data structure.ZkMap a binary gate across every corresponding pair of qubits in two quantum data structures of equal shape.[Like Z0, except the second data structure is classical.\Map a binary qubit circuit to every pair of qubits in the quantum data-type. It is a run-time error if the two structures do not have the same size.]Heterogeneous version of Z. Map a binary gate f? across every corresponding pair of qubits, and a binary gate gZ across every corresponding pair of bits, in two quantum data structures of equal shape.^iReturn the list of qubits representing the given quantum data. The qubits are ordered in some fixed, but arbitrary way. It is guaranteed that two pieces of qdata of the same given shape will be ordered in the same way. No other property of the order is guaranteed, In particular, the order may change without notice from one version of Quipper to the next._Take a specimen piece of quantum data to specify the "shape" desired (length of lists, etc); then reads the given list of qubits in as a piece of quantum data of the same shape. The ordering of the input qubits is the same as ^ produces for the given shape.XA "length mismatch" error occurs if the list does not have exactly the required length.`@Return the list of endpoints that form the leaves of the given *. The leaves are ordered in some fixed, but arbitrary way. It is guaranteed that two pieces of data of the same given shape will be ordered in the same way. No other property of the order is guaranteed. In particular, the order may change without notice from one version of Quipper to the next.aTake a specimen piece of  to specify the "shape" desired (length of lists, etc); then reads the given list of endpoints in as a piece of quantum data of the same shape. The ordering of the input endpoints equals that produced by ` for the given shape.A "length mismatch" error occurs if the list does not have exactly the required length. A "shape mismatch" error occurs if the list contains a  when a  was expected, or vice versa. Take a specimen piece of  to specify a shape; return a  that structures appropriate lists of wires with arities into data of this shape, and conversely destructures data of this shape into wires and an arity.The caveats mentioned in `" apply equally for this function.bTReturn a boolean data structure of the given shape, with every leaf initialized to [.cvReturn a quantum data structure of the given boolean shape, with every leaf initialized to the undefined dummy value .dTake two pieces of quantum data of the same shape (the first of which consists of wires of a low-level circuit) and create bindings.esApply bindings to a piece of quantum and/or classical data holding low-level wires, to get data of the same shape.EGiven a piece of quantum data and a possible value for it, return a B representing the condition that the quantum data has that value.If some aspect of the value's shape is indeterminate, it is promoted to the same shape as the quantum data; therefore, it is possible, for example, to write: ]qc_control qa 17 -- when qa :: QDInt qc_control qa [False..] -- when qa :: [Qubit]fZThis is an infix operator to concatenate two controls, forming their logical conjunction.g (qx .==. x)/: a control which is true just if quantum data qx is in the specified state x. h The notation  (q ./=. x) is shorthand for (q .==. not x), when x is a boolean parameter. Unlike g3, which is defined for any shape of quantum data, h3 is only defined for a single control bit or qubit.rAllocate new quantum data of the given shape, in the given arity. Returns the quantum data and the updated arity.ieExtract an encapsulated circuit from a circuit-generating function. This requires a shape parameter.jAs iq, but passes the current namespace into the circuit-generating function, to save recomputing shared subroutineskFTurn an encapsulated circuit back into a circuit-generating function.lmExtract an encapsulated dynamic circuit from a circuit-generating function. This requires a shape parameter.mNTurn an encapsulated dynamic circuit back into a circuit-generating function.This currently fails if the dynamic circuit contains output liftings, because the transformer interface has not yet been updated to work with dynamic circuits.Like ', but also takes a stub error message. ^Reverse a non-curried circuit-generating function. The second parameter is a shape parameter.nReverse a circuit-generating function. The reversed function requires a shape parameter, given as the input type of the original function.vThe type of this highly overloaded function is quite difficult to read. It can have for example the following types: reverse_generic :: (QCData x, QCData y) => (x -> Circ y) -> x -> (y -> Circ x) reverse_generic :: (QCData x, QCData y, QCData z) => (x -> y -> Circ z) -> x -> y -> (z -> Circ (x,y)) oLike nb, but takes functions whose output is a tuple, and curries the reversed function. Differs from n in an example such as: f :: (x -> y -> Circ (z,w)) reverse_generic f :: x -> y -> ((z,w) -> Circ (x,y)) reverse_generic_curried f :: x -> y -> (z -> w -> Circ (x,y))Note: the output must be a n-tuple, where n = 0 or nc "e 2. Applying this to a circuit whose output is a non-tuple type is a type error; in this case, n should be used.pLike ng, but only works at simple types, and therefore requires no shape parameters. Typical type instances: reverse_simple :: (QCData_Simple x, QCData y) => (x -> Circ y) -> (y -> Circ x) reverse_simple :: (QCData_Simple x, QCData_Simple y, QCData z) => (x -> y -> Circ z) -> (z -> Circ (x,y))qLike pi, but takes functions whose output is a tuple, and curries the reversed function. Typical type instance: jreverse_simple_curried :: (QCData_Simple x, QCData y, QCData z) => (x -> Circ (y,z)) -> (y -> z -> Circ x)Note: the output must be a n-tuple, where n = 0 or nc "e 2. Applying this to a circuit whose output is a non-tuple type is a type error; in this case, n should be used.rLike n, but specialized to endomorphic circuits, i.e., circuits where the input and output have the same type (modulo possibly currying) and shape. In this case, unlike n, no additional shape parameter is required, and the reversed function is curried if the original function was. Typical type instances: reverse_generic_endo :: (QCData x) => (x -> Circ x) -> (x -> Circ x) reverse_generic_endo :: (QCData x, QCData y) => (x -> y -> Circ (x,y)) -> (x -> y -> Circ (x,y))sLike r_, but applies to endomorphic circuits expressed in "imperative" style. Typical type instances: reverse_generic_endo :: (QCData x) => (x -> Circ ()) -> (x -> Circ ()) reverse_generic_endo :: (QCData x, QCData y) => (x -> y -> Circ ()) -> (x -> y -> Circ ())tConditional version of rn. Invert the endomorphic quantum circuit if the boolean is true; otherwise, insert the non-inverted circuit.uConditional version of ss. Invert the imperative style quantum circuit if the boolean is true; otherwise, insert the non-inverted circuit.Like v&, but also takes a stub error message.vLike {0, but applies to arbitrary transformers of type Transformer m a binstead of the special case Transformer Circ Qubit Bit.,This requires an additional shape argument. w)Apply the given transformer to a circuit.x8Like transform_unary_shape but for a dynamic transformery2Like transform_unary but for a dynamic transformerzLike {0, but applies to arbitrary transformers of type Transformer m a binstead of the special case Transformer Circ Qubit Bit.,This requires an additional shape argument. }The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: ltransform_generic :: (QCData x) => Transformer m a b -> Circ x -> m (QCData a b x) transform_generic :: (QCData x, QCData y) => Transformer m a b -> (x -> Circ y) -> x -> (QCData a b x -> m (QCData a b y)) transform_generic :: (QCData x, QCData y, QCData z) => Transformer m a b -> (x -> y -> Circ z) -> x -> y -> (QCData a b x -> QCData a b y -> m (QCData a b z)) and so forth.{3Apply the given transformer to a circuit. Unlike wV, this function can be applied to a circuit-generating function in curried form with n arguments, for any n "e 0.}The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: 9transform_generic :: (QCData x) => Transformer Circ Qubit Bit -> Circ x -> Circ x transform_generic :: (QCData x, QCData y) => Transformer Circ Qubit Bit -> (x -> Circ y) -> (x -> Circ y) transform_generic :: (QCData x, QCData y, QCData z) => Transformer Circ Qubit Bit -> (x -> y -> Circ z) -> (x -> y -> Circ z) and so forth.|+Execute a block with local ancillas. Opens a block, initializing an ancilla with a specified classical value, and terminates it with the same value when the block closes. Note: it is the programmer's responsibility to return the ancilla to its original state at the end of the enclosed block. Usage: \with_ancilla_init True $ \a -> do { <<<code block using ancilla a initialized to True>>> } with_ancilla_init [True,False,True] $ \a -> do { <<<code block using list of ancillas a initialized to [True,False,True]>>> }}Like u, but creates a list of n* ancillas, all initialized to |0#*. Usage: Nwith_ancilla_list n $ \a -> do { <<<code block using list of ancillas a>>> }~~ x f g : computes  x' := f(x); then computes g(x')&, which should be organized as a pair (x',y); then uncomputes x' back to x, and returns (x,y).<Important subtlety in usage: all quantum data referenced in f=, even as controls, must be explicitly bound and returned by f/, or the reversing may rebind it incorrectly. gO, on the other hand, can safely refer to anything that is in scope outside the ~.  computation code : performs  computation (with result x), then performs code x', and finally performs the reverse of  computation, for example like this:[image with_computed.png]Both  computation and codeg may refer to any qubits that exist in the current environment, and they may also create new qubits.  computation; may produce arbitrary garbage in addition to its output. This is a very general but relatively unsafe operation. It is the user's responsibility to ensure that the computation can indeed be undone. In particular, if  computation% contains any initializations, then codeE must ensure that the corresponding assertions will be satisfied in  computation [sup "1].ARelated more specialized, but potentially safer, operations are: , which is like , but assumes that  computation is unitary, and1=, which assumes that  computation* is classical (or pseudo-classical), and code/ is a simple copy-by-controlled-not operation.  basischange code%: performs a basis change, then the code., then the inverse of the basis change. Both  basischange and codeW are in imperative style. It is the user's responsibility to ensure that the image of code is contained in the image of  basischangeC, or else there will be unmet assertions or runtime errors. Usage: Ywith_basis_change basischange $ do <<<code>>> where basischange = do <<<gates>>>Bind a name to a function as a subroutine in the current namespace. This requires a shape argument, as well as complete parameters, so that it is uniquely determined which actual circuit will be the subroutine. It is an error to call that subroutine later with a different shape argument. It is therefore the user's responsibility to ensure that the name is unique to the subroutine, parameters, and shape. `This function does nothing if the name already exists in the namespace; in particular, it does notF check whether the given function is equal to the stored subroutine. -A generic interface for wrapping a circuit-generating function into a boxed and named subroutine. This takes a name and a circuit-generating function, and returns a new circuit-generating function of the same type, but which inserts a boxed subroutine instead of the actual body of the subroutine.$It is intended to be used like this: somefunc :: Qubit -> Circ Qubit somefunc a = do ... somefunc_boxed :: Qubit -> Circ Qubit somefunc_boxed = box "somefunc" somefuncHere, the type of somefunc is just an example; this could indeed be a function with any number and type of arguments, as long as the arguments and return type are quantum data."It is also possible to inline the ? operator directly, in which case it should be done like this: Hsomefunc :: Qubit -> Circ Qubit somefunc = box "somefunc" $ \a -> do ... Note: The q operator wraps around a complete function, including all of its arguments. It would be incorrect to apply the d operator after some quantum variables have already been defined. Thus, the following is incorrect: Xincorrect_somefunc :: Qubit -> Circ Qubit incorrect_somefunc a = box "somefunc" $ do ...XIt is the user's responsibility not to use the same name for different subroutines. If  is called more than once with the same name and shape of input, Quipper assumes, without checking, that they are subsequent calls to the same subroutine. The type of the c operator is overloaded and quite difficult to read. It can have for example the following types: box :: String -> (Qubit -> Circ Qubit) -> (Qubit -> Circ Qubit) box :: String -> (QDInt -> QDInt -> Circ (QDInt,QDInt,QDInt)) -> (QDInt -> QDInt -> Circ (QDInt,QDInt,QDInt)) A version of < with iteration. The second argument is an iteration count.kThis can only be applied to functions of a single argument, where the input and output types are the same. A version of  with same type as +. A version of +I that will be boxed conditionally on a boolean condition. Typical usage: DloopM_boxed_if (s > 1) "name" s x $ \x -> do <<<body>>> return x!The underlying implementation of  and . It behaves like 6, but is restricted to unary functions, and takes an  argument.Classical control on a function with same shape of input and output: if the control bit is true the function is fired, otherwise the identity map is used. Note: the constraint on the types is dynamically checked.Like kf, except inline the subroutine body from the given namespace, instead of inserting a subroutine call.+Implementation note: this currently copies all subroutine definitions from the given namespace into the current namespace, and not just the ones used by the current subroutine.EImplementation note: this currently only works on lists of endpoints.X0213456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~X3456789:;<=>?@ABCDEFGHIJKLMNOPQTUVWRSXYZ[\]^_`abcdefghijklmnopqrstu021xyw{vz|}~f3g4h4None ,=>?@AHV8U(This is a quantum analogue of Haskell's \ type class. Its purpose is to define a total ordering on each of its instances. The functions in this class are assumed dirty in the sense that they do not uncompute ancillas, and some of the inputs may be returned as outputs. The functions are also assumed to be non-linear safe, i.e., they apply no gates to their inputs except as control sources. Minimal complete definition:  or ". The default implementations of  and ] assume that both arguments are of the same shape (for example, numbers of the same length).Test for less than. Test for greater than.Test for less than or equal.Test for greater than or equal."Compute the maximum of two values."Compute the minimum of two values.(This is a quantum analogue of Haskell s  type class. Default implementations are provided; by default, equality is bitwise equality of the underlying data structure. However, specific instances can provide custom implementations. In this case, " is a minimal complete definition.Test for equality. Test for inequality. qx qy: test whether qx < qy$. A functionally typed wrapper for . qx qy: test whether qx > qy#. A functionally typed wrapper for . qx qy: test whether qx "d qy#. A functionally typed wrapper for . qx qy: test whether qx "e qy#. A functionally typed wrapper for .None>HV .Available output formats.!Encapsulated PostScript graphics./Portable Document Format. One circuit per page.!PostScript. One circuit per page.%A textual representation of circuits.TDon't print anything, but preview directly on screen (requires the external program acroread). Print statistics on gate counts.$Annotated gate counts of circuits. Gate counts of circuits. A data type analogous to &, but with extra annotations, e.g. a  ,, for use in the computation of gate counts.[A data type representing equivalence classes of basic gates, for the output of gatecounts.vAn abbreviated representation of the controls of a gate: the number of positive and negative controls, respectively.A @ is a map from wire id's to pairs of a wiretype and a starting x -coordinate.7A data type that holds all the customizable parameters.The RenderFormat to use.The color of the background.3The color of the foreground (e.g. wires and gates). Line width./Gap for double line representing classical bit.&Radius of dots for "controlled" gates.Radius of oplus for "not" gate.Horizontal column width.3Difference between width of box and width of label.Height of labelled box.*Width and height of "cross" for swap gate.Vertical shift for text labels.Width of "bar" bar.Height of "bar" bar.Width of "D" symbol.Height of "D" symbol.Maximal width of a gate label.Maximal width of a wire label.Maximal width of a wire number. Font to use for labels on gates.Font to use for comments.Color to use for comments.Font to use for labels.Color to use for labels.Font to use for numbers.Color to use for numbers.;Whether to label each subroutine call with shape parametersDetermine whether a named gate is self-inverse. The kind of a gate is uniquely determined by its name, and the number of input wires and generalized controls.For now, we only recognize "X", "Y", "Z", "H", "not", "swap", and "W" as self-inverse; it is not currently possible for user code to extend this list.]Given a map of wiretypes, and a gate, update the wiretype in the map if the gate changes it. Convert a  to the string in the format "name ", shape "x".Generate an ASCII representation of a control. As controls are stored as untyped wires, we can lookup the wiretype in the current map and annotate the control if it's classical.7Generate an ASCII representation of a list of controls.3Generate an ASCII representation of a NoControlFlag2Generate an ASCII representation of a single gate.0Generate an ASCII representation of a gate list./Generate an ASCII representation of a wiretype.6Generate an ASCII representation of a type assignment.UGenerate an ASCII representation of an arity, preceded by a title (input or output).]Generate an ASCII representation of an ordered arity, preceded by a title (input or output).IGenerate an ASCII representation of a low-level ordered quantum circuit.@Generate an ASCII representation of a low-level quantum circuit.GGenerate an ASCII representation of a low-level boxed quantum circuit.7Generate an ASCII representation of a named subroutine.~Write a prompt to get input from the user. Since the prompt doesn't include a newline, the output must be flushed explicitly.,Interactively read a bit (either 0 or 1) from standard input. This is intended for interactive user input, so it skips white space until a 0 or 1 is encountered. In case the first non-whitespace character isn't 0 or 1 or '#', the rest of the line is ignored and the user is prompted to try again.However, this also works for non-interactive input, so that the input can be redirected from a file. In this case, the characters 0 and 1 and whitespace, including newlines, can be interspersed freely. '#<' starts a comment that extends until the end of the line. &Embed a read-write computation in the  monad, by writing gates to the terminal and interactively querying the user (or a file on stdin) for dynamic liftings. We also update a M while doing so, to collect any subroutines that are defined along the way.Interactively output a  to standard output. This supports dynamic lifting by prompting the user for bit values when a dynamic lifting operation is encountered. Effectively the user is asked to behave like a quantum device.The color white.The color black.ZA RenderFormat consisting of some default parameters, along with the given RenderFormat.The default PDF Style.The default EPS Style.The default PS Style..Escape special characters in a string literal. Convert a  to the string in the format "name, shape x".Pre-processing: figure out the x -column of each gate. Returns (n,xgs) where xgs is a list of (, ) pairs, and n is the rightmost x0-coordinate of the circuit. Here we start from x0 and use constant step xoff taken from the .$Figure out how a gate at coordinate x affects the current . Return a pair (term, new ), where term is the ( of wires terminated by this gate, and new is the outgoing  of this gate. x0 y0 x1 y1: Draw a line from (x0, y0) to (x1, y1/). In case of a zero-length line, draw nothing. x y : Draw a filled control dot at (x,y). x y!: Draw an empty control dot at (x,y). x y: Draw a "not" gate at (x,y). x y+: Draw a cross (swap gate component) at (x,y). x y: Draw an init term bar at (x,y/). x y: Draw a dterm bar at (x,y). name x y: Draw an "init" gate at (x,y), with state name. name x y: Draw a "term" gate at (x,y), with state name. name x y: Draw a "dterm" gate at (x,y), with state name. name inv x y!: draw a named box centered at (x,y). If inv = Y5, append an "inverse" symbol to the end of the name. name x y): draw a global phase gate centered at (x,y). name x y": draw a named oval centered at (x,y). name x y": draw an empty box centered at (x,y), big enough to hold name. center s x y mP: draw the given string vertically, with the top of the string near the given y-coordinate. If center==Y, center it at the x3-coordinate, else move it just to the left of the x -coordinate. m/ is the maximum height allowed for the comment. center s x y7: draw the given label just above the given point. If center==Y, center it at the x4-coordinate, else move it just to the right of the x -coordinate.&Render the number at the given point (x,y). If the boolean argument is Y!, put the number to the right of x, else to the left. Render a horizontal wire from x -coordinates oldx to x , using t" as the type and figuring out the y-coordinate from ys and w>. Append to the given string. If the parameters are invalid (w not in ys), throw an error.CRender a bunch of horizontal wires from their respective starting  to x.GFormat a floating point number in concise form, with limited accuracy. x ys ws c^: Render the line connecting all the box components and all the control dots of some gate.  Parameters: x is the current x -coordinate, ys is an indexed array of y-coordinates, ws% is the set of wires for boxes, and c is a list of controls. x ys y c: Render the line connecting all control dots of the given controls, as well as a floating "global phase" gate located just below (x, y).  Parameters: x is the current x -coordinate, ys is an indexed array of y-coordinates, y is the yB-coordinate of the wire where the floating gate is attached, and c is a list of controls. x ys c2: Render the control dots for the given controls. x ys name inv wires: Render the boxes for an n-ary gate of the given name, potentially inverted, at the given list of wires+. The first two arguments are the current x%-coordinate and an indexed array of y -coordinates. x ys wires namesC: Render the boxes for multiple generalized controls at the given wires, using the given namesX. We take special care of the fact that generalized controls may be used non-linearly.  x ys wiresN: Render the boxes for multiple (numbered) generalized controls at the given wires.:Number a list of wires in increasing order, at the given x(-coordinate. If the boolean argument is Y#, put the numbers to the right of x, else to the left. Render gate g at x -coordinate x and y-coordinates as given by ys , which is a map from wires to y-coordinates. Returns a pair (s,t?) of draw actions for background and foreground, respectively.5Render the gates in the circuit. The parameters are: xarity: the ! of the currently pending wires. xgs/: the list of gates, paired with pre-computed x-coordinates. ys$: a map from wires to pre-computed y-coordinates. x: the right-most x4-coordinate where the final wires will be drawn to. maxh": the maximal height of comments.-PostScript definitions of various parameters.VPostScript definitions for various drawing subroutines. The subroutines provided are: <x0 y0 x1 y1 line : draw a line from (x0,y0) to (x1,y1) x0 y0 x1 y1 dashedline : draw a dashed line from (x0,y0) to (x1,y1) x y h w rect : draw a rectangle of dimensions w x h centered at (x,y) x y h w oval : draw an oval of dimensions w x h centered at (x,y) x y dot : draw a filled dot at (x,y) x y circ : draw an empty dot at (x,y) x y oplus : draw a "not" gate at (x,y) x y cross : draw a cross ("swap" gate component) at (x,y) x y bar : draw an init/term bar at (x,y) x y dbar : draw a dterm bar at (x,y) name x y box : draw an empty box at (x,y), big enough to fit name name x y gate : draw a named box at (x,y) name x y circgate : draw a named round box at (x,y) name x y gphase : draw a global phase gate (x,y) b x y init : draw an "init" gate at (x,y), with state b b x y term : draw a "term" gate at (x,y), with state b b x y dterm : draw a "dterm" gate at (x,y), with state b string x y m b comment : draw a vertical comment at (x,y), with max height m and baseline adjustment b string x y clabel : draw a wire label at (x,y), x-centered string x y rlabel : draw a wire label at (x,y), right of x string x y lnumber : draw a numbered input at (x,y) string x y rnumber : draw a numbered output at (x,y) name ocirc: Render the circuit ocirc on a single page.BThe rendering takes place in the following user coordinate system:[image coord.png]9Render a low-level boxed quantum circuit as a graphical G. If there are subroutines, each of them is placed on a separate page.;Render a low-level dynamic quantum circuit as a graphical . If there are subroutines, each of them is placed on a separate page. If the circuit uses dynamic lifting, an error is produced. Print a representation of a low-level quantum circuit, in the requested graphics format, directly to standard output. If there are boxed subcircuits, each of them is placed on a separate page. Print a representation of a low-level dynamic quantum circuit, in the requested graphics format, directly to standard output. If there are boxed subcircuits, each of them is placed on a separate page. If the circuit uses dynamic lifting, an error is produced. Display a document directly in Acrobat Reader. This may not be portable. It requires the external program "acroread" to be installed. Display a document directly in Acrobat Reader. This may not be portable. It requires the external program "acroread" to be installed. Display the circuit directly in Acrobat Reader. This may not be portable. It requires the external program "acroread" to be installed.Display a low-level dynamic quantum circuit directly in Acrobat Reader. This may not be portable. It requires the external program "acroread" to be installed. If the circuit uses dynamic lifting, an error is produced.OFrom a list of controls, extract the number of positive and negative controls.,Convenience constant for uncontrolled gates.Forget the annotations of an jAdd controls to an annotated gate type, or throw an error message if it is not controllable; unless its  * is set, in which case leave it unchanged.KReverse an annotated gate type, of throw an error if it is not reversible. Set the   of an annotated gate type to Y.Helper function for ': append a formatted arity to a string.8Convert a given low-level gate to an annotated gate type/Convert a gate type to a human-readable string.Given the (annotated) gatecount of a circuit, return the gatecount of the reverse circuit, or throw an error if any component is not reversible.Given the (annotated) gatecount of a circuit, return the gatecount of the same circuit with controls added, or throw an error if any component is not controllable.+Set the ncf of all gates in a gatecount to Y.(Remove the annotations from a gatecount.GInput a list of items and output a map from items to counts. Example: 7count ['a', 'b', 'a'] = Map.fromList [('a',2), ('b',1)]rCount the number of gates of each type in a circuit, with annotations, treating subroutine calls as atomic gates.`Count the number of gates of each type in a circuit, treating subroutine calls as atomic gates. Given an  describing a subroutine call (possibly repeated), and a gate count for the subroutine itself, return the gatecount of the subroutine call.T(This may be the reverse of the original subroutine, may have controls added, etc.) eGiven a circuit and gatecounts for its subroutines, give an (aggregated) gatecount for the circuit.!#Give the aggregate gate count of a V; that is, the the total count of basic gates once all subroutines are fully inlined."LCount by how much a low-level gate changes the number of wires in the arity.#:Find the maximum number of wires used simultaneously in a %, assuming all subroutines inlined. $eGiven a circuit and gatecounts for its subroutines, give an (aggregated) gatecount for the circuit.%;Print a gate count, as a table of integers and gate types. &LPrint the simple gate count, plus summary information, for a simple circuit.'Print gate counts for a boxed circuit: first the simple gate count for each subroutine separately, then the aggregated count for the whole circuit.()Print gate counts for a named subroutine.)Print gate counts for a static R. The circuit may not use any dynamic lifting, or else an error will be produced.*fA mapping from lower-case strings (to be used, e.g., with command line options) to available formats.+XPrint a low-level quantum circuit directly to the IO monad, using the specified format.,@Print a document to the requested format, which must be one of , , , or .-Like ,, but also takes a  data structure..Like /&, but also takes a stub error message./^Print a circuit generating function to the specified format; this requires a shape parameter.0EPrint a circuit generating function to the specified format. Unlike /M, this can be applied to a circuit-generating function in curried form with n arguments, for any n >= 0. It then requires n shape parameters.}The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: print_generic :: Format -> Circ qa -> IO () print_generic :: (QCData qa) => Format -> (qa -> Circ qb) -> a -> IO () print_generic :: (QCData qa, QCData qb) => Format -> (qa -> qb -> Circ qc) -> a -> b -> IO () and so forth.1Like 0N, but only works at simple types, and therefore requires no shape parameters.      !"#$%&'()*+,-./01      !"#$%&'()*+,-./01None>HV SK:A R to eliminate all Bs style gates, such as "and", "or", "not", "xor", "eq", and "if-then-else" gates, and replace them by equivalent C and D gates.;GAuxiliary function: compute the reversible circuit corresponding to a B5 of the given name, using only controlled-not gates.<QTranslate all classical gates in a circuit into equivalent controlled-not gates.uThe type of this overloaded function is difficult to read. In more readable form, it has all of the following types: classical_to_cnot :: (QCData qa) => Circ qa -> Circ qa classical_to_cnot :: (QCData qa, QCData qb) => (qa -> Circ qb) -> (qa -> Circ qb) classical_to_cnot :: (QCData qa, QCData qb, QCData qc) => (qa -> qb -> Circ qc) -> (qa -> qb -> Circ qc)and so forth. ="Map an endpoint to the underlying * in the trivial case. Auxiliary function.>A RJ to replace all classical gates in a circuit by equivalent quantum gates.?EReplace all classical gates in a circuit by equivalent quantum gates.@EReplace all classical gates in a circuit by equivalent quantum gates.uThe type of this overloaded function is difficult to read. In more readable form, it has all of the following types: $classical_to_quantum :: (QCData qa) => Circ qa -> Circ (QType qa) classical_to_quantum :: (QCData qa, QCData qb) => (qa -> Circ qb) -> (QType qa -> Circ (QType qb)) classical_to_quantum :: (QCData qa, QCData qb, QCData qc) => (qa -> qb -> Circ qc) -> (QType qa -> QType qb -> Circ (QType qc))and so forth. AGeneric function for turning a classical (or pseudo-classical) circuit into a reversible circuit. The input is a classical boolean function x ! f(x), given as a not necessarily reversible circuit (however, the circuit should be one-to-one, i.e., no "garbage" should be explicitly erased). The output is the corresponding reversible function (x,y) ! (x,y " f(x)). qa and qb. can be any quantum data types. The function A7 does not itself change classical bits to qubits; use @ for that.:;<=>?@A:;<=>?@ANone=>?@ACHVX xBThe KT function produces (and also requires) functions with somewhat unwieldy types. The Bs class defines generic functions for unpacking these types into a more useable format, and for packing them back. For example,   (qa ->   (qb ->   qd)) unpacks into the type  qa -> qb ->   qd. Note that D and Cf do not in general form an isomorphism, just a retraction of the packed type onto the unpacked type.EAA custom-design boolean type, not modified by circuit generation.H Type-cast from BoolParam to BoolILifted version of PFalse.JLifted version of PTrue.KyInput the syntax tree of a classical function, and output the syntax tree of a corresponding quantum function. The type J is mapped to  ; the type E& is unchanged; and and each function f : a ! b is mapped to a function f' : a' !   b', where a' and b'$ are the translations of the types a and b, respectively. The function K/ knows about many built-in operations such as  and 0, whose circuit translations are defined below.LLifted version of H: newBool :: BoolParam -> Bool.:Depending on the boolean parameter, the circuit is either  0 |--or 1 |--MLifted version of [: False :: Bool.The circuit is (0 |-- output: quantum bit in state |0>NLifted version of Y:  True :: Bool.The circuit is (1 |-- output: quantum bit in state |1>OLifted version of : not :: Bool -> Bool.The circuit is 2a -----x-- | 1 |--N------- output: not a.PLifted version of : (&&) :: Bool -> Bool -> Bool.The circuit is Ja -----x--- | b -----x--- | 0 |--N------- output: a and b.QLifted version of : (||) :: Bool -> Bool -> Bool.The circuit is Ia -----o--- | b -----o--- | 1 |--N------- output: a or b.RLifted version of E: !bool_xor :: Bool -> Bool -> Bool.The circuit is Ya -----x------- | b -----|---x--- | | 0 |--N---N------ output: a xor b.SLifted version of the  if-then-else construction:  ,if-then-else :: Bool -> b -> b -> b SWe only allow first-order terms in the "then" and "else" clauses. The circuit is: q -----x---o--- | | a -----x---|--- | | b -----|---x--- | | 0 |--N---N-------- wire output of the function.TLifted version of the  operator: (==) :: Eq a => a -> a -> BoolBCDEFGHIJKLMNOPQRSTEFGHIJKLMNOPQRSTBCDFNone>HV y MUVWX   021021UVWX1None>HV z()*+:;<  RSTUVWXYZ[\]^_`abcdefgijk !"#$%&'()  !"%&'()*+,-./0345678<=>?BCDEFGHIJKLMPQRSTWbcefgmopquvwxy|3456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]bcfghnopqrstuz{|}~*,-/01<@ABCDEFGHIJKLMNOPQRST  !"%&'()*+,-./0345678AJ<D=>?BCDEFGHIJKLMPQRSTKWE3456789:;<=>?@bcefgPQTUVWRSXopqBCFGHINOLMYZ[]fghwmu}|~vxy:;<*(+)nprsoqtu*/01,-<@ARSTUVWXYZ[\]^_`abcdef|{z  ijkgcbNone>HV ކaVA boolean flag indicating whether to respect global phases during circuit synthesis (Y) or disregard them ([).bAA type to measure precision. Precision is expressed as a number b2 of bits, i.e., binary digits, so that  = 2[sup "b].cmBinary digits, as a unit of precision. For example, the following specifies a precision of 20 binary digits: prec = 20 * bitsdoDecimal digits, as a unit of precision. For example, the following specifies a precision of 30 decimal digits: prec = 30 * digitseApply a gate (from the type  of Clifford+T operators) to the given .f!Apply a gate list (from the type  of Clifford+T operators) to the given . Note: the operators in the list are applied right-to-left, i.e., the gate list is assumed given in matrix multiplication order, but are applied in circuit order.gLike f>, but apply the same list of gates to two qubits in parallel.hInput two indices i and j, a list of qubits qlist-, and an imperative-style single-qubit gate U . Apply the two-level operator U[sub i,j] to qlist. Intended usage: twolevel i j qlist gate_U_atThe qubits in qlistN are ordered lexicographically left-to-right, e.g., [|00#*, |01#*, |10#*, |11#*].;This function implements an improved version of Gray codes.iApply a T[sup m%] gate. This gate is decomposed into Z, S, S [sup ], T, and T[sup ] gates.jApply a 3 gate to the given list of qubits. The qubits in qlistN are ordered lexicographically left-to-right, e.g., [|00#*, |01#*, |10#*, |11#*].kApply a list of % gates to the given list of qubits. The qubits in qlistN are ordered lexicographically left-to-right, e.g., [|00#*, |01#*, |10#*, |11#*].Note: the operators in the list are applied right-to-left, i.e., the gate list is assumed given in matrix multiplication order, but are applied in circuit order.lLike j8, but use the alternate generators for two-level gates.mApply a list of % gates to the given list of qubits. The qubits in qlistN are ordered lexicographically left-to-right, e.g., [|00#*, |01#*, |10#*, |11#*].Note: the operators in the list are applied right-to-left, i.e., the gate list is assumed given in matrix multiplication order, but are applied in circuit order.nCDecompose the given operator exactly into a single-qubit Clifford+Tg circuit. The operator must be given in one of the available exact formats, i.e., any instance of the  class. Typical instances are: K: a 22 unitary operator with entries from the ring [bold D][] = !$[1/"2, i]; : a 33 Bloch sphere operator with entries from the ring !$[1/"2]. In this last case, the operator will be synthesized up to an unspecified global phase.o5Decompose the given operator exactly into a Clifford+T, circuit. The operator must be given as an nn@-matrix with coefficients in a ring that is an instance of the - class. A typical example of such a ring is .)If this function is applied to a list of m qubits, then we must have n "d 2[sup m].The qubits in qlistN are ordered lexicographically left-to-right, e.g., [|00#*, |01#*, |10#*, |11#*].vThe generated circuit contains no ancillas, but may contain multi-controlled gates whose decomposition into Clifford+T generators requires ancillas.pLike o, but use the alternate algorithm from Section 6 of Giles-Selinger. This means all but at most one of the generated multi-controlled gates have determinant 1, which means they can be further decomposed without ancillas.q Decompose an R[sub z ]() = [exp "iZ'/2] gate into a single-qubit Clifford+T$ circuit up to the given precision. [image Rz.png]The parameters are: a precision b "e 0;an angle , given as a  value;a source of randomness g.rConstruct a Clifford+TY circuit (with no inputs and outputs) that approximates a scalar global phase gate [exp i2] up to the given precision. The parameters are:a flag  keepphaseU to indicate whether global phase should be respected. (Note that if this is set to [', then this function is just a no-op); a precision b "e 0;an angle , given as a  value;a source of randomness g.#We use the following decomposition:[image phase.png]sDecompose the operatorU = [exp i ] R[sub z ]() R[sub x ]() R[sub z]()into the Clifford+T; gate base, up to the given precision. The parameters are:a flag  keepphaseE to indicate whether global phase should be respected. If this is [, the angle  is disregarded; a precision b "e 0;/a tuple of Euler angles (, , , ), given as  values;a source of randomness g.t&Decompose a single-qubit unitary gate U into the Clifford+T: gate base, up to the given precision, provided that det U = 1. The parameters are:a flag  keepphase7 to indicate whether global phase should be respected; a precision b "e 0;0a 22 complex matrix, with entries expressed as   values;a source of randomness g.uDecompose a controlled R[sub z ]() = [exp "iZ'/2] gate into a single-qubit Clifford+T? circuit up to the given precision. The parameters are as for rJ. The first input is the target qubit, and the second input the control.1We use the following decomposition. It has lower T-count than the alternatives and makes good use of parallelism. Since it uses the same rotation twice, only a single run of the synthesis algorithm is required.mage controlled-zrot.png]v!Decompose a controlled phase gate[image controlled_phase.png]into the Clifford+T' gate base. The parameters are as for r.1We use the following decomposition. It has lower T-count than the alternatives and makes good use of parallelism. Since it uses the same rotation twice, only a single run of the synthesis algorithm is required.#[image controlled-phase-decomp.png]If the a= flag is set, respect global phase; otherwise, disregard it.abcdefghijklmnopqrstuvbcdaefghijklmnopqrstuvNone=>?@ACHSVX <w$A PMonad is a Monad enriched with a x function that takes a probability, and two results, and returns a merged version of these results under the given monad. This idea is taken directly from QIO.yA yF is the data structure containing the state that we update throughout the simulation. We need to keep track of the next available wire, and a quantum state in the form of a distribution of basis states. We also track a list of quantum traces, so that we have a "tracing" mechanism during the execution of quantum circuits.A QuantumTrace is essentially a probability distribution for the current state of the qubits that have been traced. We can represent this using a Vector. The list of Booleans is in the same order as the list of Qubits that was being traced.<A probability distribution gives each element a probability.HAn amplitude distribution gives each classical basis state an amplitude.$The type of vectors with scalars in n over the basis a'. A vector is simply a list of pairs. Gates that act on a single qubit can be defined by essentially a 2-by-2 matrix. A GateR is written by rows, such that a matrix:[image GateR.png] &would be written as (m00,m01,m10,m11).XWe define our own trace function that only calls trace if the boolean argument is true.;Scalar multiplication of a 2-by-2 matrix by a given scalar.The inverse of a  is its conjugate transpose.BA simple pattern matching function that gives each "gate name" a GateR representation. Adding (single qubit) quantum gates to this function will give them an implementation in the simulator. Any single qubit named quantum gate that needs to be simulated must have a clause in this function, along with a given GateR that is its matrix representation. Note that unitarity is not enforced, so defined gates must be checked manually to be unitary operators. YExample Gates: gateQ "x" = (0,1,1,0) gateQ "hadamard" = (h, h, h,-h) where h = (1/sqrt 2)Like C, but also conditionally invert the gate depending on InverseFlag.The exponential function for  numbers.$The constant , as a complex number.Like 9, but takes the name of a rotation and a real parameter. Like C, but also conditionally invert the gate depending on InverseFlag.Return the matrix for the 3 gate.Return the matrix for the  gate.Translate a classical gate name into a boolean function. Adding classical gates to this function will give them an implementation in the simulator. 6Example Gate: gateC "if" [a,b,c] = if a then b else c ?Normalizing is used to make sure the probabilities add up to 1.<When we start a simulation, we need an empty starting state.It doesn't make sense having a quantum control on a classical gate, so we can throw an error if that is the case, and just collect the boolean result otherwise.Map the - function to all the controls, and take the  of the resultWhen we want a quantum control, we will be working with one "basis state" at a time, and can look up the qubit's value in that basis state to see whether the control firs.Map the L function to all the controls (under the given basis state), and take the  of the result.2We can calculate the magnitude of a complex numberThe  function splits a Amplitude distribution, by partitioning it around the state of the given qubit within each basis state. It also returns the probability of the qubit being True within the given Amplitudes. This function is used when we want to measure a qubit.We can merge two measurement outcomes, and explicitly keep the first outcome as the True result, and the second as the False result.The v function returns a probability distribution of the state of a list of qubits within a given amplitude distribution.vAdd an amplitude to an amplitude distribution, combining (adding) the amplitudes for equal states in the distribution.iThe apply' function is used to apply a function on "basis states" to an entire amplitude distribution. Lift a function that returns a single basis state, to a function that returns an amplitude distribution (containing a singleton).3apply the given function only if the controls fire.W defines how a single qubit gate is applied to a quantum state. The application of a GateRt to a qubit in a single basis state can split the state into a pair of basis states with corresponding amplitudes.The F is the actual transformer that does the simulation. The type of the ` shows that Qubits are kept as qubits, but Bits are turned into Boolean values, i.e., the results of the computation. We use a StateT Monad, acting over the IO Monad, to store a QuantumState throughout the simulation. This means we carry a state, but also have access to the IO Monad's random number generator (for probabilistic measurement).yThe simulation_transformer is also Dynamic, as the simulated wire states can simply be used to perform dynamic liftings. Apply the + to a (unary) circuit generating function.In order to simulate a circuit using an input basis vector, we need to supply each quantum leaf, with a concrete (i.e., not a dummy) qubit.In order to simulate a circuit using an input basis vector, we need to supply the transformer with a concrete set of qubit bindings.As a helper function, in order to simulate a circuit using an input basis vector, we need to be able to convert each basis into a map from concrete qubits to their value in the given basis.In order to simulate a circuit using an input basis vector, we need to be able to convert the basis vector into a quantum state suitable for use by the simulator i.e. of type Amplitudes.As a helper function, in order to simulate a circuit using an input basis vector, we need to be able to convert a map from concrete qubits to their value into a basis of the given concrete shape.In order to simulate a circuit using an input basis vector, we need to be able to convert the quantum state (i.e. of type Amplitudes) into a basis vector. Apply the  to a (unary) circuit generating function, starting with the quantum state set to the given vector of base states and returning the resulting vector of base states.Input a source of randomness, a quantum circuit, and an initial state (represented as a map from basis vectors to amplitudes). Simulate the circuit and return the final state. If the circuit includes measurements, the simulation will be probabilistic.mThe type of this heavily overloaded function is difficult to read. It has, for example, the following types: sim_amps :: StdGen -> (Qubit -> Circ Qubit) -> Map Bool (Cplx Double) -> Map Bool (Cplx Double) sim_amps :: StdGen -> ((Qubit,Qubit) -> Circ Qubit) -> Map (Bool,Bool) (Cplx Double) -> Map Bool (Cplx Double)#and so forth. Note that instead of ^%, another real number type, such as GH e, can be used.Input a source of randomness, a real number, a circuit, and a basis state. Then simulate the circuit probabilistically. Measure the final state and return the resulting basis vector.`The real number argument is a dummy and is never evaluated; its only purpose is to specify the type: of real numbers that will be used during the simulation.Like , but return the list of  elements that were generated during the computation. This is useful for checking the intermediary state of qubits within a computation.Like , but run in the < monad instead of passing an explicit source of randomness.Like , but run in the < monad instead of passing an explicit source of randomness. Apply the  to a (unary) circuit, and then evaluate the resulting stateful computation to get a probability distribution of possible resultsQuantum simulation of a circuit, for testing and debugging purposes. Input a source of randomness, a real number, and a quantum circuit. Output a corresponding probabilistic boolean function.The inputs to the quantum circuit are initialized according to the given boolean arguments. The outputs of the quantum circuit are measured, and the boolean measurement outcomes are returned. `The real number argument is a dummy and is never evaluated; its only purpose is to specify the type: of real numbers that will be used during the simulation.The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types (for example): run_generic :: (Floating r, Random r, Ord r, RandomGen g, QCData qa) => g -> r -> Circ qa -> BType qa run_generic :: (Floating r, Random r, Ord r, RandomGen g, QCData qa, QCData qb) => g -> r -> (qa -> Circ qb) -> BType qa -> BType qb run_generic :: (Floating r, Random r, Ord r, RandomGen g, QCData qa, QCData qb, QCData qc) => g -> r -> (qa -> qb -> Circ qc) -> BType qa -> BType qb -> BType qc and so forth.Like h, but also output a trace of the states of the given list of qubits at each step during the evaluation.Like , but run in the < monad instead of passing an explicit source of randomness.Like , but run in the < monad instead of passing an explicit source of randomness.oA generic function to simulate Quipper circuits, returning a probability distribution of the possible results.The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types (for example): sim_generic :: (Floating r, Ord r, QCData qa) => r -> Circ qa -> ProbabilityDistribution r (BType qa) sim_generic :: (Floating r, Ord r, QCData qa, QCData qb) => r -> (qa -> Circ qb) -> BType qa -> ProbabilityDistribution r (BType qb) sim_generic :: (Floating r, Ord r, QCData qa, QCData qb, QCData qc) => r -> (qa -> qb -> Circ qc) -> BType qa -> BType qb -> ProbabilityDistribution r (BType qc) and so forth.VWe can show certain vectors, ignoring any 0 probabilities, and combining equal terms.#Any numeric indexed vector forms a . forms a wr such that probabilistic results are "merged" by extending the probability distribution by the possible results.A State Monad holding a _ forms a w`, where results are merged by choosing one probabilistically using a random number from the _.eIO forms a PMonad, where results are merged by choosing one probabilistically using a random number.?wxyz}|{~?yz}|{~wxNone >HVX CAuxiliary function: determine whether a "control" is true of false.EAuxiliary function: compute the boolean function corresponding to a B of the given name.A Quipper.Internal.Transformer mapping each gate to the corresponding boolean function. This will fail with an error for gates that don't act within the computational basis, or if some assertion is not met. Some gates are not yet implemented. tBoolean simulation of a circuit, for testing and debugging purposes. This function makes use of the concept of a  valuationX. A valuation is a partial map from circuit wires to booleans, represented by the type h BoolA. Given a circuit and a valuation for its inputs, the function & produces a valuation for its outputs.The simulation will fail with an error if the circuit contains a gate not acting within the computational basis, or if some assertion is not met. Not all gates are currently implemented. Subroutines are not currently implemented.Like &, but also takes a stub error message.Boolean simulation of a circuit, for testing and debugging purposes. Input a classical circuit, and output the corresponding boolean function. This will fail with an error if the circuit contains a gate not acting within the computational basis, or if some assertion is not met.Boolean simulation of a circuit, for testing and debugging purposes. Input a classical circuit, and output the corresponding boolean function. This will fail with an error if the circuit contains a gate not acting within the computational basis, or if some assertion is not met.Unlike M, this can be applied to a circuit-generating function in curried form with n arguments, for any n9 "e 0. The resulting boolean function then will also have n arguments. }The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: run_classical_generic :: (QCData qa) => Circ qa -> BType qa run_classical_generic :: (QCData qa, QCData qb) => (qa -> Circ qb) -> BType qa -> BType qb run_classical_generic :: (QCData qa, QCData qb, QCData qc) => (qa -> qb -> Circ qc) -> BType qa -> BType qb -> BType qc and so forth.None >HVX 65A datatype to represent controls that we can simulateyThe stabilizer transformer. Used to transform a Quipper circuit, made up of Clifford group operators, directly into the  monad (where o is a type-synonym for StateT Tableau IO). Note that this transformer only deals with 1 and 2-qubit operators.<Construct an element of ControlInfo from a list of Controls.Use the ( to transform a Quipper circuit into a , ready for simulation.HReturn the tableau resulting from simulating the given Quipper circuit.Efficiently simulate a unary Quipper circuit that consists entirely of Clifford group operators, using the stabilizer formalism.}Efficiently simulate a Quipper circuit that consists entirely of Clifford group operators, using the stabilizer formalism. pInputs a quantum circuit, and outputs a corresponding probabilistic boolean function. The inputs to the quantum circuit are initialized according to the given boolean arguments. The outputs of the quantum circuit are measured, and the boolean measurement outcomes are returned. Because the measurement outcomes are probabilistic, this function takes place in the  monad.The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types (for example): run_clifford_generic :: (QCData qa) => Circ qa -> IO (BType qa) run_clifford_generic :: (QCData qa, QCData qb) => (qa -> Circ qb) -> BType qa -> IO (BType qb) run_clifford_generic :: (QCData qa, QCData qb, QCData qc) => (qa -> qb -> Circ qc) -> BType qa -> BType qb -> IO (BType qc) and so forth.  INone>HV   None 2=>?@AHV The type of boolean registers. The type of  registers. The syntax a .!(i) is used to access the ith element of the register a.|The type of quantum registers. A quantum register is an array of qubits, indexed by natural numbers in the range from 0 to n -1, where n+ is the length of the register. The syntax a .!(i) is used to access the ith element of the register a. The main advantage of a register over a list is constant-time access. The main disadvantage is that registers don't allow easy appending, pattern matching, or recursion.0A register is an array of elements of some type x5, indexed by natural numbers in the range from 0 to n -1, where n is the length of the register.r !.(i) : Return the ith element of a register r.DConvert a list to a register. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.DConvert a register to a list. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list. Return the length of a register. Convert a  to a (. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list. Convert a  to a (. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.Return the length of a . -Return a piece of shape data to represent an ms-qubit quantum register. Please note that the data can only be used as shape; it will be undefined at the leaves.MTurn a bit vector into a bit register. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.MTurn a bit register into a bit vector. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.Return the length of a .OTurn a bool vector into a bool register. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.OTurn a bool register into a bool vector. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list.Return the length of a .kCreates a new quantum register, initialized from a list of booleans. The conversion is tail-endian, i.e., r".!(0) holds the tail of the list.Terminates a quantum register, and assert that its state is as specified by the list of booleans. The conversion is tail-endian, i.e., r!.!(0) holds the tail of the list./Measure a quantum register, yielding a list of s. .Temporarily create a quantum register of size na for use as an ancilla. This can be used to introduce an ancilla with a local scope, like this: Mwith_ancilla_reg n $ \r -> do { <<<code block using ancilla register r>>> }Like `, except also initialize the register as specified by a bit vector. In this case, the argument n is not required, because it equals the length of the bit vector. When the ancilla is terminated at the end of its scope, it is asserted to be in the same state it was prepared in.boolreg_of_int m x7: Initialize a bool register directly from an integer x(, regarded as a binary string of length me. The conversion is little-endian, i.e., the register holds the least significant digit at index 0.int_of_boolreg_unsigned_le m r: Turn a bool register into an integer, regarded as a binary string. The conversion is little-endian, i.e., the register holds the least significant digit at index 0. The integer is unsigned.9 !None>HV n?4Decomposition of the Toffoli gate into the Clifford+T base, from Nielsen and Chuang (Figure 4.9). The first argument is the target, and the other two are the controls. The controls can be positive or negative.[image toffoli_NC.png]4Decomposition of the Toffoli gate into the Clifford+T base, from Amy et al. ( http://arxiv.org/abs/1206.0758v3, Figure 13). The first argument is the target, and the other two are the controls. The controls can be positive or negative.[image toffoli_AMMR.png]Decomposition of the Toffoli gate using controlled Clifford operators, from Nielsen and Chuang (Figure 4.8). The controls can be positive or negative.[image toffoli_V.png]4Decomposition of the Toffoli gate into the Clifford+T base, using T"-depth 1 and four ancillas. From  http://arxiv.org/abs/1210.0974~ (Figure 1). The first argument is the target, and the other two are the controls. The controls can be positive or negative.[image toffoli_S.png]'Decomposition of the doubly-controlled iX-gate into the Clifford+T base, using T -count 4 and T-depth 2. Adapted from ( http://arxiv.org/abs/1210.0974, Figure 10). The first argument is the target, and the other two are the controls. The controls can be positive or negative.[image cc_iX.png]'Decomposition of the doubly-controlled iX-gate into the Clifford+T base, using T-count 4, and using the control qubits only as controls. Derived from Nielsen and Chuang (Figure 4.9). The controls can be positive or negative.[image cc_iX_simple.png]'Decomposition of the doubly-controlled iX-gate into the Clifford+T base, using T)-depth 1 and one ancilla. Adapted from ( http://arxiv.org/abs/1210.0974~, Figure 9). The first argument is the target, and the other two are the controls. The controls can be positive or negative.[image cc_iX_S.png]'Decomposition of the doubly-controlled Z-gate into the Clifford+T! base. Adapted from Amy et al. ( http://arxiv.org/abs/1206.0758v38, Figure 13). The controls can be positive or negative.[image ccZ_AMMR.png]'Decomposition of the doubly-controlled Z-gate into the Clifford+T base, using T,-depth 1 and four ancillas. From Selinger ( http://arxiv.org/abs/1210.09747, Figure 1). The controls can be positive or negative.[image ccZ_S.png]GDecomposition of the Fredkin (controlled-Swap) gate into the Clifford+Tx base. The first two arguments are the targets, and the last one the control. The controls can be positive or negative.[image fredkin.png]Decomposition of a controlled H-gate into the Clifford+T base. From Amy et al. ( http://arxiv.org/abs/1206.0758v3{, Figure 5(a)). The first argument is the target and the second one the control. The control can be positive or negative.[image cH_AMMR.png]Decomposition of a controlled W-gate into the Clifford+T base. The first two arguments are the targets, and the last argument is the control. The control can be positive or negative.[image controlled_W.png]Decomposition of a W-gate into the Clifford+T base.[image gate_W_CliffordT.png]Decomposition of a controlled iX-gate into the Clifford+Tv base. The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_iX.png]Decomposition of a controlled S-gate into the Clifford+T base. From Amy et al. ( http://arxiv.org/abs/1206.0758v3, Figure 5(b)). The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_S.png]Decomposition of a controlled T-gate into the Clifford+Tv base. The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_T.png]Decomposition of a controlled V-gate into the Clifford+T! base. Adapted from Amy et al. ( http://arxiv.org/abs/1206.0758v3, Figure 5(c)). Our V -gate is HS[sup ]H as in Nielsen and Chuang. The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_V.png]Decomposition of a controlled E-gate into the Clifford+Tv base. The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_E.png]>Decomposition of a controlled [bold Y]-gate into the Clifford+T] base. The gate is from the Ground State Estimation algorithm and is defined as [bold Y] = SHS, or equivalently, [image Y.png])It should not be confused with the Pauli Yv gate. The first argument is the target, and the second one is the control. The control can be positive or negative.[image controlled_YY.png]cA "plain" Toffoli gate, not decomposed. This is provided for convenience, for example to use with .A "plain" doubly-controlled iXS-gate, not decomposed. This is provided for convenience, for example to use with .Decomposition of an m"-times controlled not-gate, using mc"2 ancillas that do not need be initialized in a particular state. Adapted from Barenco et al. ( $http://arxiv.org/abs/quantph/9503016 , Lemma 7.2).In addition to what is shown in Barenco et al., this function permits some Toffoli gates to be replaced by doubly-controlled iX@-gates. This may be beneficial in gate bases, such as Clifford+T, where a doubly-controlled iX8-gate has a simpler representation than a Toffoli gate.The first argument is a Toffoli gate to use in the decomposition. The second argument may be either a Toffoli gate or a doubly-controlled iX gate. The third argument is the target, the fourth argument is a list of qubits to be used as ancillas, and the fifth argument is a list of signed controls. The ancillas need not be initialized, and are returned in their original state.WThe size of this circuit is linear in the number of controls; the decomposition uses 4m"8 doubly-controlled gates for m "e 3.[image multi_cnot_barenco.png]'Decomposition of a multiply-controlled iX=-gate, using no ancillas. Adapted from Giles and Selinger ( http://arxiv.org/abs/1212.0506, Section 5.2).=The first argument is a Toffoli gate or a doubly-controlled iX_-gate. The third argument is the target, and the fourth argument is a list of signed controls.WThe size of this circuit is linear in the number of controls; the decomposition uses 8m"32 doubly-controlled gates, 4 T-gates, and 2 H -gates, for m "e 6.[image multi_ciX_noancilla.png]8Partition a list of controls into quantum and classical.kGiven a function that expects a qubit (typically as a control), turn it into a function that can handle a signed (positive or negative) qubit. This is done by conjugating the circuit with negations on both sides, if the sign is negative. Usage: 3with_signed_qubit c $ \q -> do <<<code using q>>>[image with_signed_qubit.png]5Decompose quantum controls recursively until at most nT remain, and then pass these reduced controls to the given circuit. Precondition: n "e 1. The decomposition is done using a Toffoli-like gate that is given as the first argument. This should be either a Toffoli gate, a doubly-controlled iXW-gate, a decomposition thereof, or any other reversible ternary gate with the behavior|000#* ! |0#*|[sub 0]#*|001#* ! |0#*|[sub 1]#*|010#* ! |0#*|[sub 2]#*|011#* ! |1#*|[sub 3]#*,9where the states |[sub 0]#*, &, |[sub 3]#* are arbitrary.For example, when nc=2, this typically yields a circuit such as the following (here shown using the doubly-controlled iX-gate):#[image with_combined_controls2.png]And for n*=1, the circuit typically looks like this:#[image with_combined_controls1.png]ZClassical controls are not decomposed, but are applied to the resulting circuit directly."None >HSVX EAn enumeration type for the three gate bases handled by this module.5Decompose quantum controls recursively until at most nT remain, and then pass these reduced controls to the given circuit. Precondition: n} "e 1. The decomposition is done using Toffoli gates, decomposed into the gate base. Classical controls are left untouched.For example, when nt=2, this typically yields a circuit such as the following (but with the Toffoli gates further decomposed into the ):[image decompose2Controls.png]And for n*=1, the circuit typically looks like this:[image decomposeControls.png] (Decompose a Toffoli gate into the given N. The controls on the Toffoli gate may be positive or negative, as specified. The inverse of  . 2Implement a QMultinot gate in terms of QNot gates. *A transformer to decompose a circuit into o gates. Note that in the case of classically-controlled quantum gates, the classical controls are unaffected. :Return a circuit producing function from a TypedSubroutinexApply the decompose transformer to the given TypedSubroutine Note: by default, set the classical-control flag to false.:A dynamic transformer variant of the decompose transformer.Decompose a circuit into gates from the given ..Decompose a circuit into gates from the given  . Unlike M, this can be applied to a circuit-generating function in curried form with n arguments, for any n "e 0.}The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: <decompose_legacy_generic :: (QCData qa) => LegacyGateBase -> Circ qa -> Circ qa decompose_legacy_generic :: (QCData qa, QCData qb) => LegacyGateBase -> (qa -> Circ qb) -> (qa -> Circ qb) decompose_legacy_generic :: (QCData qa, QCData qb, QCData qc) => LegacyGateBase -> (qa -> qb -> Circ qc) -> (qa -> qb -> Circ qc) and so forth.          #None >HSVX  A version of  that uses doubly-controlled iX3-gates to do the decomposition. For example, when n0=2, this yields circuits such as the following:#[image with_combined_controls2.png]And for n=1:#[image with_combined_controls1.png] A version of 0 that further decomposes the doubly-controlled iX-gates into the Clifford+T gate base.Turn a list of signed controls into a list of positive quantum controls, by applying all classical controls directly, and conjugating any negative quantum controls by X;. Call the inner block with those quantum controls. Usage: @with_normalized_controls ctrls $ \qs -> do <<<code using qs>>>Like  , but use HSSH instead of X, so as not to leave the H, S, T, CNot gate base. )Negate the number if the boolean is true.2This transformer makes sure that not-gates, Pauli X-, Y-, and Z -gates, and iX-gates have at most two controls; that phase gates of the form Diag(1, ) have no controls; and that all other gates have at most one control.HThis transformer decomposes rotation and phase gates into the Clifford+T6 basis, using the approximate synthesis algorithm of  http://arxiv.org/abs/1212.6253. Other gates are unchanged. YThis transformer requires a precision parameter, as well as a source of randomness. The a2 flag indicates whether to respect global phases.BThis transformer decomposes all gates that permit exact Clifford+TE representations into the following concrete gate base for Clifford+T:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].aClassical controls and classical gates are not subject to the gate base, and are left untouched.wRotations and phase gates are left unchanged by this transformer, but any controls on those gates will be decomposed. YThis transformer decomposes a circuit into the standard gate set, which we define to be:X, Y, Z, H, S, S [sup ], T, T [sup ], and CNOT.LAs a precondition, the input circuit must only contain the following gates:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].Global phases are suppressed. Classical controls and classical gates are not subject to the gate base, and are left untouched.Any gates that are not among the input gates listed above will be transformed to a semantically correct circuit which may, however, contain gates that are not in the standard gate set. The best way to avoid this is to apply exact and approximate Clifford+T decomposition first.WThis transformer decomposes a circuit into the strict gate set, which we define to be:H, S, T, and CNOT.LAs a precondition, the input circuit must only contain the following gates:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].Global phases are suppressed. Classical controls and classical gates are not subject to the gate base, and are left untouched.Any gates that are not among the input gates listed above will be transformed to a semantically correct circuit which may, however, contain gates that are not in the strict gate set. The best way to avoid this is to apply exact and approximate Clifford+T decomposition first.Handle subroutines for the .Dynamic transformer for the .Unary transformer for the . Handle subroutines for the .!Dynamic transformer for the ."Unary transformer for the .#Handle subroutines for the .$Dynamic transformer for the .%Unary transformer for the .&Handle subroutines for the .'Dynamic transformer for the .(Unary transformer for the .)Handle subroutines for the .*Dynamic transformer for the .+Unary transformer for the .,2This transformer makes sure that not-gates, Pauli X-, Y-, and Z -gates, and iX-gates have at most two controls; that phase gates of the form Diag(1, ) have no controls; and that all other gates have at most one control.-HThis transformer decomposes rotation and phase gates into the Clifford+T6 basis, using the approximate synthesis algorithm of  http://arxiv.org/abs/1212.6253e. It requires a precision parameter, as well as a source of randomness. Other gates are unchanged..BThis transformer decomposes all gates that permit exact Clifford+TE representations into the following concrete gate base for Clifford+T:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].aClassical controls and classical gates are not subject to the gate base, and are left untouched.wRotations and phase gates are left unchanged by this transformer, but any controls on those gates will be decomposed. /YThis transformer decomposes a circuit into the standard gate set, which we define to be:X, Y, Z, H, S, S [sup ], T, T [sup ], and CNOT.LAs a precondition, the input circuit must only contain the following gates:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].Global phases are suppressed. Classical controls and classical gates are not subject to the gate base, and are left untouched.Any gates that are not among the input gates listed above will be transformed to a semantically correct circuit which may, however, contain gates that are not in the standard gate set. The best way to avoid this is to apply exact and approximate Clifford+T decomposition first.0WThis transformer decomposes a circuit into the strict gate set, which we define to be:H, S, T, and CNOT.LAs a precondition, the input circuit must only contain the following gates:7controlled-not (with one positive or negative control), any single-qubit Clifford gates,T and T[sup ].Global phases are suppressed. Classical controls and classical gates are not subject to the gate base, and are left untouched.Any gates that are not among the input gates listed above will be transformed to a semantically correct circuit which may, however, contain gates that are not in the strict gate set. The best way to avoid this is to apply exact and approximate Clifford+T decomposition first. !"#$%&'()*+,-./0 !"#$%&'()*+,-./0$None>HV  1An enumeration type for gate bases. More cases can be added in the future, for example for using gates from a particular physical machine description. Some gate bases carry additional parameters; for example, in the case of decomposition into a discrete gate base, one may specify a precision , a random seed, or other flags.If a bJ parameter is present, it specifies the desired precision per gate. If a < parameter is present, it specifies a source of randomness.If a aK parameter is present, it determines whether global phases are respected (Y) or disregarded ([).29Use all logical gates, i.e., leave the circuit unchanged.3Decompose into binary gates.4(Decompose into Toffoli and binary gates.5Decompose into Clifford+Tk. This is a legacy transformer that does not handle all gates correctly. For example, it does not handle W(-gates, rotations, or phase gates. Use 6 instead.6Decompose into Clifford+T{, specifically: single-qubit Clifford gates, the controlled-not gate (with positive or negative controls), and the gates T and T[sup ].7=Decompose into the standard gate set, which we define to be X, Y, Z, H, S, S [sup ], T, T[sup ], and CNOT. Suppresses global phases.8Decompose into H, S, T, CNOT' gates only. Suppresses global phases.91Decompose rotation and phase gates into Clifford+TG, using an approximate synthesis algorithm. Other gates are unchanged.:ADecompose gates that can be exactly represented in the Clifford+T base into that base, specifically: single-qubit Clifford gates, the controlled-not gate (with positive or negative controls), and the gates T and T3[sup ]. Leave rotation and phase gates unchanged.;%Eliminate excess controls from gates.<MAn assignment of gate bases to names. Names are given as lower-case strings.EThis can be useful, e.g., in the definition of command line options.In the future, the syntax should be extended so that users can specify parameters (e.g., the precision, random seed) on the command line as well. For now, we just use the default precision.=.Decompose a circuit into gates from the given 1N. This can be applied to a circuit-generating function in curried form with n arguments, for any n "e 0.}The type of this heavily overloaded function is difficult to read. In more readable form, it has all of the following types: decompose_generic :: (QCData qa) => GateBase -> Circ qa -> Circ qa decompose_generic :: (QCData qa, QCData qb) => GateBase -> (qa -> Circ qb) -> (qa -> Circ qb) decompose_generic :: (QCData qa, QCData qb, QCData qc) => GateBase -> (qa -> qb -> Circ qc) -> (qa -> qb -> Circ qc) and so forth. 1;:97542683<= 1;:97542683<=JNone>HV Xabcd138624579:;<=bcda138624579:;<=%None2=>?@AHV *n?Quantum analogue of Haskell s x type class. This provides basic addition, subtraction, multiplication, sign operations, and conversion from integers.@^Add two quantum numbers into a fresh one. The arguments are assumed to be of equal size. The I instance uses O<(!) gates, both before and after transformation to Toffoli.AfMultiply two quantum numbers into a fresh third. The arguments are assumed to be of equal size. The I instance is O (![sup 2]).BcSubtract two quantum numbers into a fresh one. The arguments are assumed to be of equal size. The I instance uses O<(!) gates, both before and after transformation to Toffoli.C>Compute the absolute value of a (signed) quantum number. The I instance is O(!).D7Compute the negation of a (signed) quantum number. The I instance is O(!).ECompute a quantum number of the same precision as the input, with value 1, 0, or 1, depending on the sign of the input. Analogous to Haskell s . The I instance is O(!).F Convert a I to a quantum number. For the I* instance, this is just a copy operation.GThe type of fixed-length m~-bit integer parameters. Values of this type are parameters, i.e., they are classical and known at circuit generation time.Unlike values of type I and H, a value of type GJ may have an indeterminate length. This happens, for example, if the value is specified by means of an integer literal (e.g., 17), which does not carry length information. In such cases, the value can only be used when it can be deduced from the context. For example, such values may be used for terminating or controlling a I, but not for initializing a I.HThe type of fixed-length mG-bit classical integer inputs. This is a circuit execution time value.IThe type of fixed-length mA-qubit quantum integers. This is a circuit execution time value.JJ xC is the type of fixed-length integers, but using elements of type xo instead of bits. It is an abstract type, and details of its implementation is not exposed to user-level code.K Create a J x from a list of x`s. The conversion is big-headian, i.e., the head of the list holds the most significant digit.L Create an G! of indeterminate length from an X. If the J is of determinate length, return its list of digits as a big-headian list, i.e., the head of the list holds the most significant digit. If the J& is of indeterminate length, return (n, id ), where n is the underlying X and id is the witness proving that x = J.SThis is a lowest-level access function not intended to be used by user-level code.Set the length of an J to m~ "e 0. This operation is only legal if the input (a) has indeterminate length or (b) has determinate length already equal to mu. In particular, it cannot be used to change the length from anything other than from indeterminate to determinate.cIf both arguments already have determinate lengths, and they do not coincide, throw an error. The g4 argument is used as an error message in that case. Note that if x "` J, the input is guaranteed to have determinate length. However, we cannot test for equality of types in a polymorphic function. This is where the Z argument to  is used.Return Y if the J is of determinate length, and [$ if it is of indeterminate length. MFrom a J:, which must be of determinate length, extract a list of xs. The conversion is big-headian, i.e., the head of the list holds the most significant digit. It is an error to call this function with an J of indeterminate length.NReturn the size of a J, or P if indeterminate.O Convert an G of length m to an X in the range {0, &, 2[sup m ]-1}. If the G0 has indeterminate length, return the original X.P Convert an G of length m to an X in the range {-2[sup m-1], &, 2[sup m-1]-1}. If the G0 has indeterminate length, return the original X.\Equality test. If at least one argument has determinate length, test equality modulo 2[sup mQ]. If both have indeterminate length, check equality of the underlying integers.}Get the nominal length of an integer (in bits). It is an error to apply this function to an integer of indeterminate length.QConvert an integer to a bit list. The conversion is little-headian, i.e., the head of the list holds the least significant digit.RConvert a bit list to an integer. The conversion is little-headian, i.e., the head of the list holds the least significant digit. Extend a J to the given length without changing its (unsigned) value. This is done by adding the required number of high bits initialized to zeroX. It is an error to call this function when the new length is shorter than the old one. Extend a J to the given length without changing its (signed) value. This is done by adding the required number of high bits initialized to copies of the sign bit (or to zero if the original integer was of length 0). It is an error to call this function when the new length is shorter than the old one.SReturn the size of an G, or P if indeterminate.T Convert an G to a list of booleans. The conversion is big-headian, i.e., the head of the list holds the most significant digit. As usual, [ is 0 and Y5 is 1. It is an error to apply this operation to an G whose length is indeterminate.UConvert a boolean list to an G_. The conversion is big-headian, i.e., the head of the list holds the most significant digit.V Create an GG of the specified length (first argument) and value (second argument).Set the length of an G to m~ "e 0. This operation is only legal if the input (a) has indeterminate length or (b) has determinate length already equal to m{. In particular, it cannot be used to change the length from anything other than from indeterminate to determinate. (Use W or X# to increase a determinate length).cIf both arguments already have determinate lengths, and they do not coincide, throw an error. The g4 argument is used as an error message in that case.W Extend an G to the given length without changing its (unsigned) value. This is done by adding the required number of high bits initialized to 0. It is an error to call this function when the new length is shorter than the old one.X Extend an G to the given length without changing its (signed) value. This is done by adding the required number of high bits initialized to copies of the sign bit. It is an error to call this function when the new length is shorter than the old one.Y Convert a Hs to a list of qubits. The conversion is big-headian, i.e., the head of the list holds the most significant digit.ZConvert a list of qubits to a H_. The conversion is big-headian, i.e., the head of the list holds the most significant digit.[ Convert a Hu to a list of bits. The conversion is little-headian, i.e., the head of the list holds the least significant digit.\Convert a list of bits to a Hc. The conversion is little-headian, i.e., the head of the list holds the least significant digit.]Return the length of a H , in bits.^ Extend a H to the given length without changing its (unsigned) value. This is done by adding the required number of high bits initialized to 0. It is an error to call this function when the new length is shorter than the old one._ Extend a H to the given length without changing its (signed) value. This is done by adding the required number of high bits initialized to copies of the sign bit. It is an error to call this function when the new length is shorter than the old one.` Convert a Is to a list of qubits. The conversion is big-headian, i.e., the head of the list holds the most significant digit.aConvert a list of qubits to a I_. The conversion is big-headian, i.e., the head of the list holds the most significant digit.b Convert a Iw to a list of qubits. The conversion is little-headian, i.e., the head of the list holds the least significant digit.cConvert a list of qubits to a Ic. The conversion is little-headian, i.e., the head of the list holds the least significant digit.dReturn the length of a I , in bits.e Extend a I to the given length without changing its (unsigned) value. This is done by adding the required number of high bits initialized to 0. It is an error to call this function when the new length is shorter than the old one.f Extend a I to the given length without changing its (signed) value. This is done by adding the required number of high bits initialized to copies of the sign bit. It is an error to call this function when the new length is shorter than the old one.g-Return a piece of shape data to represent an mr-qubit quantum integer. Please note that the data can only be used as shape; it will be undefined at the leaves.h-Return a piece of shape data to represent an m-bit H\. Please note that the data can only be used as shape; it will be undefined at the leaves.Input the lengths of two inputs to a binary operation, and return the common length. If one length is indeterminate, return the other; if both are indeterminate, return PV; if both are determinate but not equal, throw an error with the given error message.iTry to set the length of an G to that of another J value (which could be a I, a H , or another G). This will fail with an error if both numbers already have determinate lengths that don't coincide. In this case, the string argument is used as an error message.4A useful auxiliary function that converts a list of Gs to a list of Xs, while also returning their common length. All arguments whose length is not indeterminate must have the same common length. If the lengths don't match, throw an error with the error message specified by the g argument.Like , but regards the Gs as unsigned integers.j Create an GR of the given length and value. Leave the length indeterminate if it is given as P.6Auxiliary function for lifting a binary operator from X to GG. The string argument is the name of the operator, for error messages.5Auxiliary function for lifting a unary operator from X to G.kReturn the interval [x..y], with x and y$ regarded as signed values of type G.lReturn the interval [x..y], with x and y& regarded as unsigned values of type G. error_str [n1,n2,n3]: if n1, n2, n3W all equal, return this value; else throw an error. Useful for checking that sizes of Is match. error_str [x1,x2,x3]: if x1, x2, x3C all have the same length, return this value; else throw an error. m Increment a I in place. O (!) gates. Implementation note: currently tries to minimize gate count, at the cost of a rather long Quipper description. Can the latter be reduced without increasing the former? Low-level implementation of m2: represents integers as big-headian qubit lists.n Decrement a I in place. Inverse of m. O(!).Add two IAs into a fresh one. Arguments are assumed to be of equal size. O;(!) gates, both before and after transformation to Toffoli.Low-level implementation of 2: represents integers as big-headian qubit lists. Subtract two IBs, into a fresh one. Arguments are assumed to be of equal size. O(!).Low-level implementation of 2: represents integers as big-headian qubit lists.oAdd one I onto a second, in place; i.e. (x,y) ! (x,x+y0). Arguments are assumed to be of equal size. O (!) gates.Low-level implementation of o2: represents integers as big-headian qubit lists.p Subtract one I from a second, in place; i.e. (x,y) ! (x,y x0). Arguments are assumed to be of equal size. O (!) gates.Low-level version of p2: represents integers as big-headian qubit lists.qAdd a parameter G and a I, into a fresh I: (x, y) ! (y, x+y). The parameter x must be of the same length as y, or x& can also be of undetermined length. O(!).Low-level implementation of qA: represents integers as big-headian qubit lists. Precondition: x and y have the same length.rSubtract a parameter G from a I, into a fresh I. The G cannot be shorter than the IM (that would give ill-defined behavior), but can be of undetermined length. O(!).sAdd a parameter G onto a I, in place; i.e. (x,y) ! x+y. The parameter x must be of the same length as y, or x& can also be of undetermined length. O(!).Low-level implementation of sA: represents integers as big-headian qubit lists. Precondition: xlist and y& have the same length. Precondition: x and y have the same length.tSubtract a parameter G from a I, in place; i.e. (x,y) ! (x,x-y). x cannot be shorter than y. O(l) gates.uMultiply a parameter G by a I, into a fresh I. The G cannot be shorter than the IM (that would give ill-defined behavior), but can be of undetermined length. O(!).Low-level implementation of u4: represents integers as big-headian (qu)bit lists.vNegate a (signed) I in place. O(!).Low-level version of v2: represents integers as big-headian qubit lists.#Compute the negation of a (signed) I. O(!).6(Fixes the minimum value, consistently with Haskell s   :: .) )Compute the absolute value of a (signed) I. O(!).6(Fixes the minimum value, consistently with Haskell s   :: .) Low-level implementation of 2: represents integers as big-headian qubit lists. Compute a Iv of the same length as the input, with value 1, 0, or 1, depending on the sign of the input. Analogous to Haskell s . O(!).Low-level implementation of 2: represents integers as big-headian qubit lists.wComparison of two Is, considered as unsigned. O(!).Low-level implementation of w2: represents integers as big-headian qubit lists.Same as w, but uncurried, represents integers as big-headian qubit lists, and doesn t clean up its garbage. (If each recursive call cleans up its own garbage, gate use becomes O(2[sup n]).)xComparison of two I"s, considered as signed. Used in  instance  I. O(!).Low-level implementation of x2: represents integers as big-headian qubit lists.yComparison of two I"s, considered as signed. Used in  instance  I. O(!).zText whether a I is nonnegative. O(1) Multiply two ICs into a fresh third. Arguments are assumed to be of equal size. O (![sup 2]).Low-level implementation of 2: represents integers as big-headian qubit lists.{ Reduce one IG modulo another, in place, returning also the integer quotient, i.e. (x, y) ! (x mod y, y, x div y}). All inputs and outputs are considered unsigned. Inputs are assumed to have the same length. Division by zero returns (x,0,-1).O(![sup 2]) gates, O (!) qubits.Low-level implementation of {2: represents integers as big-headian qubit lists.Implementation note: this algorithm can be optimized significantly: [scratch] is always 0, so can be optimized away. This optimisation is much clearer at the circuit level than the code level, however, so is deferred for now.| Reduce one I modulo another, i.e. (x, y) ! (x, y, x mod yf). All inputs and outputs are considered unsigned. Inputs are assumed to have the same length. If y = 0, returns (x,0,x).O(![sup 2]) gates, O (!) qubits.}Integer division of two I0s, returning the quotient and remainder, i.e. (x,y) ! (x,y,x div y,x mod y). All inputs and outputs are considered unsigned. Inputs are assumed to have the same length. Division by zero returns (-1,x).O(![sup 2]) gates, O (!) qubits.~Integer division of two Is, returning just the quotient. All inputs/outputs considered unsigned. Inputs are assumed to have the same length. Division by zero returns 1.O(![sup 2]) gates, O (!) qubits.Low-level version of ~2: represents integers as big-headian qubit lists.Integer division of two Is into a fresh third, rounding towards ". The first argument is the numerator, and is assumed to be signed. The second argument is the denominator, and is assumed to be unsigned. The output is signed. Inputs are assumed to have the same length.O(![sup 2]) gates, O (!) qubits.Low-level implementation of 2: represents integers as big-headian qubit lists.Integer division of two Is into a fresh third, rounding towards 0. The first argument is the numerator, and is assumed to be signed. The second argument is the denominator, and is assumed to be unsigned. The output is signed. Inputs are assumed to have the same length.O(![sup 2]) gates, O (!) qubits.Low-level implementation of 2: represents integers as big-headian qubit lists.Integer division of two Is, returning the quotient, assuming that the second exactly divides the first and throwing an error otherwise. All inputs/outputs considered unsigned. Inputs are assumed to have the same length.O(![sup 2]) gates, O (!) qubits.Integer division of two Is, returning the quotient, assuming that the second exactly divides the first. The first argument is the numerator, considered signed. The second argument is the denominator, considered unsigned. The output is signed.O(![sup 2]) gates, O (!) qubits.Euclid's extended algorithm.  a b : returns (a,b,x,y,d ) such that ax + by = d = gcd(a,b).Quantum lifting of the  operator.F?@AEBCDFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~FJIHG`abcdefYZ[\]^_TUSOPjLViklWXghNMKQR?@AEBCDFmnopvqrstuwxyz{|}~&None>HV J&7Extract the list of wires from a piece of quantum data.Translates a Quipper circuit to a simple circuit. The only gates considered are initializations, terminations, and multi-controlled NOT gates. All other gates are ignored.Note that simple circuits do not possess termination wires: these wires are simply not terminated, and all subsequent initializations using the same wire ID are sent to fresh wires.hThe state of this function is a bit complex, as it keeps track of where the output wires are mapped to.FGet the wire initialized by the gate, if it is an initialization gate.CGiven a list of Quipper gates, get the smallest wire id not in use.Send a Quipper  to a c.Send a Quipper  to a c. Generate a custom error message.Given a Quipper circuit generating function and a shape argument, return a simple circuit together with the list of non-garbage circuit outputs.CTranslate a gate from the simple circuit model into a Quipper gate.Generate a Quipper comment. The first argument is a comment string, and the second argument is a label to apply to the qubits in the third argument.Optimize a Quipper . The second argument is the list of non-garbage outputs. A corresponding list of outputs is also returned along with the circuit.|Optimize a Quipper circuit producing function (together with a shape argument). Return the optimized circuit as a Quipper 7, along with a list of the non-garbage circuit outputs.5Optimize a Quipper circuit-producing function. This assumes that the function only consists of pseudo-classical quantum gates, i.e., initializations, terminations, and (possibly multiply controlled) NOT gates. The behavior on other kinds of circuits is undefined. The second argument is a shape parameter.Like A&, but also apply circuit optimization.Like :, but insert the optimized circuit as a boxed subroutine.KNone>HV K'None>HV SbApply the binary WG-gate to a pair of qubits. The W-gate diagonalizes the SWAP operation. Apply the inverse of the W-gate. Note: since the W3-gate is self-inverse, this is really the same as ?. However, we define this as a separate function for clarity. :Apply a doubly-controlled not gate to a triple of qubits (a, b, c). Here the qubit c is negated if a=1 and b=0.controlledExpGate(t, r, h): Apply the [exp x_x_UNI8722_x_xiZt] gate to the qubit h, provided that r=0. (None>HV A data structure to hold an oracle. The binary welded tree algorithm is parametric on an oracle. An oracle encodes a graph, and provides the following information: the tree depth n. (in the above example: 3), the label length m? (in bits; 5 in the above example), the number of edge colors k, the entrance label ENTRANCE', and for each color 0 x_x_UNI8804_x_x c < k, a reversible circuit ORACLE[sub c](a,b,rW). On basis vectors, this circuit encodes the edge information in the following sense: [ORACLE[sub c](a, b, r) = (a, b x_x_UNI8853_x_x v[sub c](a), r x_x_UNI8853_x_x f[sub c](a)),where f[sub c](a) is 1 if the node a# is connected to an edge of color c, and 0 otherwise; and v[sub c](a') is the node label connected to node a along an edge of color c% (if any), and arbitrary otherwise. yNot all available node labels need to be used (for example, 0 and 16 are unused in the graph in the above illustration).3The main loop of the binary welded tree algorithm. qrwbwt oracle s dtJ: Do a quantum random walk on the binary welded tree given by the oracle oracle, for s times steps of length dtD. Returns a bit list corresponding to the computed exit node label.timestep (a, b, r, dt, m): Perform a single time step dt of the quantum walk. This is done by iterating through each of the available edge colors, and performing a diffusion step for each color. Here, a is an mG-qubit registers holding (a superposition of) the current node label. b is an m-qubit ancilla register, and r is an ancilla qubit. Both b and rv are expected to be initialized to |0x_x_UNI9002_x_x by the caller, and will be returned in state |0x_x_UNI9002_x_x.=The top-level oracle circuit. The arguments are of the form (a, b, r, color, f, g, n ), where a, b" are quantum registers of length n+2, color) is a boolean register of length 2, and f and g! are boolean registers of length n.Input a node label a of length at least n+1. Negate both root and even if a is a root node.Input a node label a of length at least n +1. Negate even if the node a& occurs at an even height in the tree.Input a node label a! of length at least 1, and flags root and even describing whether a7 is a root and at an even level, respectively. Negate isparent if a has a parent of color color in the tree.  The qubit ismatch is an ancilla, and really is either 0 or 1. They are jointly used to control uncomputation, so that the following sequence will compute and then uncompute : ismatch <- qinit 0 testIsParent (a, root, even, isparent, color, n, 1, ismatch) testIsParent (a, root, even, isparent, color, n, 0, ismatch) qterm 0 ismatchConsider a node a , and negate ischild if a has a child node of color color . Also set  direction= to indicate whether it is a "left" or "right" child. Here, colorZ is a boolean register of length 2, representing a color. This function is self-inverse.Input a node label a of length at least n+2, and a flag isparent? that has been initialized accordingly. Also input a register b of length at least n++2, initialized to |0x_x_UNI9002_x_x. If isparent is set, set b% to the node label of the parent of a. This is self-inverse. Similar to  , but set b. to the node label of the indicated child of a. Here a and b+ are quantum registers of length at least n+2, and f and g" are boolean registers of length n.A special case of O, where the child is inside the same binary tree (i.e., not via the welding). A special case of \, where the child is in the opposite binary tree, i.e., we follow one of the welding edges.Input a node label a, and a register b' initialized to |0x_x_UNI9002_x_x. If weldctrl is set, set b to the node connected to a by the welding function f. This is self-inverse. Here, a and b* are quantum registers of length at least n+2, and f" is a boolean register of length n.Input a node label a, and a register b' initialized to |0x_x_UNI9002_x_x. If weldctrl is set, set b to the node connected to a by the welding function g. This is self-inverse. Here, a and b* are quantum registers of length at least n+2, and g" is a boolean register of length n.EThis function implements integer addition. Input a quantum register input and a boolean register num1, representing integers, and a quantum register out' initialized to |0x_x_UNI9002_x_x. If control is set, set out to input + num, otherwise do nothing. Here input and out+ are quantum registers of length at least n, num! is a boolean register of length n.9A helper function for clearing the scratch space used by .Like %, except subtract instead of adding. 9A helper function for clearing the scratch space used by .+This function inputs two welding functions f and g>, and returns the oracle defined by the preceding functions. We call this the "orthodox" oracle, because the implementation follows its specification very closely. For example, it uses a very "imperative" programming style. For alternative implementations of this and other oracles, see the modules "Quipper.Algorithms.BWT.Alternative and Quipper.Algorithms.BWT.Template.QOutput the circuit for the quantum walk and a binary welded tree, for the given  in the specified  and using the specified 1. Use s time steps of length dt.!Output the circuit for the given ' and the given color (specified as an ). Use the specified output  and 1.)None>HV Inputs an oracle and prints out a list of colored edges in text format. This is done by simulating the circuit for every possible input, decomposed to the given 1.Input an oracle and output the colored edges in graphical format. This is done by simulating the circuit for every possible input. The second parameter is a boolean which determines whether the node numbering follows the schema of the orthodox oracle (Y) or the simple oracle ([). Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate ( on all possible inputs for tree height n.  Simulate  (including )) on all possible inputs for tree height n.  Simulate  (including )) on all possible inputs for tree height n. FReturn the smallest number of bits required to hold the given integer.Run simulations of , , , , , , , , , , , and  for tree height n.*None>HVD1Like ,, but uses qubits instead of classical bits.;The type of nodes: a pair of a tree bit and a node address.;The type of nodes: a pair of a tree bit and a node address.This is a version of  that uses  instead of C. An oracle provides the following information: the tree depth n, the label length m, the number of edge colors k, the entrance label ENTRANCE', and for each color 0 x_x_UNI8804_x_x c < k, a reversible circuit ORACLE[sub c](a,b,r). Convert an  Alternative. into a BWT..MDo a quantum random walk on the binary welded tree given by the oracle, for s times steps of length dtn. Return a bit list corresponding to the probable exit label. This is a more functional implementation of  from the module Quipper.Algorithms.BWT.BWT.kNote: This implementation does not rely on the oracle being self-inverse, and therefore only requires that 8ORACLE[sub c](a, 0, 0) = (a, v[sub c](a), f[sub c](a)), &rather than the more general property  ]ORACLE[sub c](a, b, r) = (a, b x_x_UNI8853_x_x v[sub c](a), r x_x_UNI8853_x_x f[sub c](a)). NThis gives us the freedom to build more efficient oracles, where appropriate.1Apply one round of the Hamiltonian for time step dt to a.Apply the diffusion step to (a,b,r). Here a and b must be of equal length.(Apply the basis change from Figure 3 of  Childs et al. to a, b, and h. Here a and b must be of equal length.OCompute the required number of iterations as a function of x_x_UNI949_x_x and dt.Inputs: n= is the tree depth, x_x_UNI949_x_x is the desired precision, dt4 is the simulation time step. Intermediate values: t" is the simulation time. Output: s:, the upper bound on the number of simulation time steps.Note:  Childs et al specifies that t? should be chosen uniformly at random within the interval 0 < t x_x_UNI8804_x_x n<[sup 4]/2x_x_UNI949_x_x. Here, for simplicity, we just use t = x_x_UNI8970_x_xn[sup 4]/2x_x_UNI949_x_xx_x_UNI8971_x_x. Also note that this function is for information only, as it is not actually used. Users should specify s directly.A blackbox oracle for testing. This just produces a labelled box in place of the actual oracle circuit. The argument is the tree height.This oracle, which works only for the fixed tree height 3, works by explicitly listing all the edges. It serves only to illustrate how the edge information is encoded. Listing all edges explicitly obviously would not scale well to larger graphs..Convert integers to nodes, mainly for testing..Convert nodes to integers, mainly for testing.Convert a bit vector to a node.Convert a node to a bit vector. Input a node a and return the parent of a. We assume that a is not a root or invalid. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y, respectively). Assumes that a is not a leaf. [ is a one-bit adder, and  Y; is a one-bit subtracter (i.e., add the 2's complement of y). Input an n+1-bit leaf node a:aa (without the tree bit; a is the highest bit and aa is the remaining n bits) and a sign s (where Y = negative, [ = positive). Return a:(aa + s * f). The first input is the n-bit welding vector f( (a parameter to the oracle). Note that f is a parameter and s, aa are inputs. Input an n+1-bit leaf node a:aa% (without the tree bit), and return a:(aa x_x_UNI8853_x_x g). The first input is the n-bit welding vector g (a parameter to the oracle).Input a leaf node a& and return the left or right weld of a. in the other tree (depending on whether the weldbit is [ or Y). Assumes that a is a leaf. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y*. This works for leaf and non-leaf nodes.sInput a node address (without the tree bit) and return the parity of the node level expressed as a boolean either [ or Y. Leaves have parity [k, and other levels have alternating parities. In other words: count the number of leading zeros modulo 2.7Input a node address (without the tree bit) and return Y: iff the node address is invalid. In other words, return Y# iff the list consists of all 0's.7Input a node address (without the tree bit) and return Yd iff the node is a root or invalid. In other words, check whether all digits but the last are 0's. f g c a : returns v[sub c](a'), the label of the node connected to a by an edge of color c, or P+ if there is no such node. The parameters f and g8 encode the welding functions, and are lists of length n. c$ is a color in the range 0..3, and a is an (n+2)-bit node label. Convert a  to a . Convert a  to a .&Exclusive or operation on bit vectors. Input a node a and return the parent of a. We assume that a is not a root or invalid. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y, respectively). Assumes that a is not a leaf. [ is a one-bit adder, and  Y; is a one-bit subtracter (i.e., add the 2's complement of y). Input an n+1-bit leaf node a:aa (without the tree bit; a is the highest bit and aa is the remaining n bits) and a sign s (where Y = negative, [ = positive). Return a:(aa + s * f). The first input is the n-bit welding vector f( (a parameter to the oracle). Note that f is a parameter and s, aa are inputs. Input an n+1-bit leaf node a:aa% (without the tree bit), and return a:(aa x_x_UNI8853_x_x g). The first input is the n-bit welding vector g (a parameter to the oracle).Input a leaf node a& and return the left or right weld of a. in the other tree (depending on whether the weldbit is [ or Y). Assumes that a is a leaf. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y*. This works for leaf and non-leaf nodes.sInput a node address (without the tree bit) and return the parity of the node level expressed as a boolean either [ or Y. Leaves have parity [k, and other levels have alternating parities. In other words: count the number of leading zeros modulo 2.7Input a node address (without the tree bit) and return Y: iff the node address is invalid. In other words, return Y# iff the list consists of all 0's.7Input a node address (without the tree bit) and return Yd iff the node is a root or invalid. In other words, check whether all digits but the last are 0's. f g c a : returns v[sub c](a'), the label of the node connected to a by an edge of color c, or P+ if there is no such node. The parameters f and g8 encode the welding functions, and are lists of length n. c$ is a color in the range 0..3, and a is an (n+2)-bit node label.We currently implement  + as an indexed union, and specifically as (,). When Bit=Y, the value of O is undefined (doesn't matter); in particular, this value may contain garbage.7The classical oracle implementation, packaged into the K abstraction. This oracle has two parameters, namely the welding vectors f and g7. Note: this oracle has not been optimized whatsoever.?Output the list of colored edges as computed by the classical , for some arbitrary choice of f and g and n=3.For debugging:  is similar to , except it works by calling u to assemble the circuit, then simulates it. This is for testing whether the assembled circuit is correct. Returns (J, ) instead of  M, so that we can see any garbage that is output in case of an invalid node.HOutput the list of colored edges as computed by simulating the circuit , for some arbitrary choice of f and g and n=3. This is like D, except it actually assembles and simulates the classical circuit.:Graphically output the classical oracle circuit for color c , using n9 from the oracle data structure, and for some arbitrary f and g.Like F, except it rewrites the classical circuit in terms of Toffoli gates.Like :, except it makes the classical circuit reversible first. Output the top-level circuit for the binary welded tree algorithm with the classical oracle, using some arbitrary welding vectors f and g, and s=1.7 7 +None =>?HVy  Exclusive or operation on bit vectors.    [ is a one-bit adder, and   Y; is a one-bit subtracter (i.e., add the 2's complement of y). Input a node a and return the parent of a. We assume that a is not a root or invalid. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y, respectively). Assumes that a is not a leaf. Input an n+1-bit leaf node a:aa (without the tree bit; a is the highest bit and aa is the remaining n bits) and a sign s (where Y = negative, [ = positive). Return a:(aa + s * f). The first input is the n-bit welding vector f( (a parameter to the oracle). Note that f is a parameter and s, aa are inputs. Input an n+1-bit leaf node a:aa% (without the tree bit), and return a:(aa x_x_UNI8853_x_x g). The first input is the n-bit welding vector g (a parameter to the oracle).Input a leaf node a& and return the left or right weld of a. in the other tree (depending on whether the weldbit is [ or Y). Assumes that a is a leaf. Input a node a' and return the left or right child of a (depending on whether the childbit is [ or Y*. This works for leaf and non-leaf nodes.sInput a node address (without the tree bit) and return the parity of the node level expressed as a boolean either [ or Y. Leaves have parity [k, and other levels have alternating parities. In other words: count the number of leading zeros modulo 2.7Input a node address (without the tree bit) and return Y: iff the node address is invalid. In other words, return Y# iff the list consists of all 0's.7Input a node address (without the tree bit) and return Yd iff the node is a root or invalid. In other words, check whether all digits but the last are 0's.   f g c a : returns v[sub c](a'), the label of the node connected to a by an edge of color c, or P+ if there is no such node. The parameters f and g8 encode the welding functions, and are lists of length n. c$ is a color in the range 0..3, and a is an (n+2)-bit node label.!$A color is a number between 0 and 3.#MConvert an integer representation of a color into the two-bit representation.$ This is the  irreversible# classical circuit generated from   . This is basically the same as "!, except that excessive uses of  N are removed from the type, and the inputs and outputs have been reorganized.% This is the  reversible& circuit automatically generated from $. & This is the  reversible& circuit automatically generated from $,, and optimized with peep-hole optimization.''The template oracle, packaged into the  abstraction. Note that this circuit is automatically generated from the classical functions above, but is completely unoptimized. This oracle has two parameters, namely the welding vectors f and g.(The template oracle, optimized. First color bit.Second color bit.Vector f from Equation (26).Vector g from Equation (27). Entry node a.(Y, exit node) or ([ , garbage).$ The color.#The two welding vectors and a node a.Output (r,b).%Color.(f, g, a, r, b).Output (f, g, a, r, b).&Color.(f, g, a, r, b).Output (f, g, a, r, b).     !"#$%&'(     "!#$%&'(,None>HVf)7A data type to hold values set by command line options.+What kind of thing to output.,The output format.-%What kind of gates to decompose into..Which kind of oracle to use./The tree height.0The color to use with --oracle.1The parameter s to use.2The parameter dt to use.3,An enumeration type for selecting an oracle.4The "orthodox" oracle. 5The "simple" oracle.6A blackbox oracle.7+An oracle generated from classical program.89An oracle automatically generated using Template Haskell.9VAn oracle automatically generated using Template Haskell, with peep-hole optimization.:EAn enumeration type for determining what the main function should do.;Show the whole circuit.<Show only the oracle.=3Show colored edges computed from oracle simulation.>3Show the "classical" oracle as a classical circuit.?0Run simulations of individual circuit fragments.@The default options.A<The list of command line options, in the format required by .B4An enumeration of available oracles and their names.CProcess argv$-style command line options into an ) structure.DPrint usage message to .E?Main function: read options, then execute the appropriate task.FCompute the appropriate < for the given options.)*.-+,20/13965478:>;<?=@ABCDEF:>;<?=3965478)*.-+,20/1@ABCDEFLMNLMOPQRSTUVWXXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~E      !"#$%&'()*+,-./0123344556789:DB;<=>?C@ABCDEFGHHIIJKLMNOPQRRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                        7                       ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W XYZ[\]^_`abcdeffVghijklmmnoopqrstuvhigwxyz{|}~O      !"#$%&'()*+,-./012345627789:;<=>?@ABCDEFGHIJKLMNCOP@ABDQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~I/8-.      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN9:OPQR@STUVWXYZ[N\]^_`abcdefghijklmnopqrstuvwxyAz{645|}~<;      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN=OPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~   ?                        !!!!!!!!!!!!!!!!!!!!!! ! ! ! ! """""""""""""""#### #!#"###$#%#&#'#(#)#*#+#,#-#.#/#0#1#2#3#4#5#6#7#8#9#:$;$<$=$>$?$@$A$B$C$D$E$F$G$H%I%J%K%L%M%N%O%P%Q%R%3%S%T%U%V%W%X%Y%Z%[%\%]%^%_%`%a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~%%%%%%%%%%%%%%%%%%%%b%%%%%%%%%%%&&&&&&&&&&&&&&&''''((((((((((((((((((((((((((())))))))))))))))*******************************************************++ ++ ++ ++ ++ +++++++++++++++++++++,,,,,,,, ,/,!,",#,$,%,,&,',(,6,,),*,+,,,-,.,/,0,,1,2,3,456789:8;<8;=8>?@ABCDEFAGHAIJAIKALMNOP56QARS56T5UVAWX56YPQZAIAI[AI\A]^AI_AR`AabARcAdeARfARghijklmnopqrstuvwxyz{|}~AIAAaA5U565U5U5U5UA]AR   AA%%%%%%%%%%%%%%%%%%%%%%%%%%%%AA56%A%%%%%%%%%%%%AABAAmainQuipper.Utils.TemplateQuipper.Utils.SamplingQuipper.Utils.Auxiliary(Quipper.Libraries.ClassicalOptim.Circuit'Quipper.Libraries.ClassicalOptim.AlgExp/Quipper.Libraries.ClassicalOptim.SimplificationQuipper.Internal.CircuitQuipper.Internal.TransformerQuipper.Utils.CommandLineQuipper.Utils.PreviewQuipper.Utils.RandomSourceQuipper.Utils.Stabilizers.Pauli"Quipper.Utils.Stabilizers.Clifford Quipper.Utils.Template.Auxiliary Quipper.Utils.Template.ErrorMsgQQuipper.Utils.Template.LiftQQuipper.Utils.Template.LiftingQuipper.Utils.TupleQuipper.Internal.ControlQuipper.Internal.MonadQuipper.Internal.LabelsQuipper.Internal.QDataQuipper.Internal.GenericQuipper.Internal.QClassesQuipper.Internal.PrintingQuipper.Internal.ClassicalQuipper.Internal.CircLiftingQuipper.Libraries.Synthesis.Quipper.Libraries.Simulation.QuantumSimulation0Quipper.Libraries.Simulation.ClassicalSimulation/Quipper.Libraries.Simulation.CliffordSimulationQuipper.Libraries.Qureg$Quipper.Libraries.GateDecompositions"Quipper.Libraries.Decompose.Legacy%Quipper.Libraries.Decompose.CliffordT$Quipper.Libraries.Decompose.GateBaseQuipper.Libraries.Arith1Quipper.Libraries.ClassicalOptim.QuipperInterface"Quipper.Algorithms.BWT.DefinitionsQuipper.Algorithms.BWT.BWTQuipper.Algorithms.BWT.Simulate"Quipper.Algorithms.BWT.AlternativeQuipper.Algorithms.BWT.TemplateQuipper.Algorithms.BWT.Main qcdata_zipqcdata_promote Control.MonadzipWithMQuipperBitQDInt.==../=..&&.Qubitcommentqinitqtermwith_basis_change with_computedclassical_to_reversibleQuipper.Utils.TypeableQuregqc_initqshapeCGateCInitCNotbool_xorQuipper.InternalData.Number.FixedPrec FixedPrecQuipper.Libraries.SimulationQuipper.Libraries.Decompose Quipper.Libraries.ClassicalOptimtemplate-haskellLanguage.Haskell.TH.SyntaxQDec!random-1.1-3ypV4EIycgb35PKjTYYr5q System.RandomRandomCurrymcurrymuncurryErrMsgIdentityIdgetIdStrbufBListBoollistXIntMapapplyAt overwriteAthas_duplicates substituteintset_inserts map_provide intmap_zipintmap_zip_errmsg intmap_map intmap_mapMxintmap_deletexintmap_deletesxintmap_insertxintmap_insertsxintmap_lookupxintmap_member xintmap_emptyxintmap_freshkeyxintmap_freshkeysxintmap_to_intmap xintmap_size xintmap_dirtyxintmap_reservesxintmap_unreservesxintmap_makecleanloop_with_indexloop_with_indexMlooploopMsequence_rightsequence_right_ zip_strictzip_strict_errmsgzip_rightstrictzip_rightstrict_errmsgzipWith_strictzipWith_rightstrictzipRightWithRightStrictMzipRightWithRightStrictM_foldRightPairMfoldRightPairM_fold_right_zipfold_right_zipMforendforforeachmmap monad_join1 map_either map_eitherMmap_pair map_pairM int_ceilingboollist_of_int_bhboollist_of_int_lhint_of_boollist_unsigned_bhint_of_boollist_signed_bh boollist_xorstring_of_listoptional blist_of_list list_of_blist+++ blist_empty blist_concatstrbuf_of_stringstring_of_strbuf strbuf_empty strbuf_concat reflexivitysymmetry transitivityidentity $fShowXIntMap $fShowBList $fFunctorId$fApplicativeId $fMonadId$fShowIdentity$fCurry->(,)res $fCurryb()bCirc CircStateCScircuit freshWireGateNoOpInitCnotWire wireOfGate ctlsOfGateevalCirc emptyStategetFreshincrementFreshaddGateextractCircuitinitcnot printCircuitprint_quipperStyle $fFunctorCirc$fApplicativeCirc $fMonadCirc $fShowGate$fEqGate$fShowCircStateExpmapOfSetsetOfMap split_even listOfExp expOfListexp_andexp_xor exp_falseexp_trueexp_notexp_var vars_of_expexp_evalvaluations_of_varstruth_table_of_expexp_of_truth_table $fShowSetEvalCircExpState gates_to_skipallWiresInCircgateIdusedControlWires usedNotWiresfuturepastexpMapfreshVaroutWiressizeCircUsedWire GateIdSetGateIdtracemoveWireflipCtl moveWireFlipsuppress_garbagesuppressGarbageGates getAllWires getInitWires getInputWires compressWires gateIdFindMin gateIdFindMax pairUsedWire firstUsedWire lastUsedWire nextUsedGatecircuitControlWirescircuitNotWires exp_length exp_list_and expEvalCtl expEvalGate initExpState runEvalCirc getExpState setExpState newFreshVar pullNewGate changeFuture updateFuture storeOldGate incrGateIdgetAllWiresInCircsetAllWiresInCircremoveFromAllWiresInCirc getExpMap setExpMapupdateUsedControlWiresupdateUsedNotWiresupdateOutWiresaddToSkipGates sendEndOfTime shiftGate pairEqualExp pruneListExp stepEvalCirc stepSwapCircstepSwapCirc_simplerunWhile stripNoOp alg_simplifyalg_swapalg_swap_simple is_equal_list get_list_init simplRec'simplRec $fNFDataGate$fFunctorEvalCirc$fApplicativeEvalCirc$fMonadEvalCirc DBCircuit ReadWrite RW_ReturnRW_WriteRW_Read RW_Subroutine OBCircuitBCircuit NamespaceTypedSubroutineCircuitTypeStructureOCircuitCircuitExtArityQGateQRotGPhaseCGateInvCSwapQPrepQUnprepQInitQTermCTermQMeasQDiscardCDiscardDTerm SubroutineComment RepeatFlagBoxIdControllableFlagNoCtlAllCtlOnlyClassicalCtl NoControlFlag InverseFlagTimestepControlsSignedArityWiretypeQbitCbit from_signedget_sign gate_arity gate_controls gate_ncflaggate_with_ncflag gate_reversewires_of_controls wires_of_gatewirelist_of_gatearity_append_safearity_append_unsafe arity_append arity_emptyarity_unused_wirearity_unused_wires arity_allocarity_of_extarity n_of_extaritywirelist_of_circuitreverse_gatelistreverse_circuitcircuit_to_nocontrolreverse_ocircuitid_CircuitTypeStructuredestructure_withstructure_withcircuit_of_typedsubroutinenamespace_empty showNames ob_circuitreverse_bcircuitreadwrite_wrapreadwrite_unwind_staticgatelist_of_readwritebcircuit_of_static_dbcircuitdbcircuit_of_bcircuit$fShowRepeatFlag$fFunctorReadWrite$fApplicativeReadWrite$fMonadReadWrite$fShowWiretype $fEqWiretype $fShowSigned$fEqControllableFlag$fOrdControllableFlag$fShowControllableFlag $fEqBoxId $fOrdBoxId $fShowBoxId$fEqRepeatFlag$fOrdRepeatFlagDynamicTransformerDT transformerdefine_subroutinelifting_functionBT TransformerT_GateT_QGateT_QRotT_GPhaseT_CNotT_CGate T_CGateInvT_CSwapT_QPrep T_QUnprepT_QInitT_CInitT_QTermT_CTermT_QMeas T_QDiscard T_CDiscardT_DTerm T_Subroutine T_CommentCtrlsBindings B_EndpointEndpoint_Qubit Endpoint_Bitwires_of_bindingsbindings_emptybindbind_qubit_wire bind_bit_wireunbindunbind_qubit_wireunbind_bit_wire bind_delete bind_listbind_qubit_wire_listbind_bit_wire_list unbind_listunbind_qubit_wire_listunbind_bit_wire_list bind_controlsunbind_controls bind_gatetransform_circuittransform_bcircuit_rectransform_bcircuit_idtransform_dbcircuit $fShowT_Gate$fEqB_Endpoint$fOrdB_Endpoint$fShowB_Endpointoptfail parse_intparse_list_int parse_double match_enum show_enumtry_several_IOsystem_pdf_viewerwindows_pdf_viewermacos_pdf_viewerlinux_pdf_viewer RandomSource$fShowRandomSourceMatrix2Matrix1SignPlusMinusIPlusIOneSignPlusMinusPauliIXYZnegativenegate multiply_signmultiply_signPlussignPlus_to_sign levi_civitakronecker_deltacommute toMatrix1scale1 fromMatrix1multiplyMatrix1 transpose1my_Ytensor1control1 toMatrix2scale2 fromMatrix2multiplyMatrix2 transpose2my_IY $fShowSign$fShowSignPlus $fShowPauli $fEqPauli $fOrdSign$fEqSign CliffordCirc MinUnitary2 MinPauli2IXXIIZZIUnitary2 MinUnitaryMinPauliXminZminUnitaryTableauST next_qubitsigntableaude_sign de_tableaulookup empty_tableau add_qubit from_minimal from_matrix apply_unitaryapply_unitary_row from_minimal2 from_matrix2from_matrix_controlledapply_unitary2measurereducemultiply multiply_dexx_minx'x''yy_miny'y''zz_minz'z''hh_minh'h''ss_mins's''ee_mine'e''cnot_mincnot'cnot''czcz_mincz'cz'' init_qubit init_qubitsgate_Xgate_Ygate_Zgate_Hgate_S gate_Unitary controlled_X controlled_Z gate_Unitary2 measure_qubitmeasure_qubits show_tableauevalsimswap controlled_Z'bellmeasure_bell00 controlled_ifteleport test_teleport random_bool $fShowTableau$fEq->$fEq->0template_symb_colon_%template_symb_obracket_symb_cbracket_ template_init template_lasttemplate_symb_plus_symb_plus_ template_zip3template_foldltemplate_reversetemplate_zipWithtemplate_fold_right_ziptemplate_symb_dollar_template_error template_sndErrMsgQerrorMsgembedQextractQ$fFunctorErrMsgQ$fApplicativeErrMsgQ$fMonadErrMsgQLiftQ LiftQState LiftStateboundVarprefix monadNameemptyLiftStategetStatesetState embedErrMsgQ addToBoundVarremoveFromBoundVar withBoundVar withBoundVars isBoundVar setPrefix getPrefix setMonadName getMonadNamemkNamenewNamesanitizeStringtemplateStringlookForTemplatemakeTemplateName prettyPrint clauseGetPatsequalNEListEltsclausesLengthPats$fFunctorLiftQ$fApplicativeLiftQ $fMonadLiftQBindSVarEConELitEAppELamETupECondELetECaseEListEReturnEMAppEValDMatchPatLitPVarPTupPWildPListPConPLitCharLIntegerL RationalLBodydoE getVarNames substMatchsubstDecsubstExp mapSubstExp litTHtoExpAST litTHtoPatASTnormalizePatInExp whereToLet clauseToMatchclausesToLambda expTHtoAST matchTHtoAST bodyTHtoAST patTHtoASTfirstLevelDecTHtoAST decTHtoAST typReturnEtypMAppE litASTtoTH patASTtoTH matchASTtoTH decASTtoTH expASTtoTH liftIntegerL liftRationalL liftLitAST liftPatAST liftMatchAST liftDecASTliftFirstLevelDecAST liftExpASTmakeDecTemplateprettyPrintASTprettyPrintLiftExpTHprettyPrintLiftExpAST decToMonad expToMonad $fShowLit $fShowPat $fShowExp $fShowDec $fShowMatchTupletupleuntuple TupleOrUnary weak_tuple weak_untuple$fTupleOrUnary(,,,,,,,,,)(,)$fTupleOrUnary(,,,,,,,,)(,)$fTupleOrUnary(,,,,,,,)(,)$fTupleOrUnary(,,,,,,)(,)$fTupleOrUnary(,,,,,)(,)$fTupleOrUnary(,,,,)(,)$fTupleOrUnary(,,,)(,)$fTupleOrUnary(,,)(,)$fTupleOrUnary(,)(,)$fTupleOrUnarya(,)$fTupleOrUnary()()$fTuple(,,,,,,,,,)(,)$fTuple(,,,,,,,,)(,)$fTuple(,,,,,,,)(,)$fTuple(,,,,,,)(,)$fTuple(,,,,,)(,)$fTuple(,,,,)(,)$fTuple(,,,)(,)$fTuple(,,)(,) $fTuple(,)(,) $fTuple()()ZerozeroIntervalinterval sample_all sample_step sample_random sample_all0 sample_step0sample_random0 $fRandom[]$fRandom(,,,,,,)$fRandom(,,,,,)$fRandom(,,,,) $fRandom(,,,) $fRandom(,,) $fRandom(,) $fRandom() $fInterval[]$fInterval(,,,,,,)$fInterval(,,,,,)$fInterval(,,,,)$fInterval(,,,)$fInterval(,,) $fInterval(,) $fInterval()$fIntervalBool$fIntervalDouble$fIntervalInteger $fIntervalInt$fZero[]$fZero(,,,,,,) $fZero(,,,,,) $fZero(,,,,) $fZero(,,,) $fZero(,,) $fZero(,)$fZero() $fZeroBool $fZeroDouble $fZeroInteger $fZeroInt ControlSource to_control ControlList Inconsistent clist_empty clist_addcombinecombine_controlsadd_to_controls control_gatecontrol_gate_catch_allcontrollable_gatecontrollable_circuit$fControlSource(,,,,,,)$fControlSource(,,,,,)$fControlSource(,,,,)$fControlSource(,,,)$fControlSource(,,)$fControlSource(,)$fControlSource()$fControlSource[]$fControlSourceControlList$fControlSourceSigned$fControlSourceInt$fControlSourceBool$fShowControlListBitlistQulistCtrlEndpointput_subroutine_definition get_namespace set_namespaceextract_simpleextract_general wire_of_qubit wire_of_bit qubit_of_wire bit_of_wirewire_of_endpointwires_with_arity_of_endpointsendpoint_of_wireendpoints_of_wires_in_arity bind_qubitbind_bit unbind_qubit unbind_bitclist_add_qubit clist_add_bitprovide_simple_subroutineprovide_subroutinesprovide_subroutineqnothadamardqmultinot_listcmultinot_list gate_S_invgate_T gate_T_invgate_E gate_E_inv gate_omegagate_V gate_V_inv swap_qubitswap_bitexpZtrGategate_Wgate_iX gate_iX_inv global_phaseglobal_phase_anchored_listnamed_gate_qulistnamed_rotation_qulistqnot_at hadamard_at gate_H_atqmultinot_list_atcmultinot_list_at gate_X_at gate_Y_at gate_Z_at gate_S_at gate_S_inv_at gate_T_at gate_T_inv_at gate_E_at gate_E_inv_at gate_omega_at gate_V_at gate_V_inv_at swap_qubit_at swap_bit_atexpZt_atrGate_at gate_W_at gate_iX_atgate_iX_inv_atnamed_gate_qulist_atnamed_rotation_qulist_atcnot_at qinit_qubit qterm_qubitqdiscard_qubit prepare_qubitunprepare_qubit cinit_bit cterm_bit dterm_bit cdiscard_bit cgate_xorcgate_eq cgate_if_bit cgate_not cgate_andcgate_orcgatecgateinv subroutinecall_subroutine comment_labelwithout_commentsdynamic_lift_bitqinit_plusminus qinit_of_charqinit_of_string qinit_list qterm_list cinit_list with_ancilla with_controls controlledwithout_controlswithout_controls_ifqinit_qubit_ancillaqterm_qubit_ancillaidentity_transformeridentity_dynamic_transformerapply_circuit_with_bindingsapply_bcircuit_with_bindingsapply_dbcircuit_with_bindingsextract_in_contextextract_in_current_namespaceunextract_in_contextreverse_encapsulated with_reserve$fControlSourceB_Endpoint$fMonadFailCirc$fControlSourceQubit$fControlSourceSigned0$fControlSourceBit$fControlSourceSigned1 $fShowQubit $fEqQubit $fOrdQubit $fShowBit$fEqBit$fOrdBit Labelable label_rec LabelMonad getLabelMonad IndexListindexlist_formatindexlist_emptyindexlist_subscriptindexlist_dottedlabelmonad_get_indexlistlabelmonad_put_bindinglabelmonad_with_indexlistlabelmonad_run label_wire with_indexwith_dotted_indexindexeddotted_indexed label_emptymklabellabelcomment_with_label$fFunctorLabelMonad$fApplicativeLabelMonad$fMonadLabelMonad$fLabelableChar[]$fLabelableFloat[]$fLabelableDouble[]$fLabelableInt[]$fLabelableInteger[]$fLabelableB_EndpointB_Endpoint$fLabelableB_Endpoint[]$fLabelable[][]$fLabelable[][]0!$fLabelable(,,,,,,,,,)(,,,,,,,,,)$fLabelable(,,,,,,,,)(,,,,,,,,)$fLabelable(,,,,,,,)(,,,,,,,)$fLabelable(,,,,,,)(,,,,,,)$fLabelable(,,,,,)(,,,,,)$fLabelable(,,,,)(,,,,)$fLabelable(,,,)(,,,)$fLabelable(,,)(,,)$fLabelable(,)(,)$fLabelable(,,,,,,,,,)[]$fLabelable(,,,,,,,,)[]$fLabelable(,,,,,,,)[]$fLabelable(,,,,,,)[]$fLabelable(,,,,,)[]$fLabelable(,,,,)[]$fLabelable(,,,)[]$fLabelable(,,)[]$fLabelable(,)[]$fLabelable()()$fLabelable()[]$fLabelableSignedSigned$fLabelableSigned[]$fLabelableBit[]$fLabelableQubit[]LTypeBit_Leaf Qubit_LeafQCLeafQCDataPlus_Simple QCData_Simple QCDataPlusQShapeBDataCDataQDataHTypeBTypeCTypeQType SimpleTypefs_shapeQCData qcdata_mapMQTypeBQCTypedummyqubitbitbool shapetype_q shapetype_c shapetype_bshape qdata_mapM qdata_zip qdata_promote qdata_unzip qdata_map qdata_foldqdata_fold_map qdata_foldMqdata_fold_mapMqdata_sequentializeqdata_unsequentializeqdata_makeshape qdata_mapM_opqdata_promote_c qcdata_unzip qcdata_map qcdata_foldqcdata_fold_map qcdata_foldMqcdata_fold_mapMqcdata_sequentializeqcdata_unsequentializeqcdata_makeshapeqcdata_mapM_opcanonical_shape$fShowQubit_Leaf$fShowBit_Leaf $fQCDataChar $fQCDataFloat$fQCDataDouble $fQCDataInt$fQCDataInteger$fQCDataSigned$fQCDataB_Endpoint $fQCData[]$fQCData(,,,,,,,,,)$fQCData(,,,,,,,,)$fQCData(,,,,,,,)$fQCData(,,,,,,)$fQCData(,,,,,)$fQCData(,,,,) $fQCData(,,,) $fQCData(,,) $fQCData(,) $fQCData() $fQCDataBit $fQCDataQubit$fSimpleType(,,,,,,,,,)$fSimpleType(,,,,,,,,)$fSimpleType(,,,,,,,)$fSimpleType(,,,,,,)$fSimpleType(,,,,,)$fSimpleType(,,,,)$fSimpleType(,,,)$fSimpleType(,,)$fSimpleType(,)$fSimpleType()$fSimpleTypeBit$fSimpleTypeQubit $fQCLeafBit $fQCLeafQubitQCurryqcurryquncurryqdiscardcinitctermcdiscardqc_init_with_shapeqc_term qc_discardprepare qc_measure qc_prepareglobal_phase_anchored map_hadamardmap_hadamard_atswap_atcontrolled_notcontrolled_not_atbool_controlled_notbool_controlled_not_at qmultinot qmultinot_at qc_copy_fun qc_uncopy_funqc_copy qc_uncopycgate_ifcirc_ifextended_named_gateextended_named_gate_at named_gate named_gate_atnamed_rotationnamed_rotation_at dynamic_liftmapUnary mapBinary mapBinary_cmap2Q qc_mapBinaryqubits_of_qdataqdata_of_qubitsendpoints_of_qcdataqcdata_of_endpointsqc_falseqc_bind qc_unbindencapsulate_generic encapsulate_generic_in_namespaceunencapsulate_genericencapsulate_dynamicunencapsulate_dynamicreverse_genericreverse_generic_curriedreverse_simplereverse_simple_curriedreverse_generic_endoreverse_generic_impreverse_endo_ifreverse_imp_iftransform_unary_shapetransform_unarytransform_unary_dynamic_shapetransform_unary_dynamictransform_generic_shapetransform_genericwith_ancilla_initwith_ancilla_listwith_computed_funprovide_subroutine_genericboxnbox box_loopMloopM_boxed_ifwith_classical_controlinline_subroutine $fNumBool$fQCurry->(,)res$fQCurryCirc()bQOrdq_less q_greaterq_leqq_geqq_maxq_minQEq q_is_equalq_is_not_equalq_ltq_gtq_leq_geFormatEPSPDFPSASCIIPreview GateCount CustomStyle AnnGatecount Gatecount AnnGatetypeAnnGatetypeSubroutineGatetypeGatetypeSubroutine ControlTypeXarity FormatStyle renderformatbackgroundcolorforegroundcolor linewidthcoffs dotradius oplusradiusxoffgatepad gateheight crossradius stringbasebarwidth barheightdwidthdheightmaxgatelabelwidth maxlabelwidthmaxnumberwidthgatefont commentfont commentcolor labelfont labelcolor numberfont numbercolorsubroutineshape WireTypeMap self_inversetrack_wiretypeascii_of_boxidascii_render_controlascii_render_controlsascii_render_nocontrolflagascii_render_gateascii_render_gatelistascii_render_wiretypeascii_render_typeasascii_render_arityascii_render_oarityascii_of_ocircuitascii_of_circuitascii_of_bcircuitascii_of_subroutinepromptgetBitrun_readwrite_asciiprint_dbcircuit_asciiwhiteblack defaultStylepdfepsps ps_escapestring_of_boxidassign_x_coordinates update_xarity render_line render_dot render_circle render_not render_swap render_bar render_dbar render_init render_term render_dtermrender_namedgaterender_gphasegaterender_circgaterender_blankgaterender_comment render_label render_number render_typeas render_xaritydshowrender_controlwirerender_controlwire_floatrender_controldotsrender_multi_gaterender_multi_named_ctrlrender_multi_genctrlrender_ordering render_gate render_gates ps_parametersps_subroutinespage_of_ocircuitrender_bcircuitrender_dbcircuitprint_bcircuit_formatprint_dbcircuit_formatpreview_documentpreview_document_custompreview_bcircuitpreview_dbcircuit controltype nocontrolsunannotate_gatetypeadd_controls_gatetypereverse_gatetypeset_ncf_gatetype with_aritygatetypestring_of_gatetypereverse_gatecountadd_controls_gatecountset_ncf_gatecountunannotate_gatecountcountanngatecount_of_circuitgatecount_of_circuitgatecount_of_subroutine_call$anngatecount_of_circuit_with_sub_cts aggregate_gatecounts_of_bcircuitgate_wires_changeaggregate_maxwires_of_bcircuit%maxwires_of_circuit_with_sub_maxwiresprint_gatecountprint_gatecounts_circuitprint_gatecounts_bcircuitprint_gatecounts_subroutineprint_gatecounts_dbcircuit format_enumprint_dbcircuitprint_of_documentprint_of_document_custom print_errmsg print_unary print_generic print_simple$fShowFormatStyle $fEqGatetype $fOrdGatetype$fShowGatetype$fEqAnnGatetype$fOrdAnnGatetype$fShowAnnGatetype $fShowFormatcgate_to_cnot_transformertranslate_cgateclassical_to_cnottrivial_endpoint classical_to_quantum_transformerclassical_to_quantum_unaryclassical_to_quantumCircLiftingUnpackunpackpack BoolParamPTruePFalsenewBooltemplate_PFalsetemplate_PTruedecToCircMonadtemplate_newBooltemplate_False template_True template_not'template_symb_ampersand_symb_ampersand_template_symb_vbar_symb_vbar_template_bool_xor template_iftemplate_symb_equal_symb_equal_$fCircLiftingUnpackCircCirc$fCircLiftingUnpackCircCirc0$fCircLiftingUnpackCircCirc1$fCircLiftingUnpackCircCirc2$fCircLiftingUnpackCircCirc3$fCircLiftingUnpackCircCirc4$fCircLiftingUnpackCircCirc5$fCircLiftingUnpackCircCirc6$fCircLiftingUnpackCircCirc7$fCircLiftingUnpackCirc-> $fEqBoolParam$fShowBoolParam KeepPhase Precisionbitsdigits apply_gate_atapply_gates_atapply_gates2_attwolevelgate_T_power_atapply_twolevel_atapply_twolevels_atapply_twolevel_alt_atapply_twolevels_alt_atexact_synthesis1exact_synthesisexact_synthesis_altapproximate_synthesis_zrotapproximate_synthesis_phaseapproximate_synthesis_eulerapproximate_synthesis_u2approximate_synthesis_zrot_ctrl approximate_synthesis_phase_ctrlPMonadmerge QuantumStateQState next_wire quantum_statetraces namespace trace_flag QuantumTraceProbabilityDistribution AmplitudesVectorGateRscalereverseRgateQgateQinvexpCpiCrotQrotQinvexpZtRgPhasegateC normalizeempty_quantum_stateclassical_controlclassical_controls qc_control qc_controls magnitudesplitmerge_with_result get_traceaddapplyvector if_controls performGateQsimulation_transformersimulation_dynamic_transformersimulate_transform_unaryqdata_concrete_shapeqdata_concrete_bindingsqdata_to_basisqdata_vector_to_amplitudesbasis_to_qdataamplitudes_to_qdata_vectorsimulate_amplitudes_unarysim_amps run_unaryrun_unary_trace run_unary_iorun_unary_trace_io sim_unary run_genericrun_generic_tracerun_generic_iorun_generic_trace_io sim_generic $fShowVector$fFunctorVector$fApplicativeVector $fMonadVector$fPMonadrVector$fPMonadrStateT $fPMonadrIOcontrolssimulate_cgatesimulate_classical run_classicalrun_classical_errmsgrun_classical_unaryrun_classical_generic ControlInfoNone Classical OneQuantum ManyQuantumstabilizer_transformer control_infotoCliffordCirc eval_unaryrun_clifford_unaryrun_clifford_genericBoolregBitregRegister.!qureg_of_qulist_tequlist_of_qureg_te qureg_length qureg_shapebitreg_of_bitlist_tebitlist_of_bitreg_te bitreg_lengthboolreg_of_boollist_teboollist_of_boolreg_teboolreg_lengthqinit_registerqterm_registerqmeasure_registerwith_ancilla_regwith_ancilla_reg_initboolreg_of_int_leint_of_boolreg_unsigned_le$fLabelableRegister[]$fQCDataRegister$fLabelableRegister[]0$fQCDataRegister0$fShowRegister toffoli_NC_attoffoli_AMMR_at toffoli_V_at toffoli_S_atcc_iX_atcc_iX_simple_at cc_iX_S_at ccZ_AMMR_atccZ_S_at fredkin_at cH_AMMR_atcontrolled_W_atgate_W_CliffordT_atcontrolled_iX_atcontrolled_S_atcontrolled_T_atcontrolled_V_atcontrolled_E_atcontrolled_YY_attoffoli_plain_atcc_iX_plain_atmulti_cnot_barenco_atmulti_ciX_noancilla_atpartition_controlswith_signed_qubitwith_combined_controlsLegacyGateBase GB_Toffoli GB_Binary GB_CliffordTwith_combined_controls_gbdecomposeQToffolidecomposeQToffoli_invdecomposeQMultinotdecompose_transformeropen_subroutinedecompose_subroutinedecompose_dynamic_transformerdecompose_legacy_unarydecompose_legacy_generic$fShowLegacyGateBasewith_combined_controls_iXwith_combined_controls_CTwith_normalized_controlswith_normalized_controls_HS negate_iftrimcontrols_transformerapprox_ct_transformerexact_ct_transformerstandard_transformerstrict_transformertrimcontrols_subroutinetrimcontrols_dtransformertrimcontrols_unaryapprox_ct_subroutineapprox_ct_dtransformerapprox_ct_unaryexact_ct_subroutineexact_ct_dtransformerexact_ct_unarystandard_subroutinestandard_dtransformerstandard_unarystrict_subroutinestrict_dtransformer strict_unarytrimcontrols_genericapprox_ct_genericexact_ct_genericstandard_genericstrict_genericGateBaseLogicalBinaryToffoli CliffordT_old CliffordTStandardStrict ApproximateExact TrimControls gatebase_enumdecompose_generic$fShowGateBaseQNumq_addq_multq_subq_absq_negateq_signum q_fromQDIntIntMCIntXIntxint_of_list_bhintm_of_integerlist_of_xint_bhxint_maybe_lengthinteger_of_intm_unsignedinteger_of_intm_signedlist_of_xint_lhxint_of_list_lh intm_lengthboollist_of_intm_bhintm_of_boollist_bhintmintm_extend_unsignedintm_extend_signedbitlist_of_cint_bhcint_of_bitlist_bhbitlist_of_cint_lhcint_of_bitlist_lh cint_lengthcint_extend_unsignedcint_extend_signedqulist_of_qdint_bhqdint_of_qulist_bhqulist_of_qdint_lhqdint_of_qulist_lh qdint_lengthqdint_extend_unsignedqdint_extend_signed qdint_shape cint_shape intm_promoteintm_with_lengthintm_interval_signedintm_interval_unsigned q_increment q_decrementq_add_in_placeq_sub_in_place q_add_param q_sub_paramq_add_param_in_placeq_sub_param_in_place q_mult_paramq_negate_in_place q_le_unsigned q_le_signed q_lt_signed q_negativeq_moddiv_unsigned_in_placeq_mod_unsignedq_divrem_unsignedq_div_unsignedq_divq_quotq_div_exact_unsigned q_div_exact q_ext_euclidtemplate_symb_plus_$fEqXInt$fLabelableXInt[] $fQCDataXInt $fQOrdXInt $fShowXInt$fIntegralXInt $fEnumXInt $fRealXInt $fOrdXInt $fNumXInt $fZeroXInt$fIntervalXInt $fShowXInt0 $fQNumXInt $fShowXInt1 getListWirequipperGateToMyGatequipperGateInitWquipperGateFreshWirequipperCircuitToMyCircquipperBCircuitToMyCirc myCircErrMsgquipperFunToMyCircmyGateToQuipperGate makeCommentquipperBCircuitSimplsimplify_classical'simplify_classicalclassical_to_reversible_optim!box_classical_to_reversible_optimwGate wGateInverse toffoliGatecontrolledExpGateOraclenmkentrance oraclefunqrwbwttimesteporacle parseNodeRoot parseNodeEven testIsParent testIsChild setParentsetChildsetChildInTreesetWelddoWeld1doWeld0cAddNum cAddNumClearcSubNum cSubNumClearoracle_orthodox main_circuit main_oraclesimulate_edges render_oraclesimulate_parseNodeRootsimulate_parseNodeEvensimulate_testIsParentsimulate_testIsChildsimulate_setParentsimulate_setChildsimulate_setChildInTreesimulate_setWeldsimulate_doWeld1simulate_doWeld0simulate_cAddNumsimulate_cSubNumhibitmain_allQNodeCNodeNodeconvert_oracle hamiltonian time_step basischange compute_stepsoracle_blackbox oracle_simple node_of_int int_of_nodenode_of_boollistboollist_of_nodeparent childintree bit_adderdoweld1doweld0weldchild level_parityis_zerois_root v_functionqnode_of_qulistcnode_of_bitlist cboollist_xorcparent cchildintree cbit_addercdoweld1cdoweld0cweldcchild clevel_paritycis_zerocis_root cv_functionoracle_classical main_edges1circfun main_edges2 main_oraclec main_oracle2 main_oracle3 main_qrwbwttemplate_boollist_xortemplate_bit_addertemplate_parenttemplate_childintreetemplate_doweld1template_doweld0 template_weldtemplate_childtemplate_level_paritytemplate_is_zerotemplate_is_rootColortemplate_v_functioncolorToBoolParamclassical_BWT_oraclereversible_BWT_oraclereversible_BWT_oracle_optimoracle_templateoracle_template_optimOptionswhatformatgatebasecdt OracleSelectOrthodoxSimpleBlackboxTemplate TemplateOptim WhatToShowGraphOracleCSimulatedefaultOptionsoptions oracle_enumdoptsusageoracle_of_options$fShowWhatToShow$fShowOracleSelect $fShowOptionsghc-prim GHC.TypesBoolcontainers-0.6.0.1Data.IntMap.InternalIntMapData.IntSet.InternalIntSetinsertData.Map.InternalMapintmap_ziprightbase GHC.MaybeNothingxintmap_touchedxintmap_reservexintmap_unreserveData.TraversablesequenceGHC.ListzipzipWithGHC.Realceiling integer-gmpGHC.Integer.TypeIntegerTrueGHC.BaseidFalse GHC.ClassesOrd Data.EitherEitherDouble RandomGenlastzip3 Data.Foldablefoldlreverse$GHC.ErrerrorString Data.Tuplesndreturn>>= list_stepsafe_zipState NoCommentFlag empty_state initial_state get_state set_stateput_gate apply_gatedo_readrun_circ get_arityarity set_arity get_clistclist set_clist get_ncflagncflag set_ncflagget_nocommentflag nocommentflagset_nocommentflagwiretype_of_endpointrepeat&identity_dynamic_transformer_with_lift%identity_dynamic_transformer_constantGHC.Showshow undefinedShow circuit_type_structure_of_qcdataqc_allocreverse_errmsg reverse_unarytransform_errmsg box_internalEqIO)easyrender-0.1.1.4-LGKgMKvsO8OHhnh1fDMW56Graphics.EasyRender.InternalDocumentCustom&&||not=='newsynth-0.4.0.0-DUJYtOD4us1132TcZsHlLUQuantum.Synthesis.CliffordT%Quantum.Synthesis.MultiQubitSynthesisTwoLevel TwoLevelAltToGatesQuantum.Synthesis.MatrixU2Quantum.Synthesis.RingDOmegaSO3DRootTwoToQOmegaQuantum.Synthesis.SymRealSymRealCplxandMonadregister_of_list_telist_of_register_teregister_lengthGHC.NumNumsignum xint_casexint_set_length XInt_indetxint_is_determinate xint_equals xint_lengthxint_extend_unsignedxint_extend_signedintm_set_lengthcombine_lengthintegers_of_intms_signedintegers_of_intms_unsigned intm_binop intm_unop common_value common_lengthq_increment_qulist q_add_qdint q_add_qulist q_sub_qdint q_sub_qulistq_add_in_place_qulistq_sub_in_place_qulistq_add_param_qulistq_add_param_in_place_qulistq_mult_param_qulistq_negate_in_place_qulistq_negate_qdintGHC.EnumminBoundInt q_abs_qdintabs q_abs_qulistq_signum_qdintq_signum_qulistq_le_unsigned_qulistq_le_unsigned_auxq_le_signed_qulist q_mult_qdint q_mult_qulist!q_moddiv_unsigned_in_place_qulistq_div_unsigned_qulist q_div_qulist q_quot_qulist+MaybeSystem.Console.GetOptgetOptGHC.IO.Handle.FDstdout