L      !"#$%&'()*+,-./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 NoneL1Type for the monad encapsulating error messages. M Shortcut for 'Either String a'. N$Set an error message, to be thrown.  Usage: / errorMsg "an error happened" OMake a P" computation error-message aware. QAThrow the error that has been created, using the given string as  a prefix. Usage: $ extractQ "name of function: " $ do ' <<commands that may thow an error>> LRMNOQSTULRMNOQLRMNOQSTUNone V The monad. W Shortcut to StateT LiftState ErrMsgQ. XState of the monad. Y#How many times each name is bound. ZThe template prefix . [The name of the monad. \An empty state. ]#Retrieve the state from the monad. ^Set the state of the monad. _From L to V. `From P to V. aGet P out of V bSet an error message. c1Increase the number of binds of a variable name. d1Decrease the number of binds of a variable name. e6Run a computation with a particular name being bound. f?Run a computation with a particular list of names being bound. g#Say whether a given name is bound. hSet the template prefix. iGet the template prefix. jSet the monad name. kGet the monad name. lMake a name out of a string. m,Make a name out of a string, monadic-style. n.Make any string into a string containing only  [0-9a-zA-Z_.]. , For example, it replaces any occurrence of "+" with  " symb_plus_". oBTake a string and make it into a valid Haskell name starting with  " template_". pLook for the corresponding template name. q-Make a the template version of a given name. r3Print on the terminal a monadic, printable object. s"Project patterns out of a clause. t:Check that the list is a non-empty repetition of the same  element. uBReturns the length of the patterns in a list of clauses. Throw an 6 error if the patterns do not have all the same size. %VvWXwYZ[\]^_`abcdefghijklmnopqrstuxyz"VvWXwYZ[\]^_`abcdefghijklmnopqrstu VvWXwYZ[\]^_`abcdefghijklmnopqrstuxyz Safe-Inferred{A data type for handlers. |&An operating system specific handler. }Like ~), but only handle the first such signal. ~?Handle the signal in a new thread when the signal is received. Ignore the signal. Default action. 9A data type for signals. This can be extended as needed. .TERM signal (POSIX) or Close event (Windows). Control-C event. ;Install a handler for the given signal. The old handler is  returned. >Run a block of code with a given signal handler. The previous 0 handler is restored when the block terminates. Map an abstract  to a POSIX specific . Map a { to a POSIX specific handler. POSIX implementation of . {|}~ {}~{~}|None Safe-Inferred?A container type to hold a source of randomness. This can hold  any instance of the  class. NoneC Datatype to encode the notation x <- expr.  Expression hardcoded constant for . hardcoded constant for . List: [...]. Case distinction Let-construct. If-then-else. Tuple. Lambda abstraction.  Application.  Literal. Constant name. Variable name. First-level declaration. Match term construct.  Patterns. Cons: h:t. List as [...].  Wildchar. Tuple. Variable name.  Literal.  Literals. Reals.  Integers.  Characters.  There are no "guarded bodies" . One net effect is to make the  "where"" construct equivalent to a simple "let".  A simple do: list of monadic let followed by a computation. ,Get the set of variable names in a pattern. Substitution in a . Substitution in a . Substitution in an . -Substitution of several variables in one go. Downgrading TH literals to . Downgrading TH literals to . &Take a list of patterns coming from a where section and output & a list of fresh names for normalized lets. Also gives a mapping B for substituting inside the expressions. Assume all names in the  list of patterns are distinct. Build a let-expression out of pieces. Build a  out of a TH clause @From 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 . 1Abstract syntax tree of the type of the function . Upgrade literals Upgrade patterns. Upgrade match-constructs. Upgrade declarations. Upgrade expressions. 9Variable referring to the lifting function for integers. 6Variable referring to the lifting function for reals. Lifting literals. Lifting patterns. Lifting match-constructs. Lifting declarations. "Lifting first-level declarations. Lifting expressions. Amake 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. ?Lift a list of declarations. The first argument is the name of  the monad to lift into. @Lift an expression. The first argument is the name of the monad  to lift into. FF. None Safe-InferredWIn almost all instances, the standard form can also be deduced from the tupled form; , the only exception is the unary case. The ! class includes no new methods, ) adding just this functional dependency. While the methods of ! are always copied from those of , J 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,()))))* ( 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,())))).  Safe-Inferred Types in the  class have an "origin", i.e., an element B that can conveniently serve as the starting point for intervals. =Inputs 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,max() and returns a list of all values with  lower bound min and upper bound max.  min max: 0 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. samples every n0th element from the list, starting with element k same as ", but throw an error if length don't match Lists  7-Tuples  6-Tuples  5-Tuples  4-Tuples Triples Pairs  0-tuples ,      !*       Safe-Inferred["The "7 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 % fun = 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  qcdata_zip and  qcdata_promote/, throws an error because of a failure of some  low-level condition, such as "list too short". To produce error E messages that are meaningful to user-level code, these functions do A not have a hard-coded error message. Instead, they input a stub  error message. GA meaningful error message typically consists of at least three parts: C the name of the user-level function where the error occurred, for  example: "reverse_generic"; C what the function was doing when the error occurred, for example:  "-operation not permitted in reversible circuit"; 9 a 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". DThe 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 D operations (e.g., transforming, reversing). The mid-level function C knows what operation was being performed when the error occurred, E 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:  "7qterm: 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 D example, a function that implements integers as bit lists may wish C to report a problem with integers, rather than a problem with the  underlying lists. % The type % a b" consists of isomorphisms between  a and b, i.e. pairs (f,g ) such that g.f == id :: a -> a,  f.g == id :: b -> b. As with e.g. Haskell s && class, it is not possible in general B to guarantee that the intended laws hold; it is the programmer s  responsibility to ensure this. Under the hood, % and  are in fact the same; ' they differ just in the API exposed.  The type  a b witnesses the fact that a and b B are the same type. In other words, this type is non-empty if and  only if a = b.. This property is not guaranteed by the type 9 system, but by the API, via the fact that the operators   relexivity, , and  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. CIdentity types are useful in certain situations. For example, they E can be used to define a data type which is polymorphic in some type  variable x3, and which has certain constructors that are only  available when x+ is a particular type. For example, in the  declaration  I data ExampleType x = Constructor1 x | Constructor2 x (Identity x Bool),  Constructor1 is available for all x, but  Constructor2 is only  available when x = '. (The identity monad. Using m = ( gives useful special cases  of monadic functions. ):A string buffer holds a string that is optimized for fast 1 concatenation. Note that this is an instance of * , and hence  * operations (in particular +) can be applied to string A buffers. The following functions are synonyms of the respective  *. functions, and are provided for convenience. *6The 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 ., except that it supports C some additional efficient operations: to find the smallest unused @ key, to find the set of all keys ever used in the past, and to E reserve a set of keys so that they will not be allocated. Moreover, C it keeps track of the highest key ever used (whether or not it is ! still used in the current map). /4Apply a function to a specified position in a list. 08Overwrite an element at a specified position in a list. 1%Check whether a list has duplicates. 22 string character replacement: ! Replace the first occurrence of  character in string by  replacement. 3$Insert the elements of a list in an 4 (cf. 5). 6%Insert the given key-value pair in a 7, but only if the given A key is not already present. If the key is present, keep the old  value. 8 Take two .s m[sub 1] and m[sub 2], and form a new  . 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 .'s with the same domain, and form a new . = whose values are pairs. It is an error if the two inputs don't have  identical domains. Like 4, but also takes an error message to use in case of  domain mismatch. %Map a function over all values in an .. Monadic version of !. Map a function over all values  in an .. 9Delete 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 > if  not found. ?&Check whether the given key is in the -. @ The empty -. A!Return the first free key in the -, but without actually  using it yet. BReturn the next k unused keys in the -, but without  actually using them yet. C Convert a - to an .. D*Return the smallest key never used in the -. E,Return the set of all keys ever used in the -. F A wire is dirty' if it is touched but currently free. GReserve a key in the -. If the key is not free, do C nothing. The key must have been used before; for example, this is  the case if it was returned by F. HReserve a set of keys in the -. For any keys that are not E free, do nothing. All keys must have been used before; for example, + this is the case if they were returned by F. IUnreserve a key in the - . If the key is currently used, E do nothing. The key must have been reserved before, and (therefore)  must have been used before. J Unreserve a list of keys in the -. If any key is > currently used, do nothing. All keys must have been reserved 5 before, and (therefore) must have been used before. KMake an exact copy of the -, except that the set of C touched wires is initially set to the set of used wires. In other : words, we mark all free and reserved wires as untouched. Like  5, 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 f will 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  . LA right-to-left version of M: Evaluate each action in the 7 sequence from right to left, and collect the results. NSame as L, but ignore the result. OA "strict" version of !, i.e., raises an error when the # lists are not of the same length. PLike O., but also takes an explicit error message to  use in case of failure. QA " right strict" version of !, i.e., raises an error when the + left list is shorter than the right one. R A version of Q# that also takes an explicit error $ message to use in case of failure. SA "strict" version of T!, i.e., raises an error when the # lists are not of the same length. UA " right strict" version of T!, i.e., raises an error when the * right list is shorter than the left one. VA right-to-left version of zipWithM, 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. WSame as  zipRightWithM, but ignore the result. XGFold over two lists with state, and do it right-to-left. For example,  ) foldRightPairM (w0, [1,2,3], [a,b,c]) f will do the following:  do  w1 <- f (w0, 3, c)  w2 <- f (w1, 2, b)  w3 <- f (w2, 1, a)  return w3 YLike X, but ignore the final result. Z4Combine 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') [Monadic version of Z. A "for" loop. Counts from a to b in increments of s. Standard notation:   for i = a to b by s do  commands  end for Our notation:  for a b s $ \i -> do  commands  endfor Mark the end of a "for""-loop. This command actually does : nothing, but can be used to make the loop look prettier. =Iterate a parameter over a list of values. It can be used as  follows:   foreach [1,2,3,4] $ \n -> do 0 <<<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 ^. `Take two functions f : a !b and g : c !d , and return  f g : a c !c d. aMonadic version of mappair. bA version of the c function that returns an d. e>Convert 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. f>Convert 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. gBConvert a bit vector to an integer. The conversion is big-headian E (or equivalently, little-tailian), i.e., the head of the list holds  the integer'5s most significant digit. This function is unsigned, $ i.e., the integer returned is "e 0. h,Convert a bit vector to an integer, signed. i$Exclusive or operation on booleans. j'Exclusive or operation on bit vectors. k,A general list-to-string function. Example: = string_of_list "{" ", " "}" "{}" show [1,2,3] = "{1, 2, 3}" ll b s: if b = m , return s, else the empty + string. This function is for convenience. nConvert a List to a *. o Convert a * to a List. +Fast concatenation of *s or string buffers. p The empty *. qConcatenate a list of Blists. r%Convert a string to a string buffer. s%Convert a string buffer to a string. tThe empty string buffer. u&Concatenate a list of string buffers. Witness the fact that a=a. Witness the fact that a=b implies b=a. Witness the fact that a=b and b=c implies a=c. The identity function v : a !b, provided that a and b  are the same type. w#Map forwards along an isomorphism. x$Map backwards along an isomorphism. j"#$%yz({|)*}~,-/0123689:;<=?@ABCDEFGHIJK LNOPQRSUVWXYZ[ \]^_`abefghijklno+pqrstuwxV"#$({|)*,-/012369:;<=?@ABCDFHJK LNOPQRSUVWXYZ[ \]^_`abefghijklno+pqrstua"#$%yz({|)*}~,-/0123689:;<=?@ABCDEFGHIJK LNOPQRSUVWXYZ[ \]^_`abefghijklno+pqrstuwx Safe-Inferred Lifted version of '(:)' :: a -> [a] -> [a]. Lifted version of '[]' :: [a]. Lifted version of  :: [a] -> [a]. Lifted version of  :: [a] -> [a]. Lifted version of '(++)' :: [a] -> [a] -> [a]. Lifted version of . lifted version of  lifted version of  lifted version of T Lifted version of Z !Lifted version of the combinator . Lifted version of  :: String -> a. Using it will make the 5 circuit generation fail with the error described in . Lifted version of  :: (a,b) -> b    Safe-InferredAExit with an error message after a command line error. This also 9 outputs information on where to find command line help. (Parse a string to an integer, or return > on failure. 0Parse a string to a list of integers, or return > on failure. Parse a string to a  , or return > on failure. AIn an association list, find the key that best matches the given > string. If one key matches exactly, return the corresponding A key-value pair. Otherwise, return a list of all key-value pairs D whose key have the given string as a prefix. This list could be of D 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.  Safe-InferredP -The type of dynamic boxed circuits. The type   a is $ the appropriate generalization of (', a), in a setting C that is dynamic rather than static (i.e., with dynamic lifting or  "interactive measurement"). !The !4 monad describes a standard read-write computation, / here specialized to the case where writes are 1s, prompts are  Bits, and reads are '&s. Thus, a read-write computation can  do three things: + terminate with a result. This is the case %.  write a single 1 and continue. This is the case $.  issue a prompt, which is a W, then read a ', then  continue. This is the case #. &An ordered boxed circuit is a ' together with an A ordering on the input and output endpoints, or equivalently, an  - together with a namespace. 'oA 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 B responsibility to ensure there is no circular dependency, and no  clash of names. ) A typed subroutine consists of: O a low-level circuit, ordered to allow binding of incoming and outgoing wires;  functions for structuring/-destructuring the inputs and outputs to and J from lists of wires (these functions being dynamically typed, since the  input/+output type may vary between subroutines);  a I1, recording whether the circuit is controllable. +COne often wants to consider the inputs and outputs of a circuit as  more structuredtyped than just lists of bitsqubits; for instance, F a list of six qubits could be structured as a pair of triples, or a  triple of pairs, or a six-bit QDInt. DWhile for the most part this typing information is not included in F low-level circuits, we need to consider it in hierarchical circuits, F so that the information stored in a subroutine is sufficient to call $ the subroutine in a typed context. DSpecifically, the extra information needed consists of functions to  destructure the input/+output data as a list of typed wires, and J restructure such a list of wires into a piece of data of the appropriate  type. -An ordered circuit is a / together with an ordering on A (usually all, but potentially a subset of) the input and output  endpoints. CThis extra information is required when a circuit is used within a  larger circuit (e.g. via a 3 gate), to identify which wires G 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, B the total number of wires used by the circuit. Because wires are 5 allocated consecutively, this means that the wire id' s used are  [0..n-1]. 0Recall that an S, is a set of typed wires, and it determines < the external interfaces at which circuits and gates can be  connected. The type 0$ stores the same information as the  type S7, but in a format that is more optimized for efficient D updating. Additionally, it also stores the set of wires ever used. 1'The low-level representation of gates. 29A comment. Does nothing, but can be useful for marking a & location or some wires in a circuit. 3:Reference 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. 4Termination of a U& wire, with a comment indicating what A the observed state of that wire was. This is typically inserted ; in a circuit after a dynamic lifting is performed. Unlike  89, this is in no way an assertion, but simply a record of = observed behavior during a particular run of the algorithm. 5Termination of a U wire without  assertion: U -> 1 6Termination of a V wire without  assertion: V -> 1 7 Measurement: V -> U. 8Termination of a U wire with assertion ) that the bit is in the specified state:  U * ' -> 1. 9Termination of a V wire with assertion + that the qubit is in the specified state:  V * ' -> 1. :Initialization: ' -> U. ;Initialization: ' -> V. < Measurement V -> U 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: U -> V. >Classical swap gate: U * U -> U * U. ?Uncompute classical gate U -> 1, asserting that the > classical bit is in the state specified by the corresponding  @. @Generic classical gate 1 -> U. AClassical not: U -> U. BGlobal phase gate: '1' -> '1'<. The list of wires is just a hint for graphical rendering. C<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 D. D!A named reversible quantum gate: V ^(m+n) ->  V^(m+n). The second [W] argument should be  "generalized controls"!, i.e. wires not modified by the > gate. The gate type is uniquely determined by: the name, the A number of inputs, and the number of generalized controls. Gates < that differ in one of these respects should be regarded as  different gates. E=A flag that indicates how many times a particular subroutine A should be repeated. If non-zero, it implies some constraints on  the type of the subroutine. G@An identifier for a subroutine. A boxed subroutine is currently C identified by a pair of: the user-defined name of the subroutine; F and a value uniquely identifying the type and shape of the argument. CFor now, we represent the shape as a string, because this gives an  easy total  instance, needed for Data.Map. However, in E principle, one could also use a pair of a type representation and a : shape term. The implementation of this may change later. IFA flag, to specify if the corresponding subroutine can be controlled. @ Either no control allowed, or all controls, or only classical. MA flag that, if m+, indicates that the gate is controllable, A but any further controls on the gate should be ignored. This is = used, e.g., for circuits consisting of a basis change, some B operation, and the inverse basis change. When controlling such a C circuit, it is sufficient to control the middle operation, so the C gates belonging to the basis change and its inverse will have the  NoControlFlag set. NA flag that, if m', indicates that the gate is inverted. O7A time step is a small floating point number used as a ; parameter to certain gates, such as rotation gates or the  [exp "iZt] gate. P,A list of controlled wires, possibly empty. QA signed item of type a. Q x m represents a  positive item, and Q x  represents a negative item. >When used with wires in a circuit, a positive sign is used to B represent a positive control, i.e., a filled dot, and a negative C sign is used to represent a negative control, i.e., an empty dot. SAAn arity, also known as a typing context, is a map from a finite  set of wires to wire types. T2Wire type. A wire is either quantum or classical. UClassical wire. VQuantum wire. W?Wire identifier. Wires are currently identified by an integer, > but the users of this interface should be oblivious to this. X.Extract the underlying item of a signed item. Y#Extract the sign of a signed item: m is positive, and   is negative. Z8Compute the incoming and outgoing wires of a given gate ? (excluding controls, comments, and anchors). This essentially D encodes the type information of the basic gates. If a wire is used , multiple times as an input or output, then Z also A returns it multiple times; this enables run-time type checking.  Note that Z returns the logical wires, and therefore D excludes things like labels, comments, and graphical anchors. This  is in contrast to `, which returns the  syntactic  set of wires used by the gate. [@Return the controls of a gate (or an empty list if the gate has  no controls). \ Return the M of a gate, or  if it doesn' t have one. ]Apply the given M to the given 1. This means,  if the first parameter is m, set the gate's M, ? otherwise do nothing. Throw an error if attempting to set the  M on a gate that can't support this flag. ^>Reverse a gate. Throw an error if the gate is not reversible. _4Return the set of wires used by a list of controls. `<Return the set of wires used by a gate (including controls,  labels, and anchors). Unlike Z, the function ` is used for B printing, and therefore returns all wires that are syntactically ? used by the gate, irrespective of whether they have a logical  meaning. aLike `!, except return a list of wires. b?Check whether the given gate is well-formed and can be legally B applied in the context of the given arity. If successful, return ; the updated arity resulting from the gate application. If 7 unsuccessful, raise an error. Properties checked are: @ that each gate has non-overlapping inputs, including controls; A that each gate has non-overlapping outputs, including controls; ? that the inputs of the gate (including controls) are actually  present in the current arity; B that the types of the inputs (excluding controls) match those of  the current arity; 6 that the outputs of the gate (excluding controls) don' t conflict 7 with any wires already existing in the current arity. cLike d%, but without type checking. This is D potentially faster, but should only used in applications that have 1 already been thoroughly tested or type-checked. d@For now, we disable run-time type checking, because we have not ? yet implemented run-time types properly. Therefore, we define  d to be a synonym for c. eReturn an empty arity. f+Return a wire unused in the current arity. gReturn the next k$ wires unused in the current arity. h>Add a new typed wire to the current arity. This returns a new  wire and the updated arity. i0Convert an extended arity to an ordinary arity. j9Return the smallest wire id nowhere used in the circuit. k.Return the set of all the wires in a circuit. lReverse a gate list. mDReverse a circuit. Throw an error if the circuit is not reversible. nSet the M on all gates of a circuit. o Reverse an -3. Throw an error if the circuit is not reversible. p The trivial + on ([W],S). qUse a +% to destructure a piece of (suitably ) typed) data into a list of typed wires. rUse a +% to structure a list of typed wires  (of the appropriate length/(arity) into a piece of structured data. sExtract just the / from a ). tThe empty namespace. u<A function to display the names of all the subroutines in a (. v Construct an & from a ' and an ordering on the  input and output endpoints. wEReverse a simple boxed circuit, or throw an error if not reversible. xGTransforms a read-write computation into one that behaves identically, / but also returns the list of gates generated. DThis is used as a building block, for example to allow a read-write C computation to be run in a simulator while simultaneously using a 6 static backend to print the list of generated gates. y!Extract the contents of a static ! computation. A  !4 computation is said to be static if it contains no  #: instructions, or in other words, no dynamic lifting. If  an #4 instruction is encountered, issue an error message  using the given stub. zATurn 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, x5). The list of gates is generated lazily, and can be 2 consumed one gate at a time. However, the values ns and x are A only computed at the end of the computation. Any function using 1 them should not apply a strict pattern match to ns or x, or ? else the whole list of gates will be generated in memory. For 1 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 C dynamic boxed circuit may not contain any dynamic liftings, since C these cannot be performed in a static setting. In case any output C liftings are encountered, try to issue a meaningful error via the  given stub error message. |@Convert a boxed circuit to a dynamic boxed circuit. The latter,  of course, contains no # instructions. a !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|] !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|]WTVUSQRXYPONMILKJGHEF1DCBA@?>=<;:98765432Z[\]^_`a0bcdefghij/klmn-.o+,pqr)*s(tu'&vw!%$#"xyz {|? !%$#"&'()*+,-./01DCBA@?>=<;:98765432EFGHILKJMNOPQRSTVUWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{| Safe-Inferred}LTo transform Dynamic Boxed circuits, we require a Transformer to define the M behavior on static gates, but we also require functions for what to do when P a subroutine is defined, and for when a dynamic_lift operation occurs. This is 2 all wrapped in the DynamicTransformer data type. A "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 D introduce an abbreviation for this type primarily as a convenience  for the definition of !, but also because this type can & be completely hidden from user code. BA circuit transformer is specified by defining a function of type   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 N my_transformer (T_Gate1 <parameters> f) = f $ <semantic function for gate 1> N my_transformer (T_Gate2 <parameters> f) = f $ <semantic function for gate 2> N my_transformer (T_Gate3 <parameters> f) = f $ <semantic function for gate 3>  ...  The type 0 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 f( is a higher-order function to pass the  translation of X to. <A list of signed values of type 'Endpoint'. This type is an ' abbreviation defined for convenience. @A binding is a map from a set of wires to the disjoint union of  a and b. An endpoint is either a qubit or a bit. In a transformer, : we have 'Endpoint Qubit Bit' = 'Qubit' + 'Bit'. The type Endpoint  a b is the same as  a b, but we use more suggestive  field names. /Return the list of bound wires from a binding. The empty binding. :Bind a wire to a value, and add it to the given bindings. @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. 7Retrieve the value of a wire from the given bindings. <Retrieve the value of a qubit wire from the given bindings. ; Throws an error if the wire was bound to a classical bit. :Retrieve the value of a bit wire from the given bindings. 3 Throws an error if the wire was bound to a qubit. 'Delete a wire from the given bindings. Like 7, except bind a list of wires to a list of values. The # lists must be of the same length. Like 1, except bind a list of qubit wires to a list of / values. The lists must be of the same length. Like /, except bind a list of bit wires to a list of / values. The lists must be of the same length. Like $, except retrieve a list of values. Like $, except retrieve a list of values. Like $, except retrieve a list of values. >Given a list of signed wires (controls), and a list of signed I values, make a bindings from the wires to the values. Ignore the signs. Like 2, but retrieve binding for all wires in a list of  controls. Turn a 1 into a %. 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 B gate, of turning a semantic function into a binding transformer. @ Additionally, this function is passed a Namespace, so that the 0 semantic function for T_Subroutine can use it. Apply a  '-' 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 1 would like to leave the boxed structure intact.  For " simulation", types of applications, one would generally & recurse through the boxed structure. AThe difference is specified in the definition of the transformer A 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"C 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 % function of the DynamicTransformer. 7}~6}~6}~}~ Safe-Inferred A "control source". is anything that can be used as a control on A a gate. The most common way to construct a control source is by  using the .==., ./=., and .&&. operators. In addition, % we provide the following instances:  ':. A boolean condition that is known at circuit generation B time can be used as a control, which is then either trivial (the A gate is generated) or inconsistent (the gate is not generated).  W. This includes the type Bit (for a classical  execution-time control) and Qubit! (for a quantum control). A wire D can be used as a shorthand notation for a positive control on that  wire.  . A control list is Quipper' s internal C 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 A of conjunctive controls, i.e., controls that can be constructed  using the .==., ./=., and .&&. operators. =The empty control list, corresponding to a condition that is  always true. /Add a single signed control to a control list. combine list1 list2: C 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 P from  the Quipper.Circuit module. Like ", but also return a value of type  P, or ># if the controls are inconsistent. # This function is for convenience. AModify the given gate by applying the specified controls. If the E total set of controls (i.e., those specified in the gate itself and > those specified in the control list) is inconsistent, return  >;. If it is consistent, return the appropriately controlled C version of the gate. Throw an error if the gate is of a kind that  cannot be controlled. The " catch all" clause for . This handles all D gates that are not controllable. If the control condition is known " at circuit generation time to be , 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 controlled  Safe-Inferred)Synonym for a bit list, for convenience. +Synonym for a qubit list, for convenience. A control consists of an  and a boolean (m = & perform gate when control wire is 1;  = perform gate when E 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 . >The type of run-time classical bits (i.e., boolean wires in a  circuit). The type of qubits. The 8 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) @Holds the state during circuit construction. Currently this has B four components: the output arity of the circuit currently being  assembled, the current (, the currently active   and M", and a flag to determine whether B comments are disabled. All gates that are appended will have the  controls from the  added to them. 2A flag to indicate whether comments are disabled (m) or  enabled (). =Return a completely empty state, suitable to be the starting ! state for circuit construction. 8Prepare an initial state from the given extended arity. Get the  monad' s state. Set the  monad' s state. Pass 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 . $Issue a prompt and receive a reply.  Issue a RW_Subroutine primitive This is the universal "run" function for the  monad. It  takes as parameters a ' computation, and an initial state. It  outputs !# computation for the result of the  " computation and the final 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. 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. ?Run a monadic term in the initial arity, and extract a dynamic  boxed circuit. 2Extract the underlying low-level wire of a qubit. 0Extract 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 W of an . !Extract the underlying low-level T of an . Break a list of s down into a list of Ws together with an S.  (Partial inverse to .)  Create an  from a low-level W and T. Create a list of s from a list of Ws together with an S, . 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. <Retrieve the value of a qubit wire from the given bindings. ; Throws an error if the wire was bound to a classical bit. BRetrieve the value of a bit wire from the given bindings. Throws , an error if the wire was bound to a qubit. :Add a single signed qubit as a control to a control list. 8Add a single signed bit as a control to a control list. provideSimpleSubroutine; 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. provideSubroutines namespace:  Add each subroutine from the  namespace to the current circuit, 2 unless a subroutine of that name already exists. provideSubroutine name circ:  if name4 not already bound, binds it to the main circuit of circ, 6 and additionally provides any missing subroutines of circ. AApply the specified low-level gate to the current circuit, using A the current controls, and updating the monad state accordingly. A This includes run-time well-formedness checks. This is a helper 7 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. BApply a multiple-not gate, as specified by a list of booleans and  qubits: 0qmultinot_list [(True,q1), (False,q2), (True,q3)] applies  a not gate to q1 and q3 , but not to q2. Like +, 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 { =X . It is a ? convenient gate for calculations. For example, every Clifford . operator can be uniquely written of the form  E[sup a]X[sup b]S[sup c][sup d], where a, b, c, and d" 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 = "X0 gate. This is by definition the following gate ' (see also Nielsen and Chuang, p.182): [ image V.png] Apply the inverse of a V-gate. Apply a SWAP gate. Apply a classical SWAP gate. Apply an [exp "iZt] gate. The timestep t is a parameter. Apply a rotation by angle 2i/2[sup n] about the z-axis. [image rGate.png] Apply a W gate. The W' gate is self-inverse and diagonalizes  the SWAP gate. [ image W.png] The arguments are such that   gate_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.  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]  Apply a "iX gate. This is the inverse of . !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. Like , except the gate is also "anchored" at a 9 particular bit or qubit. This is strictly for graphical D presentation purposes, to provide a hint for where the gate should C be printed in a circuit diagram. Backends are free to ignore this C 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 B given list of generalized controls. The generalized controls are B 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 C depends on a real parameter. This is typically used for rotations @ or phase gates parameterized by an angle. The name can contain  '%'2 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_list. gate, as specified by a list of booleans and  qubits: 0qmultinot_list [(True,q1), (False,q2), (True,q3)] applies  a not gate to q1 and q3 , but not to q2. Like +, 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 { =X . It is a ? convenient gate for calculations. For example, every Clifford . operator can be uniquely written of the form  E[sup a]X[sup b]S[sup c][sup d], where a, b, c, and d" 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 = "X0 gate. This is by definition the following gate ' (see also Nielsen and Chuang, p.182): [ image V.png]  Apply the inverse of a V-gate.  Apply a SWAP gate.  Apply a classical SWAP gate. Apply an [exp "iZt] gate. The timestep t is a parameter. Apply a rotation by angle 2i/2[sup n] about the z-axis. [image rGate.png] Apply a W gate. The W' gate is self-inverse and diagonalizes  the SWAP gate. [ image W.png] The arguments are such that   gate_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.  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]  Apply a "iX gate. This is the inverse of . =Apply a generic quantum gate to a given list of qubits and a B given list of generalized controls. The generalized controls are B 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 C depends on a real parameter. This is typically used for rotations @ or phase gates parameterized by an angle. The name can contain  '%'2 as a place holder for the parameter, for example " exp(-i%Z)". %Apply a NOT gate to a classical bit. 3Generate a new qubit, initialized to the parameter '. *Terminate a qubit asserted to be in state b. DWe note that the assertion is relative to the precision: when gates C in a circuit are implemented up to some precision  (either due toD physical limitations, or due to decomposition into a discrete gate D base), the assertion may only hold up to a corresponding precision  as well. Discard a qubit destructively. BGenerate a new qubit, initialized from a classical bit. Note that 2 the classical bit is simultaneously terminated. :Unprepare a qubit asserted to be in a computational basis D state. This is the same as a measurement, but must only be applied D to qubits that are already known to be in one of the states |0#* or B |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  . 5Apply a measurement gate (turns a qubit into a bit). AGenerate a new classical bit, initialized to a boolean parameter  b. Terminate a classical  asserted to be in state '. Terminate a classical $ with a comment indicating what the  observed state of the ( was, in this particular dynamic run of E the circuit. This is typically used to terminate a wire right after C a dynamic lifting has been performed. It is not intended to be a  user-level operation. It is important to note that a 4 gate does not, in any way, " represent an assertion. Unlike a 8 gate, which asserts that 1 the classical bit will have the stated value at every run of the  circuit, the 40 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 4 gate can be @ interpreted in multiple ways. In the simplest case, it is just  treated like a 5 gate, and the boolean comment E ignored. Alternatively, it can be treated as a post-selection gate: A if the actual value does not equal the stated value, the entire # computation is aborted. Normally, 4 gates should appear in  the output , not the input' of simulators; therefore, the details 2 of the behavior of any particular simulator on a 4 gate are  implementation dependent. 'Discard a classical bit destructively.   Return the " exclusive or" of a list of bits. !&Test equality of two bits, and return m iff they are equal. "If a is m, then return b, else return c. #3Return the negation of its input. Note that unlike  or  :, this gate does not alter its input, but returns a newly  created bit. $*Return the conjunction of a list of bits. %*Return the disjunction of a list of bits. &@Apply a named classical gate. This is used to define all of the C above classical gates, but should not usually be directly used by  user code. '' name w inputs: Uncompute a named classical  gate. This asserts that w( is in the state determined by the gate  type and the inputs, then uncomputes w in a reversible 7 way. This rarely used gate is formally the inverse of &. (7Insert a subroutine gate with specified name, and input/output D output types, and attach it to the given endpoints. Return the new  endpoints. Note that the [W] and S arguments are used as a pattern  for the locations/&types of wires of the subroutine; the [] H argument (and output) specify what is attached in the current circuit. = The two aspects of this pattern that are respected are: the A lingeringness of any inputs; and the number and types of wires. EFor 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. ENote that lingering wires may change type, for e.g. subroutines that  include measurements. FIt is currently assumed that all these lists are linear, i.e. contain  no duplicates. )@Look up the specified subroutine in the namespace, and apply it J to the specified inputs, or throw an error if they are not appropriately  typed.  The input/9output types of this function are determined dynamically  by the + stored with the subroutine. *@Insert a comment in the circuit. This is not a gate, and has no C effect, except to mark a spot in the circuit. The comment has two @ parts: a string (possibly empty), and a list of labelled wires B (possibly empty). This is a low-level function. Users should use  comment instead. +>Disable labels and comments for a block of code. The intended  usage is like this:   without_comments $ do {  <<<code block>>>  } DThis is sometimes useful in situations where code is being re-used, C for example when one function is implemented in terms of another, C but should not inherit comments from it. It is also useful in the B definition of recursive function, where a comment should only be E applied at the outermost level. Finally, it can be used to suppress < comments from parts of circuits for presentation purposes. , Convert a  (boolean circuit output) to a ' (boolean  parameter). BFor use in algorithms that require the output of a measurement to B 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 D consists of classical circuit endpoints (whose values are known at @ circuit execution time), and the output is a boolean parameter 5 (whose value is known at circuit generation time). BThe use of this operation implies an interleaving between circuit B execution and circuit generation. It is therefore a (physically) = expensive operation and should be used sparingly. Using the  ,2 operation interrupts the batch mode operation of B the quantum device (where circuits are generated ahead of time), D and forces interactive operation (the quantum device must wait for E the next portion of the circuit to be generated). This operation is A especially expensive if the current circuit contains unmeasured > qubits; in this case, the qubits must be preserved while the $ quantum device remains on standby. CAlso note that this operation is not supported in all contexts. It C 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. E Also, not all output devices (such as circuit viewers) support this  operation. --Generate a new qubit initialized to |+#* when b= and  |"#* when b=m. .?Generate a new qubit initialized to one of |0#*, |1#*, |+#*, |"#*,  depending on a character c which is '0', '1', '+', or '-'. /AGenerate a list of qubits initialized to a sequence of |0#*, |1#*, - |+#*, |"#*, defined by a string argument e.g. "00+0+++". 0 A version of  that operates on lists. 1 A version of ' that operates on lists. We initialize B 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 1 is longer than the right > argument, then it is truncated. So the first argument can be  ( 2). It is an error if the left argument is shorter  than the right one. 2 A version of  for lists. 3Convenient wrapper around qinit and qterm. This can be used 8 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 8 will be returned to state |0#* at the end of the block. A block created with 3 is controllable, provided that  the body is controllable. 4 A syntax for "if"*-style (classical and quantum) controls.  This can be used as follows:   gate1 # with_controls <<controls>> $ do {  gate2  gate3  }  gate4 DThe specified controls will be applied to gate2 and gate3. It is an A error to specify a control for a gate that cannot be controlled  (such as measurement). 59An infix operator to apply the given controls to a gate:   gate `controlled` <<controls>> +It also works with functional-style gates:  * result <- gate `controlled` <<controls>> =The infix operator is left associative, so it can be applied  multiple times:  F result <- gate `controlled` <<controls1>> `controlled` <<controls2>> The latter is equivalent to > result <- gate `controlled` <<controls1>> .&&. <<controls2>> 68Apply a block of gates while temporarily suspending the @ application of controls. This can be used to omit controls on D gates where they are known to be unnecessary. This is a relatively B low-level function and should not normally be called directly by E user code. Instead, it is safer to use a higher-level function such  as with_basis_change. However, the 6 operator is D useful in certain situations, e.g., it can be used to preserve the  M 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 6 block. This is even true if  the 6( block appears in a subroutine, and the B subroutine is later called in a controlled context. On the other * hand, it is possible to specify controls inside the  6 block. Consider this example:   my_subcircuit = do  gate1  without_controls $ do {  gate2 & gate3 `controlled` <<controls1>>  }  gate4   my_circuit = do , my_subcircuit `controlled` <<controls2>> BIn this example, controls 1 will be applied to gate 3, controls 2 C will be applied to gates 1 and 4, and no controls will be applied  to gate 2. 7Apply 6 if M is m , otherwise  do nothing. 83Generate a new qubit, initialized to the parameter ', that > is guaranteed to be used as an ancilla and terminated with  9. Deprecated. 9-Terminate an ancilla asserted to be in state b. Deprecated. :AThe identity transformer. This just maps a low-level circuits to D the corresponding circuit-generating function. It can also be used 6 as a building block in other transformers, to define " catch-all"  clauses for gates that don't need to be transformed. NThe identity transformer can be enriched with a dynamic lifting operation, so # as to define a DynamicTransformer ;DThe identity DynamicTransformer uses the built in do_read operation +We can define a dynamic transformer with a constant lifting function <Append the entire circuit c# to the current circuit, using the * given bindings. Return the new bindings. =Append the entire circuit c# to the current circuit, using the 0 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, C using the given bindings, and return the new bindings. Also, add 3 to the current namespace state any subroutines of c that are not  already provided. ? Similar to *, 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 f). This is a low-level operator, intended - for the construction of primitives, such as  with_computed or  with_basis_change(, where the inner block can re-use some . variables without declaring them explicitly. =We 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., E wires that were used during the execution of the body, but are free  at the end. @Intermediate between  and ?: C we build the circuit in the namespace of the current circuit, to + avoid recomputing any shared subroutines. A Append the '* to the end of the current circuit, using 6 the identity binding. This means, the input wires of '  must> 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 A. 9Note that this is a low-level function, intended for the / construction of user-level primitives such as  with_computed and  with_basis_change, and classical_to_reversible. A uses  to do the appending,  so the current  and M are respected. B However, it does not pass through the transformer interface, and  therefore low-level wire id's will be exactly preserved. B Reverse an encapsulated circuit CAn encapsulated circuit is a circuit together with data structures D holding the input endpoints and output endpoints. The type of the D encapsulated circuit depends on the type of data in the endpoints, E so functions to encapsulate and unencapsulate circuits are provided  in Quipper.Generic. C?Perform the computation in the body, but temporarily reserve a E set of wires. These wires must be initially free, and they must not C be used by the body (i.e., the body must respect reserved wires).       !"#$%&'()*+,-./0123456789:;<=>?@ABC!"#$%NOQR      !"#$%&'()*+,-./0123456789:;<=>?@ABC!%$#"QRON)      !"#$%&'(*+,-./0123456789:;<=>?@ABC      !"#$%&'()*+,-./0123456789:;<=>?@ABCNoneDD a s means that a is a data structure that can  be labelled with the format s. A "format" is a string, or a , data structure with strings at the leaves. E;Recursively label a data structure with the given format. F6A monad to provide a convenient syntax for specifying D B instances. Computations in this monad have access to a read-only  "current index list"*, and they output a binding from wires to  strings. I@An 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"5, and perhaps arbitrary suffixes. A complication is B that we want consecutive subscript indices to be combined, as in  "[i,j,k]"8. We therefore need a special data structure to hold an  index list "under construction". 9An index list consists of a string and a list of current A subscripts. For efficiency, the list of subscripts is reversed, = i.e., the most recent subscript is at the head of the list. J#Convert an index list to a string. KThe empty index list. L%Append a subscript to an index list. M(Append a dotted index to an index list. N"Get the current string and index. OOutput a binding for a label P4Run a subcomputation with a new current index list. Q@Extract a labelling from a label monad computation. This is the " run function of the label monad. R;Label a wire with the given name, using the current index. S<Run a subcomputation with a subscript index appended to the # current index list. Sample usage:  with_index "0" $ do  <<<labelings>>> TARun a subcomputation with a dotted index appended to the current ] index list. Sample usage:  with_dotted_index "left" $ do  <<<labelings>>> ULike S', except the order of the arguments is = reversed. This is intended to be used as an infix operator:  <<<labeling>>> `indexed` "0" VLike T', except the order of the arguments is = reversed. This is intended to be used as an infix operator: ( <<<labeling>>> `dotted_indexed` "left" W Do nothing. X?Given a data structure and a format, return a list of labelled  wires. Y@Insert a comment in the circuit. This is not a gate, and has no B effect, except to mark a spot in the circuit. How the comment is , displayed depends on the printing backend. Z<Label qubits in the circuit. This is not a gate, and has no B 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 Y and Z in a single command. <DEFGHIJKLMNOPQRSTUVWXYZ[DEFGHIJKLMNOPQRSTUVWXYZ[IJKLMFGHNOPQRSTUVWDEXYZ[9DEFGHIJKLMNOPQRSTUVWXYZ[None8\The 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". a The class a consists of the two types  and . C It is primarily used for convenience, in those cases (such as the E arithmetic library) where some class instance should be defined for  the cases  and , but not for general o. It is + also used, e.g., in the definition of the ./=. operator. bb+ is a convenience type class that combines  d and m. cb+ is a convenience type class that combines  d and m. dThe d# type class is almost identical to o, B except that it contains one additional piece of information that 3 allows the type checker to prove the implications  E 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) DThis is sometimes useful, for example, in the context of a function  that inputs a o), measures all the qubits, and returns a  g;. However, the additional information for the type checker D comes at a price, which is drastically increased compilation time.  Therefore d should only be used when o is  insufficient. eThe e7 class allows the definition of generic functions that $ can operate on quantum data of any "shape", for example, nested  tuples or lists of qubits. CIn general, there are three kinds of data: quantum inputs (such as  ), classical inputs (such as ), and classical  parameters (such as '). For example, a  can be  initialized from a '; a  can be measured, resulting in  a ', etc. For this reason, the type class e establishes a  relation between three types:  qa A 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 ' at  the leaves. CSome functions input a classical parameter for the sole purpose of  establishing the "shape") of a piece of data. The shape refers to D qualities of a data structure, such as the length of a list, which E are not uniquely determined by the type. For example, two different B lists of length 5 have the same shape. When performing a generic B operation, such as reversing a circuit, it is often necessary to = specify the shape of the inputs, but not the actual inputs. DIn the common case where one only needs to declare one of the types  qa, ca, or ba", one of the simpler type classes h,  g, or f can be used. fThe f5 type class contains homogeneous data types built up  from leaves of type '. gThe g5 type class contains homogeneous data types built up  from leaves of type . hThe h5 type class contains homogeneous data types built up  from leaves of type . iThe type operator i x# converts a classical, quantum, or 0 boolean type to a homogeneous type with leaves x. More precisely,  the type i x a represents the substitution  [nobr a [x / , x / ]].  For example:  % HType x (Qubit, [Qubit]) = (x, [x])  HType x (Qubit, Bit) = (x, x) *There is a very subtle difference between i x a and  t x x a-. Although these two types are equal for all  x and a., the type checker cannot actually prove that t  x x a$ is homogeneous from the assumption o a. It  can, however, prove that i x a is homogeneous. Therefore  i/ (or the slightly more efficient special cases l,  k, j0) should always be used to create a homogeneous  type from a heterogeneous one. jThe type operator j# converts a classical, quantum, or C heterogeneous type to a homogeneous boolean type. More precisely,  the type j a represents the substitution  [nobr a [' / , ' / ]]. It can be applied to ? both homogeneous and heterogeneous types, and always yields a  homogeneous type. For example: ) BType (Qubit, [Qubit]) = (Bool, [Bool]) # BType (Qubit, Bit) = (Bool, Bool) kThe type operator k' converts a classical or heterogeneous > type to a homogeneous quantum type. More precisely, the type  k a# represents the substitution [nobr a [ / ]]. It A can be applied to both homogeneous and heterogeneous types, and 0 always yields a homogeneous type. For example: ' CType (Qubit, [Qubit]) = (Bit, [Bit]) ! CType (Qubit, Bit) = (Bit, Bit) lThe type operator l' converts a classical or heterogeneous > type to a homogeneous quantum type. More precisely, the type  l a# represents the substitution [nobr a [ / ]]. D It can be applied to both homogeneous and heterogeneous types, and 0 always yields a homogeneous type. For example: ' QType (Bit, [Bit]) = (Qubit, [Qubit]) % QType (Qubit, Bit) = (Qubit, Qubit) mm is a subclass of o consisting of simple  types. We say that a data type t is "simple" if any two  elements of t5 have the same number of leaves. For example, tuples  are simple, but lists are not. n:Produce a term of the given shape. This term will contain , well-defined data constructors, but may be  at the  leaves. oThe o4 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 D data, such as copying, transformers, simulation, and heterogeneous ! versions of qterm and qdiscard. o and h) 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:  ( QCData qc implies QData (QType qc) ( QCData qc implies CData (CType qc) ( QCData qc implies BData (BType qc) DHowever, the type checker cannot prove the above implication in the  case where qc1 is a type variable; for this, the more flexible & (but more computationally expensive) d class can be used. pMap 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. 9Example (ignoring the monad for the sake of simplicity):  M qcdata_mapM (qubit, bit, [qubit]) f g (x,y,[z,w]) = (f x, g y, [f z, f w]). BFor data types that have a sense of direction, the mapping should B preferably be performed from left to right, but this property is 0 not guaranteed and may change without notice. q@Zip two heterogeneous data structures together, to obtain a new C data structure of the same shape, whose elements are pairs of the B corresponding elements of the input data structures. The zipping  is strict3, meaning that both input data structure must have ? exactly the same shape (same length of lists, etc). The first B five arguments are shape type parameters, representing the shape = of the data structure, the two leaf types of the first data A structure, and the two leaf types of the second data structure,  respectively.  Example:  t 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 0 argument is a stub error message to be used in  case of failure. r<It is sometimes convenient to have a boolean parameter with 6 some aspect of its shape indeterminate. The function  r. takes such a boolean parameter, as well as a  piece of o1, 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, r has no work to B do and should just return the first argument. For types that are 5 not simple, but where no promotion is desired (e.g. Qureg),  r/ should check that the shapes of the first and A second argument agree, and throw an error otherwise. For lists, A we allow a longer list to be promoted to a shorter one, but not A the other way around. For quantum integers, we allow an integer A of indeterminate length to be promoted to a determinate length, C but we do not allow a determinate length to be changed to another  determinate length. The 0 argument is a stub error message to be used in  case of failure. s The type s ba represents the substitution  [nobr ba [ / ']]. For example:  8 QTypeB (Bool, Bool, [Bool]) = (Qubit, Qubit, [Qubit]). GAn instance of this must be defined for each new kind of quantum data. t The type t x y a represents the substitution  [nobr a [x / , y / ]]. For example:  1 QCType x y (Qubit, Bit, [Qubit]) = (x, y, [x]). AAn instance of this must be defined for each new kind of quantum  data. u'A dummy term of any type. This term is  and must never 3 be evaluated. Its only purpose is to hold a type. vA dummy term of type %. It can be used in shape parameters  (e.g., qc_init+), as well as shape type parameters (e.g.,  p). wA dummy term of type %. It can be used in shape parameters  (e.g., qc_init+), as well as shape type parameters (e.g.,  p). xA dummy term of type '. y<Convert a piece of homogeneous quantum data to a shape type 1 parameter. This is guaranteed to never evaluate x, and returns an  undefined value. z>Convert a piece of homogeneous classical data to a shape type 1 parameter. This is guaranteed to never evaluate x, and returns an  undefined value. {<Convert a piece of homogeneous boolean data to a shape type 1 parameter. This is guaranteed to never evaluate x, and returns an 8 undefined value. Do not confuse this with the function qshape,  which creates a shape value. |4A dummy term of the same type as the given term. If x :: a,  then u x :: a%. This is guaranteed not to evaluate x, ! and returns an undefined value. }Map a function f/ over all the leaves of a data structure. The F first argument is a dummy shape parameter: its value is ignored, but  its type9 is used to determine the shape of the data to map over. 9Example (ignoring the monad for the sake of simplicity):  C qdata_mapM (leaf, [leaf]) f (x,[y,z,w]) = (f x, [f y, f z, f w]). BFor data types that have a sense of direction, the mapping should B 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 y together, to ? obtain a new data structure of the same shape with leaf type (x,  yL). The first three arguments are dummy shape type parameters, representing 6 the shape type and the two leaf types, respectively. The 5 argument is a stub error message to be used in case  of failure. @Sometimes, it is possible to have a boolean parameter with some 1 aspect of its shape indeterminate. The function  E takes such a boolean parameter, as well as a piece of quantum data, 9 and sets the shape of the former to that of the latter. BIndeterminate shapes can be used with certain operations, such as D controlling and terminating, where some aspect of the shape of the = parameter can be determined from the context in which it is A used. This is useful, e.g., for quantum integers, where one may C 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 .==. 17 instead of the more cumbersome  8 gate `controlled` qi .==. (intm (qdint_length qi) 17). AAnother 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 B hopefully make it clearer to the user which operation caused the  error. The inverse of ~': Take a data structure with leaf type  (x, y9), and return two data structures of the same shape with  leaf types x and y., respectively. The first three arguments are 4 dummy shape type parameters, analogous to those of ~. @Map 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 : Visit every leaf in a data % structure, updating an accumulator. Monadic version of : Map a function over every D leaf in a data structure, while also updating an accumulator. This  combines the functionality of  and }. AReturn a list of leaves of the given homogeneous data structure. F The first argument is a dummy shape type parameter, and is only used  for its type. DThe leaves are ordered in some deterministic, but arbitrary way. It D is guaranteed that when two data structures of the same shape type E and shape (same length of lists etc) are sequentialized, the leaves A 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" E desired (length of lists, etc); then reads the given list of leaves C in as a piece of homogeneous data of the same shape. The ordering 7 of the leaves 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. 0Please note that, by contrast with the function  %, the first argument is a shape term C 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:  q< 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 B sufficient to determine the depth of leaves in a data structure,  but not their number.  x: captures only the size of the data, but not its type. In  particular, x& may have leaves of non-atomic types. x must C 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 x, C and can therefore be used both as a shape type and a shape value.  Note that the actual leaves of qx will be v and w,  which are synonyms for .  Example:  ' q = undefined :: ([Qubit], [[Qubit]]) - x = ([undefined, 0], [[undefined], [0, 1]]) F qdata_makeshape qc a x = ([qubit, qubit], [[qubit], [qubit, qubit]]) where a :: Int. Like }/, except the leaves are visited in exactly the B opposite order. This is used primarily for cosmetic reasons: For : example, when initializing a bunch of ancillas, and then D 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 q%: Take a data structure whose leaves > are pairs, and return two data structures of the same shape, B collecting all the left components and all the right components, C respectively. The first five arguments are shape type parameters,  analogous to those of q. 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 p. 2Visit 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 : 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 D leaf in a data structure, while also updating an accumulator. This  combines the functionality of  and p. 8Return a list of leaves of the given heterogeneous data D 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. DThe leaves are ordered in some deterministic, but arbitrary way. It D is guaranteed that when two data structures of the same shape type E and shape (same length of lists etc) are sequentialized, the leaves A will be ordered the same way. No other property of the order is < guaranteed, In particular, it might change without notice. <Take 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 C shape. The ordering of the leaves, and the division of the leaves A 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  entry corresponding to a   position in the shape, or an  entry  corresponding to a  position. 0Please note that, by contrast with the function  %, the first argument is a shape term C parameter, not a shape type parameter. It is used to decide where 6 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:  q< 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 B sufficient to determine the depth of leaves in a data structure,  but not their number.  x: captures only the size of the data, but not its type. In  particular, x& may have leaves of non-atomic types. x must C 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 x, C and can therefore be used both as a shape type and a shape value.  Note that the actual leaves of qx will be v and w,  which are synonyms for .  Example:  & qc = undefined :: ([Qubit], [[Bit]]) @ x = ([undefined, (0,False)], [[undefined], [Just 2, Nothing]]) C qcdata_makeshape qc a b x = ([qubit, qubit], [[bit], [bit, bit]]) where a ::  (Int,Bool), b ::  (Maybe Int). Like p/, except the leaves are visited in exactly the B opposite order. This is used primarily for cosmetic reasons: For : example, when initializing a bunch of ancillas, and then D terminating them, the circuit will look more symmetric if they are # terminated in the opposite order.  Turn any o1 into a string uniquely identifying its type and E shape. The current implementation assumes that appropriately unique   instances are defined for all o. e\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&:\]^_`abcdefghijklmnopqrstuvwxyz{|}~:tsopqrmnlkjiuvwxyz{|h}~gfedcba_`]^\_\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%& None]The  type class is similar to the " type class, / except that the result type is guarded by the  monad. It ( provides a family of type isomorphisms  fun "E args -> Circ res,where  * fun = a1 -> a2 -> ... -> an -> Circ res, % args = (a1, (a2, (..., (an, ())))). The benefit of having Circ' in the result type is that it ensures C 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 fun*, which can be used to write higher-order  operators that consume fun of any arity and " do the right  thing". =Initialize a qubit from a boolean parameter. More generally, A initialize a data structure of qubits from a corresponding data , structure of boolean parameters. Examples:  q <- qinit False ! (q0, q1) <- qinit (True, False) + [q0, q1, q2] <- qinit [True, False, True] <Terminate a qubit, asserting its state to equal the boolean B parameter. More generally, terminate a data structure of qubits, ? asserting that their state is as given by a data structure of  booleans parameters. Examples:   qterm False q  qterm (False, False) (q0, q1) * qterm [False, False, False] [q0, q1, q2] AIn some cases, it is permissible for some aspect of the parameter's D shape to be underspecified, e.g., a longer than necessary list, or C an integer of indeterminate length. It is therefore possible, for  example, to write:  + qterm 17 qa -- when qa :: QDInt, - qterm [False..] qa -- when qa :: [Qubit]. -The rules for when a boolean argument can be "promoted" in this 0 way are specific to each individual data type. @Discard a qubit, ignoring its state. This can leave the quantum A system in a mixed state, so is not a reversible operation. More 5 generally, discard all the qubits in a quantum data  structure. Examples:  qdiscard q  qdiscard (q0, q1)  qdiscard [q0, q1, q2]  Initialize a  (boolean input) from a ' (boolean E parameter). More generally, initialize the a data structure of Bits 9 from a corresponding data structure of Bools. Examples:  b <- cinit False ! (b0, b1) <- cinit (True, False) + [b0, b1, b2] <- cinit [True, False, True]  Terminate a ), asserting its state to equal the given  '6. More generally, terminate a data structure of Bits, ? asserting that their state is as given by a data structure of  Bools. Examples:   cterm False b  cterm (False, False) (b0, b1) * cterm [False, False, False] [b0, b1, b2] AIn some cases, it is permissible for some aspect of the parameter's D shape to be underspecified, e.g., a longer than necessary list, or C an integer of indeterminate length. It is therefore possible, for  example, to write:  * cterm 17 ca -- when ca :: CInt, + cterm [False..] ca -- when ca :: [Bit]. -The rules for when a boolean argument can be "promoted" in this 0 way are specific to each individual data type.  Discard a 3, ignoring its state. This can leave the system in B a mixed state, so is not a reversible operation. More generally, 5 discard all the Bits in a data structure. Examples:  cdiscard b  cdiscard (b0, b1)  cdiscard [b0, b1, b2] Heterogeneous version of . Please note that the type of E the result of this function cannot be inferred from the type of the  argument. For example,   x <- qc_init False Ais 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 Qubit Alternatively,  can be used to fix a specific  type.  A version of ' that uses a shape type parameter. The E first argument is the shape type parameter, and the second argument E is a data structure containing boolean initializers. The shape type C argument determines which booleans are used to initialize qubits, 7 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 . Heterogeneous version of .  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:  b <- measure q  (b0, b1) <- measure (q0, q1) & [b0, b1, b2] <- measure [q0, q1, q2]  Prepare a  initialized from a . More generally, F prepare a data structure of Qubits, initialized from a corresponding # data structure of Bits. Examples:  q <- prepare b  (q0, q1) <- prepare (b0, b1) & [q0, q1, q2] <- prepare [b0, b1, b2] Heterogeneous version of . Given a heterogeneous data D structure, measure all of its qubits, and leave any classical bits  unchanged. Heterogeneous version of . Given a heterogeneous data B structure, prepare qubits from all classical bits, and leave any  qubits unchanged. Like , except the gate is also "anchored" at a B qubit, a bit, or more generally at some quantum data. The anchor D is only used as a hint for graphical display. The gate, which is a D zero-qubit gate, will potentially be displayed near the anchor(s). BApply a Hadamard gate to every qubit in a quantum data structure. Imperative version of . BApply a swap gate to two qubits. More generally, apply swap gates @ to every corresponding pair of qubits in two pieces of quantum  data. BApply a swap gate to two qubits. More generally, apply swap gates @ to every corresponding pair of qubits in two pieces of quantum  data. ;Apply a controlled-not gate to every corresponding pair of > quantum or classical bits in two pieces of QCData. The first A argument is the target and the second the (positive) control. AFor now, we require both pieces of QCData to have the same type, C i.e., classical bits can be controlled only by classical bits and 6 quantum bits can be controlled only by quantum bits.  Example:  0 ((a',b'), (x,y)) <- controlled_not (a,b) (x,y) is equivalent to  a' <- qnot a `controlled` x  b' <- qnot b `controlled` y Imperative version of . Apply a controlled-not B 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.  A version of  where the control consists of  boolean data. Example:  3 bool_controlled_not (q, r, s) (True, True, False) negates q and r , but not s.  A version of  where the control consists of  boolean data. Example:  6 bool_controlled_not_at (q, r, s) (True, True, False) negates q and r , but not s. /Negate all qubits in a quantum data structure. /Negate all qubits in a quantum data structure. =Initialize a new piece of quantum data, as a copy of a given 1 piece. Returns both the original and the copy. <Given two pieces of quantum data, assumed equal (w.r.t. the B computational basis), terminate the second piece (and return the , first, unmodified). This is the inverse of , 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 copy ACreate a fresh copy of a piece of quantum data. Note: copying is D performed via a controlled-not operation, and is not cloning. This  is similar to +, except it returns only the copy, and not  the original. "Uncopy") a piece of quantum data; i.e. terminate copy,  assuming it' s a copy of orig. This is the inverse of  ., in the sense that the following sequence of 2 instructions behaves like the identity function:  b <- qc_copy a  qc_uncopy a b If a is m, return a copy of b, else return a copy of  c. Here b and c* can be any data structures consisting of  Bits, but b and c) must be of the same type and shape (for 3 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] 6 is an if-then-else function for classical circuits.  It is a wrapper around !, intended to be used like this:  % result <- circ_if <<<condition>>> (  <<then-part>>>  )(  <<<else-part>>>  ) Unlike 0, this is a meta-operation, i.e., the bodies of  the "then" and "else" parts can be circuit building  operations. 1What makes this different from the usual boolean " if-then-else" " is that the condition is of type , i.e., it is only known at B 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. ;Define a new functional-style gate of the given name. Like  2, except that the generated gate is extended with  "generalized controls"*. The generalized controls are additional C inputs to the gate that are guaranteed not to be modified if they D are in a computational basis state. They are rendered in a special ! way in circuit diagrams. Usage:  = my_new_gate :: (Qubit,Qubit) -> Qubit -> Circ (Qubit,Qubit) ' my_new_gate = extended_named_gate "Q" "This defines a new gate with name Q, two inputs, and one  generalized input. Like +, except defines an imperative style gate.  Usage:  5 my_new_gate_at :: (Qubit,Qubit) -> Qubit -> Circ () - my_new_gate_at = extended_named_gate_at "Q" "This defines a new gate with name Q, two inputs, and one  generalized input. =Define a new functional-style gate of the given name. Usage:  & my_unary_gate :: Qubit -> Circ Qubit  my_unary_gate = named_gate "Q"  9 my_binary_gate :: (Qubit, Qubit) -> Circ (Qubit, Qubit) ! my_binary_gate = named_gate "R" CThis defines a new unary gate and a new binary gate, which will be  rendered as Q and R&, respectively, in circuit diagrams. =Define a new imperative-style gate of the given name. Usage:  & my_unary_gate_at :: Qubit -> Circ () & my_unary_gate_at = named_gate_at "Q"  0 my_binary_gate_at :: (Qubit, Qubit) -> Circ () ' my_binary_gate_at = named_gate_at "R" CThis defines a new unary gate and a new binary gate, which will be  rendered as Q and R&, respectively, in circuit diagrams. :Define a new functional-style gate of the given name, and B parameterized by a real-valued parameter. This is typically used B for rotations or phase gates that are parameterized by an angle.  The name can contain '%'& as a place holder for the parameter.  Usage:  & my_unary_gate :: Qubit -> Circ Qubit 2 my_unary_gate = named_rotation "exp(-i%Z)" 0.123 E my_binary_gate :: TimeStep -> (Qubit, Qubit) -> Circ (Qubit, Qubit) , my_binary_gate t = named_rotation "Q(%)" t :Define a new imperative-style gate of the given name, and B parameterized by a real-valued parameter. This is typically used B for rotations or phase gates that are parameterized by an angle.  The name can contain '%'& as a place holder for the parameter.  Usage:  & my_unary_gate_at :: Qubit -> Circ () 5 my_unary_gate_at = named_rotation "exp(-i%Z)" 0.123 < my_binary_gate_at :: TimeStep -> (Qubit, Qubit) -> Circ () / my_binary_gate_at t = named_rotation "Q(%)" t  Convert a  (boolean circuit output) to a ' (boolean C parameter). More generally, convert a data structure of Bits to a ( corresponding data structure of Bools. BFor use in algorithms that require the output of a measurement to B 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 D consists of classical circuit endpoints (whose values are known at @ circuit execution time), and the output is a boolean parameter 5 (whose value is known at circuit generation time). BThe use of this operation implies an interleaving between circuit B execution and circuit generation. It is therefore a (physically) = expensive operation and should be used sparingly. Using the  6 operation interrupts the batch mode operation of the B quantum device (where circuits are generated ahead of time), and D forces interactive operation (the quantum device must wait for the A next portion of the circuit to be generated). This operation is A especially expensive if the current circuit contains unmeasured > qubits; in this case, the qubits must be preserved while the $ quantum device remains on standby. CAlso note that this operation is not supported in all contexts. It C 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. E Also, not all output devices (such as circuit viewers) support this  operation. BMap a single qubit gate across every qubit in the data structure. ?Map a binary gate across every corresponding pair of qubits in - two quantum data structures of equal shape. Like 1, except the second data structure is classical. BMap a binary qubit circuit to every pair of qubits in the quantum E data-type. It is a run-time error if the two structures do not have  the same size. Heterogeneous version of . Map a binary gate f > across every corresponding pair of qubits, and a binary gate g > across every corresponding pair of bits, in two quantum data  structures of equal shape. ?Return the list of qubits representing the given quantum data. @ The qubits are ordered in some fixed, but arbitrary way. It is E 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 E guaranteed, In particular, the order may change without notice from % one version of Quipper to the next. 5Take a specimen piece of quantum data to specify the "shape" E desired (length of lists, etc); then reads the given list of qubits B 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. A "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  o6. The leaves are ordered in some fixed, but arbitrary A way. It is guaranteed that two pieces of data of the same given A shape will be ordered in the same way. No other property of the N order is guaranteed. In particular, the order may change without notice from % one version of Quipper to the next. Take a specimen piece of o 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 9 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 o to specify a shape;  return a + that structures appropriate E 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. ?Return a boolean data structure of the given shape, with every  leaf initialized to . AReturn a quantum data structure of the given boolean shape, with 5 every leaf initialized to the undefined dummy value v. @Take two pieces of quantum data of the same shape (the first of < which consists of wires of a low-level circuit) and create  bindings. (Apply bindings to a piece of quantum and/or classical data 9 holding low-level wires, to get data of the same shape. (BGiven a piece of quantum data and a possible value for it, return  a 2 representing the condition that the quantum data  has that value. If some aspect of the value' s shape is indeterminate, it is B promoted to the same shape as the quantum data; therefore, it is " possible, for example, to write: / qc_control qa 17 -- when qa :: QDInt 1 qc_control qa [False..] -- when qa :: [Qubit] ?This is an infix operator to concatenate two controls, forming  their logical conjunction.  (qx .==. x)/: a control which is true just if quantum data qx is in the specified state x.  The notation (q ./=. x) is shorthand for (q .==. not x), when  x is a boolean parameter. Unlike 2, which is defined for any shape of quantum data,  4 is only defined for a single control bit or qubit. );Allocate new quantum data of the given shape, in the given 8 arity. Returns the quantum data and the updated arity. :Extract an encapsulated circuit from a circuit-generating , function. This requires a shape parameter. As #, but passes the current namespace ; into the circuit-generating function, to save recomputing  shared subroutines <Turn an encapsulated circuit back into a circuit-generating  function. BExtract an encapsulated dynamic circuit from a circuit-generating , function. This requires a shape parameter. 1Turn 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. =Reverse a circuit-generating function. The reversed function E requires a shape parameter, given as the input type of the original  function. BThe type of this highly overloaded function is quite difficult to 5 read. It can have for example the following types: Q reverse_generic :: (QCData x, QCData y) => (x -> Circ y) -> x -> (y -> Circ x) i reverse_generic :: (QCData x, QCData y, QCData z) => (x -> y -> Circ z) -> x -> y -> (z -> Circ (x,y)) Like (, but takes functions whose output is a 9 tuple, and curries the reversed function. Differs from   in an example such as:  5 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 n "e E 2. Applying this to a circuit whose output is a non-tuple type is a  type error; in this case,  should be used. Like &, but only works at simple types, and B therefore requires no shape parameters. Typical type instances: Q reverse_simple :: (QCData_Simple x, QCData y) => (x -> Circ y) -> (y -> Circ x) k reverse_simple :: (QCData_Simple x, QCData_Simple y, QCData z) => (x -> y -> Circ z) -> (z -> Circ (x,y)) Like (, but takes functions whose output is a B tuple, and curries the reversed function. Typical type instance:  l reverse_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 n "e E 2. Applying this to a circuit whose output is a non-tuple type is a  type error; in this case,  should be used. Like +, but specialized to endomorphic circuits, F i.e., circuits where the input and output have the same type (modulo 4 possibly currying) and shape. In this case, unlike , F no additional shape parameter is required, and the reversed function C is curried if the original function was. Typical type instances: F reverse_generic_endo :: (QCData x) => (x -> Circ x) -> (x -> Circ x) b reverse_generic_endo :: (QCData x, QCData y) => (x -> y -> Circ (x,y)) -> (x -> y -> Circ (x,y)) Like &, but applies to endomorphic circuits  expressed in " imperative" style. Typical type instances: H reverse_generic_endo :: (QCData x) => (x -> Circ ()) -> (x -> Circ ()) \ reverse_generic_endo :: (QCData x, QCData y) => (x -> y -> Circ ()) -> (x -> y -> Circ ()) Conditional version of  . Invert the @ endomorphic quantum circuit if the boolean is true; otherwise, " insert the non-inverted circuit. Conditional version of  . Invert the E imperative style quantum circuit if the boolean is true; otherwise, " insert the non-inverted circuit. ,Like ', but also takes a stub error message. Like (, but applies to arbitrary transformers  of type   Transformer m a b instead of the special case   Transformer Circ Qubit Bit. -This requires an additional shape argument. *Apply the given transformer to a circuit. 9Like transform_unary_shape but for a dynamic transformer 3Like transform_unary but for a dynamic transformer Like (, but applies to arbitrary transformers  of type   Transformer m a b instead of the special case   Transformer Circ Qubit Bit. -This requires an additional shape argument. =The type of this heavily overloaded function is difficult to A read. In more readable form, it has all of the following types:  T transform_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. 2Apply the given transformer to a circuit. Unlike  $, this function can be applied to a 2 circuit-generating function in curried form with n arguments, for  any n "e 0. =The type of this heavily overloaded function is difficult to A read. In more readable form, it has all of the following types:  S transform_generic :: (QCData x) => Transformer Circ Qubit Bit -> Circ x -> Circ x k 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'fs responsibility to return the ancilla to its original state at the end of the enclosed block. Usage:  % with_ancilla_init True $ \a -> do { 8 <<<code block using ancilla a initialized to True>>>  } 2 with_ancilla_init [True,False,True] $ \a -> do { N <<<code block using list of ancillas a initialized to [True,False,True]>>>  } Like 3, but creates a list of n ancillas, all  initialized to |0#*. Usage: " with_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 code' may refer to any qubits that exist in 7 the current environment, and they may also create new  qubits.  computation. may produce arbitrary garbage in addition to  its output. BThis 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 code$ must ensure that the corresponding ! assertions will be satisfied in  computation[sup "1]. BRelated more specialized, but potentially safer, operations are:  , which is like , but assumes  that  computation is unitary, and  classical_to_reversible, 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 code( are in imperative style. It is the user's , responsibility to ensure that the image of code is contained in  the image of  basischange), or else there will be unmet assertions  or runtime errors. Usage: $ with_basis_change basischange $ do  <<<code>>>   where  basischange = do  <<<gates>>> 9Bind a name to a function as a subroutine in the current @ namespace. This requires a shape argument, as well as complete D 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 E responsibility to ensure that the name is unique to the subroutine,  parameters, and shape. 'This function does nothing if the name 9 already exists in the namespace; in particular, it does not 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 C circuit-generating function, and returns a new circuit-generating A 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" somefunc Here, the type of somefunc' is just an example; this could indeed E 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:  ! somefunc :: Qubit -> Circ Qubit * somefunc = box "somefunc" $ \a -> do ...  Note: The , operator wraps around a complete function, D including all of its arguments. It would be incorrect to apply the  9 operator after some quantum variables have already been , defined. Thus, the following is incorrect:  + incorrect_somefunc :: Qubit -> Circ Qubit 0 incorrect_somefunc a = box "somefunc" $ do ... It is the user'.s responsibility not to use the same name for  different subroutines. If # is called more than once with the B same name and shape of input, Quipper assumes, without checking, 9 that they are subsequent calls to the same subroutine. The type of the / operator is overloaded and quite difficult to 5 read. It can have for example the following types: A box :: String -> (Qubit -> Circ Qubit) -> (Qubit -> Circ Qubit) o 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. BThis 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  ' that will be boxed conditionally on a # boolean condition. Typical usage: . loopM_boxed_if (s > 1) "name" s x $ \x -> do  <<<body>>>  return x -!The underlying implementation of  and  . It behaves  like 5, but is restricted to unary functions, and takes an   argument. =Classical control on a function with same shape of input and E 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 )), except inline the subroutine body from > the given namespace, instead of inserting a subroutine call. +Implementation note: this currently copies all subroutine B definitions from the given namespace into the current namespace, 7 and not just the ones used by the current subroutine. FImplementation note: this currently only works on lists of endpoints. b'()*+,-./0XX`'()*+,-./0 None%This is a quantum analogue of Haskell's  type class. Its E purpose is to define a total ordering on each of its instances. The E functions in this class are assumed dirty in the sense that they do C 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 B 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 1 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 . 22 NoneA  to eliminate all CGate style gates, such as  "and", "or", "not", "xor", "eq", and " if-then-else" ' gates, and replace them by equivalent CInit and CNot gates. AAuxiliary function: compute the reversible circuit corresponding  to a CGate5 of the given name, using only controlled-not gates. ;Translate all classical gates in a circuit into equivalent  controlled-not gates. CThe type of this overloaded function is difficult to read. In more 3 readable form, it has all of the following types:  8 classical_to_cnot :: (QCData qa) => Circ qa -> Circ qa S classical_to_cnot :: (QCData qa, QCData qb) => (qa -> Circ qb) -> (qa -> Circ qb) j 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 0 to replace all classical gates in a circuit by  equivalent quantum gates. FReplace all classical gates in a circuit by equivalent quantum gates. FReplace all classical gates in a circuit by equivalent quantum gates. CThe type of this overloaded function is difficult to read. In more 3 readable form, it has all of the following types:  C classical_to_quantum :: (QCData qa) => Circ qa -> Circ (QType qa) d 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. ?Generic function for turning a classical (or pseudo-classical) E 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"1 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  does not itself change  classical bits to qubits; use  for that.  NoneAvailable output formats. !Print statistics on gate counts. Don'Pt print anything, but preview directly on screen (requires the external program acroread). &A textual representation of circuits.  "PostScript. One circuit per page.  0Portable Document Format. One circuit per page.  "Encapsulated PostScript graphics. 3%Annotated gate counts of circuits. 4Gate counts of circuits. 5A data type analogous to 6, but with extra annotations,  e.g. a M-, for use in the computation of gate counts. 6=A data type representing equivalence classes of basic gates,  for the output of gatecounts. 7:An abbreviated representation of the controls of a gate: = the number of positive and negative controls, respectively. 8A 8 is a map from wire id's to pairs of a wiretype and a  starting x -coordinate.  8A data type that holds all the customizable parameters. The RenderFormat to use. The color of the background. 4The color of the foreground (e.g. wires and gates).  Line width. 0Gap for double line representing classical bit. Radius of dots for " controlled" gates. Radius of oplus for "not" gate. Horizontal column width. 4Difference 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 parameters 9>Determine whether a named gate is self-inverse. The kind of a B 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. :EGiven a map of wiretypes, and a gate, update the wiretype in the map  if the gate changes it. ; Convert a G to the string in the format "name", shape "x". <0Generate an ASCII representation of a control. H As controls are stored as untyped wires, we can lookup the wiretype in / the current map and annotate the control if it' s classical. =8Generate an ASCII representation of a list of controls. >4Generate an ASCII representation of a NoControlFlag ?3Generate an ASCII representation of a single gate. @1Generate an ASCII representation of a gate list. A0Generate an ASCII representation of a wiretype. B7Generate an ASCII representation of a type assignment. CBGenerate an ASCII representation of an arity, preceded by a title  (input or output). DBGenerate an ASCII representation of an ordered arity, preceded by  a title (input or output). E@Generate an ASCII representation of a low-level ordered quantum  circuit. FAGenerate an ASCII representation of a low-level quantum circuit. )>Generate an ASCII representation of a low-level boxed quantum  circuit. G8Generate an ASCII representation of a named subroutine. H<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 8 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 3 is ignored and the user is prompted to try again. @However, this also works for non-interactive input, so that the E input can be redirected from a file. In this case, the characters 0 ? and 1 and whitespace, including newlines, can be interspersed  freely. '#'4 starts a comment that extends until the end of the  line. I&Embed a read-write computation in the J monad, by writing A gates to the terminal and interactively querying the user (or a 7 file on stdin) for dynamic liftings. We also update a ( C while doing so, to collect any subroutines that are defined along  the way. +Interactively output a   to standard output. This D supports dynamic lifting by prompting the user for bit values when E a dynamic lifting operation is encountered. Effectively the user is ( asked to behave like a quantum device. KThe color white. LThe color black. M7A RenderFormat consisting of some default parameters, $ along with the given RenderFormat. ,The default PDF Style. -The default EPS Style. .The default PS Style. N/Escape special characters in a string literal. O Convert a G to the string in the format "name, shape x". PPre-processing: figure out the x-column of each gate. Returns  (n,xgs) where xgs is a list of (1, Q ) pairs, and  n is the rightmost x*-coordinate of the circuit. Here we start  from x0 and use constant step xoff taken from the  . R$Figure out how a gate at coordinate x affects the current 8.  Return a pair (term, new ), where term is the 8 of wires  terminated by this gate, and new is the outgoing 8 of this  gate. SS x0 y0 x1 y1: Draw a line from (x0, y0)  to (x1, y10). In case of a zero-length line, draw nothing. TT x y : Draw a filled control dot at (x,y). UU x y: Draw an empty control dot at  (x,y). VV x y : Draw a "not" gate at (x,y). WW x y(: Draw a cross (swap gate component) at  (x,y). XX x y: Draw an init term bar at (x,y/). YX x y: Draw a dterm bar at (x,y). ZZ 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 = m , 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. aa center s x y m: draw the given string 7 vertically, with the top of the string near the given  y-coordinate. If center==m, center it at the  x2-coordinate, else move it just to the left of the  x -coordinate. m0 is the maximum height allowed for the comment. bb center s x y": draw the given label just above  the given point. If center==m, center it at the  x3-coordinate, else move it just to the right of the  x -coordinate. c&Render the number at the given point (x,y). If the boolean  argument is m!, put the number to the right of x, else to the left. dRender 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. eARender a bunch of horizontal wires from their repective starting  8 to x. f=Format a floating point number in concise form, with limited  accuracy. gg 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. hh x ys y c: Render the line A 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 y-coordinate of the wire * where the floating gate is attached, and c is a list of controls. ii x ys c: Render the control dots  for the given controls. jj 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. kk x ys wires names : Render : the boxes for multiple generalized controls at the given wires,  using the given names(. We take special care of the fact that 1 generalized controls may be used non-linearly. ll x ys wires: Render the boxes for 7 multiple (numbered) generalized controls at the given wires. m9Number a list of wires in increasing order, at the given  x(-coordinate. If the boolean argument is m, put the numbers  to the right of x, else to the left. n 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. o5Render the gates in the circuit. The parameters are: xarity:  the 8! 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. p.PostScript definitions of various parameters. q<PostScript definitions for various drawing subroutines. The  subroutines provided are: > x0 y0 x1 y1 line : draw a line from (x0,y0) to (x1,y1) E x0 y0 x1 y1 dashedline : draw a dashed line from (x0,y0) to (x1,y1) Q x y h w rect : draw a rectangle of dimensions w x h centered at (x,y) M x y h w oval : draw an oval of dimensions w x h centered at (x,y) 0 x y dot : draw a filled dot at (x,y) 0 x y circ : draw an empty dot at (x,y) 0 x y oplus : draw a "not" gate at (x,y) C x y cross : draw a cross ("swap" gate component) at (x,y) 4 x y bar : draw an init/term bar at (x,y) / x y dbar : draw a dterm bar at (x,y) H 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) 5 name x y circgate : draw a named round box at (x,y) 4 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 h string x y m b comment : draw a vertical comment at (x,y), with max height m and baseline adjustment b A string x y clabel : draw a wire label at (x,y), x-centered A string x y rlabel : draw a wire label at (x,y), right of x 9 string x y lnumber : draw a numbered input at (x,y) : string x y rnumber : draw a numbered output at (x,y) rr name ocirc: Render the circuit ocirc on a  single page. CThe rendering takes place in the following user coordinate system: [image coord.png] s8Render a low-level boxed quantum circuit as a graphical  t8. If there are subroutines, each of them is placed on a  separate page. /:Render a low-level dynamic quantum circuit as a graphical  t8. If there are subroutines, each of them is placed on a B separate page. If the circuit uses dynamic lifting, an error is  produced. u>Print a representation of a low-level quantum circuit, in the B requested graphics format, directly to standard output. If there C are boxed subcircuits, each of them is placed on a separate page. vBPrint a representation of a low-level dynamic quantum circuit, in @ the requested graphics format, directly to standard output. If C there are boxed subcircuits, each of them is placed on a separate B page. If the circuit uses dynamic lifting, an error is produced. ww zoom pdffile: Call a system-specific PDF  viewer on pdffile file. The zoom argument is out of 100 and may & or may not be ignored by the viewer. x?Display a document directly in Acrobat Reader. This may not be , portable. It requires the external program "acroread" to be  installed. y?Display a document directly in Acrobat Reader. This may not be , portable. It requires the external program "acroread" to be  installed. 0@Display the circuit directly in Acrobat Reader. This may not be , portable. It requires the external program "acroread" to be  installed. z@Display a low-level dynamic quantum circuit directly in Acrobat D Reader. This may not be portable. It requires the external program  "acroread"7 to be installed. If the circuit uses dynamic lifting,  an error is produced. {<From a list of controls, extract the number of positive and  negative controls. |-Convenience constant for uncontrolled gates. }Forget the annotations of an 5 ~^Add controls to an annotated gate type, or throw an error message if it is not controllable;  unless its M+ is set, in which case leave it unchanged. LReverse an annotated gate type, of throw an error if it is not reversible. Set the M of an annotated gate type to m. Helper function for (: append a formatted arity to a string. 9Convert a given low-level gate to an annotated gate type 0Convert a gate type to a human-readable string. FGiven the (annotated) gatecount of a circuit, return the gatecount of L the reverse circuit, or throw an error if any component is not reversible. FGiven the (annotated) gatecount of a circuit, return the gatecount of J 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 m. )Remove the annotations from a gatecount. =Input a list of items and output a map from items to counts.  Example: 9 count ['a', 'b', 'a'] = Map.fromList [('a',2), ('b',1)] GCount the number of gates of each type in a circuit, with annotations, , treating subroutine calls as atomic gates. 5Count the number of gates of each type in a circuit, , treating subroutine calls as atomic gates.  Given an 5 describing a subroutine call  (possibly repeated), C and a gate count for the subroutine itself, return the gatecount  of the subroutine call. >(This may be the reverse of the original subroutine, may have  controls added, etc.) 5Given a circuit and gatecounts for its subroutines, 1 give an (aggregated) gatecount for the circuit. #Give the aggregate gate count of a '; that is, the H the total count of basic gates once all subroutines are fully inlined. MCount 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. 5Given a circuit and gatecounts for its subroutines, 1 give an (aggregated) gatecount for the circuit. <Print a gate count, as a table of integers and gate types. MPrint the simple gate count, plus summary information, for a simple circuit. 1'Print gate counts for a boxed circuit: = first the simple gate count for each subroutine separately, 2 then the aggregated count for the whole circuit. *Print gate counts for a named subroutine. Print gate counts for a static  . The circuit may not = use any dynamic lifting, or else an error will be produced. 2BA mapping from lower-case strings (to be used, e.g., with command % line options) to available formats. 3BPrint a low-level quantum circuit directly to the IO monad, using  the specified format. 4?Print a document to the requested format, which must be one of   ,  ,  , or . 5Like 4, but also takes a  data  structure. Like 6', but also takes a stub error message. 6BPrint a circuit generating function to the specified format; this  requires a shape parameter. 75Print a circuit generating function to the specified  format. Unlike 6, this can be applied to a 2 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 A read. In more readable form, it has all of the following types:  - print_generic :: Format -> Circ qa -> IO () I 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. 8Like 7&, but only works at simple types, and ) therefore requires no shape parameters.    345678   !"#$%&'(9:;<=>?@ABCDEF)GH*I+KLM,-.NOPRSTUVWXYZ[\]^_`abcdefghijklmnopqrs/uvwxy0z{|}~123456785      !"#$%&'()*+,-./0123456785)+*1/0      !"#$%&'(,-.2345678s   345678   !"#$%&'(9:;<=>?@ABCDEF)GH*I+KLM,-.NOPRSTUVWXYZ[\]^_`abcdefghijklmnopqrs/uvwxy0z{|}~12345678NoneMDESTUV\]^_`abcdefghijklmnopqrstuvwxyz{|}~DESTUVNone None9The B' function produces (and also requires) - functions with somewhat unwieldy types. The 9 B class defines generic functions for unpacking these types into a 1 more useable format, and for packing them back.  For example,  (qa ->  (qb ->  qd)) unpacks into  the type  qa -> qb ->  qd.  Note that ; and : do not in general form an E isomorphism, just a retraction of the packed type onto the unpacked  type. <BA custom-design boolean type, not modified by circuit generation. ?!Type-cast from BoolParam to Bool @Lifted version of PFalse. ALifted version of PTrue. B>Input the syntax tree of a classical function, and output the ; syntax tree of a corresponding quantum function. The type ' is  mapped to  ; the type < 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 B knows ( about many built-in operations such as  and , whose ) circuit translations are defined below. CLifted version of ?:   newBool :: BoolParam -> Bool. ;Depending on the boolean parameter, the circuit is either   0 |-- or  1 |-- DLifted version of :   False :: Bool. The circuit is * 0 |-- output: quantum bit in state |0> ELifted version of m:   True :: Bool. The circuit is * 1 |-- output: quantum bit in state |1> FLifted version of :   not :: Bool -> Bool. The circuit is  a -----x--  |  1 |--N------- output: not a. GLifted version of :   (&&) :: Bool -> Bool -> Bool. The circuit is  a -----x---  |  b -----x---  | " 0 |--N------- output: a and b. HLifted version of :   (||) :: Bool -> Bool -> Bool. The circuit is  a -----o---  |  b -----o---  | ! 1 |--N------- output: a or b. ILifted version of bool_xor:  # bool_xor :: Bool -> Bool -> Bool. The circuit is  a -----x-------  |  b -----|---x---  | | % 0 |--N---N------ output: a xor b. JLifted version of the  if-then-else construction:  . if-then-else :: Bool -> b -> b -> b 'We only allow first-order terms in the "then" and "else"  clauses. The circuit is:  q -----x---o---  | |  a -----x---|---  | |  b -----|---x---  | | 3 0 |--N---N-------- wire output of the function. KLifted version of the  operator:  (==) :: Eq a => a -> a -> Bool 9:;<=>?@ABCDEFGHIJK9:;<=>?@ABCDEFGHIJK<>=?@ABCDEFGHIJK9:;9:;<>=?@ABCDEFGHIJKNone MNOQRXY    !#$%+-./34567:DYZ[defghovw      !"#$%&'(2456789:;<=>?@ABCDEFGHIJKO    !#$%-./5QRXYYZ[+D3467         !"#$%&'(267845:NMehgfodwv !"#$%&'()*+,-./0123456789:;<=>?@ABCDDEEFFGHIJKLMNOPQRSTUVWXYZ[\]]^^_`abcdefgghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZZ[\]^_`abcdefghijklmnoppqqrstuvwxyz{|}~                                                                                                                            ! " # $ % & ' ( ) * + , - . / 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 [\]^_`ab\cdefghijklmno^b]pqrstuvwxyz{|}~fh      !"#$%&'()*+,-./0123456789:;<=>?@ABCDE>FG>FHI>JKLMNOPQRSTUVWXYZ[\]^_`abcdefghi jklmnopqrstuvwxyz{|}~5638:=     56556       !"#$%&'()*+,-./0123456789:;< = > ? @ A B C D E F5G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _56` a b c d e fghi j k l m n o p q r s t u v w x y z { | } ~             gh                                gh   K  L 5555           quipper-0.7QuipperQuipper.InternalQuipper.CircuitQuipper.TransformerQuipper.Control Quipper.MonadQuipper.Labels Quipper.QDataQuipper.GenericQuipper.QClassesQuipper.ClassicalQuipper.PrintingQuipper.CircLiftingLibraries.Template.ErrorMsgQLibraries.Template.LiftQLibraries.PortableSignalsLibraries.ShowAllLibraries.RandomSourceLibraries.Template.LiftingLibraries.TypeableLibraries.TupleLibraries.SamplingLibraries.AuxiliaryLibraries.Template.AuxiliaryLibraries.CommandLineLibraries.Template decToMonad expToMonadErrMsgIdentity intmap_zipintmap_zip_errmsg intmap_map intmap_mapMloop_with_indexloop_with_indexMlooploopMforendforforeach reflexivitysymmetry transitivityidentitytemplate_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_snd DBCircuit ReadWrite RW_SubroutineRW_ReadRW_Write RW_Return OBCircuitBCircuit NamespaceTypedSubroutineCircuitTypeStructureOCircuitCircuitExtArityGateComment SubroutineDTermCDiscardQDiscardQMeasCTermQTermCInitQInitQUnprepQPrepCSwapCGateInvCGateCNotGPhaseQRotQGate RepeatFlagBoxIdControllableFlagOnlyClassicalCtlAllCtlNoCtl NoControlFlag InverseFlagTimestepControlsSignedArityWiretypeCbitQbitWire 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_bcircuitDynamicTransformerDT transformerdefine_subroutinelifting_functionBT TransformerT_Gate T_Comment T_SubroutineT_DTerm T_CDiscard T_QDiscardT_QMeasT_CTermT_QTermT_CInitT_QInit T_QUnprepT_QPrepT_CSwap T_CGateInvT_CGateT_CNotT_GPhaseT_QRotT_QGateCtrlsBindings B_Endpoint Endpoint_BitEndpoint_Qubitwires_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 ControlSource to_control ControlList Inconsistent clist_empty clist_addcombinecombine_controlsadd_to_controls control_gatecontrol_gate_catch_allcontrollable_gatecontrollable_circuitBitlistQulistCtrlEndpointBitQubitCircput_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_subroutineqnothadamardgate_Hqmultinot_listcmultinot_listgate_Xgate_Ygate_Zgate_S 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_qulistcnotqnot_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 measure_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 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_emptymklabelcommentlabelcomment_with_labelLTypeBit_Leaf Qubit_LeafQCLeafQCDataPlus_Simple QCData_Simple QCDataPlusQShapeBDataCDataQDataHTypeBTypeCTypeQType SimpleTypefs_shapeQCData qcdata_mapM qcdata_zipqcdata_promoteQTypeBQCTypedummyqubitbitbool 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_shapeQCurryqcurryquncurryqinitqtermqdiscardcinitctermcdiscardqc_initqc_init_with_shapeqc_term qc_discardmeasureprepare qc_measure qc_prepareglobal_phase_anchored map_hadamardmap_hadamard_atswapswap_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_falseqshapeqc_bind qc_unbind.&&..==../=.encapsulate_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_fun with_computedwith_basis_changeprovide_subroutine_genericboxnbox box_loopMloopM_boxed_ifwith_classical_controlinline_subroutineQOrdq_less q_greaterq_leqq_geqq_maxq_minQEq q_is_equalq_is_not_equalq_ltq_gtq_leq_gecgate_to_cnot_transformertranslate_cgateclassical_to_cnottrivial_endpoint classical_to_quantum_transformerclassical_to_quantum_unaryclassical_to_quantumclassical_to_reversibleFormat CustomStyle GateCountPreviewASCIIPSPDFEPS FormatStyle renderformatbackgroundcolorforegroundcolor linewidthcoffs dotradius oplusradiusxoffgatepad gateheight crossradius stringbasebarwidth barheightdwidthdheightmaxgatelabelwidth maxlabelwidthmaxnumberwidthgatefont commentfont commentcolor labelfont labelcolor numberfont numbercolorsubroutineshapeascii_of_bcircuitgetBitprint_dbcircuit_asciipdfepspsrender_dbcircuitpreview_bcircuitprint_gatecounts_bcircuit format_enumprint_dbcircuitprint_of_documentprint_of_document_custom print_unary print_generic print_simpleCircLiftingUnpackunpackpack BoolParamPFalsePTruenewBooltemplate_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_ErrMsgQerrorMsgembedQtemplate-haskellLanguage.Haskell.TH.SyntaxQextractQ$fFunctorErrMsgQ$fApplicativeErrMsgQ$fMonadErrMsgQLiftQ LiftQState LiftStateboundVarprefix monadNameemptyLiftStategetStatesetState embedErrMsgQ addToBoundVarremoveFromBoundVar withBoundVar withBoundVars isBoundVar setPrefix getPrefix setMonadName getMonadNamemkNamenewNamesanitizeStringtemplateStringlookForTemplatemakeTemplateName prettyPrint clauseGetPatsequalNEListEltsclausesLengthPats$fFunctorLiftQ$fApplicativeLiftQ $fMonadLiftQHandler OSHandler CatchOnceCatchIgnoreDefaultSignalClose InterruptinstallHandler with_handlerossignal unix-2.6.0.1System.Posix.Signals oshandlerinstallHandler_posix$fShows $fShow(->) RandomSourcerandom-1.0.1.1 System.Random RandomGen$fShowRandomSourceBindSExpMAppEbaseGHC.Base>>=ReturnEreturnListECaseELetECondETupELamEAppELitEConEVarEDecMatchPatConPListPWildPTupPVarPLitPLit RationalLIntegerLCharLBodydoE getVarNames substMatchsubstDecsubstExp mapSubstExp litTHtoExpAST litTHtoPatASTnormalizePatInExp whereToLet clauseToMatchclausesToLambda expTHtoAST matchTHtoAST bodyTHtoAST patTHtoASTfirstLevelDecTHtoAST decTHtoAST typReturnEtypMAppE litASTtoTH patASTtoTH matchASTtoTH decASTtoTH expASTtoTH liftIntegerL liftRationalL liftLitAST liftPatAST liftMatchAST liftDecASTliftFirstLevelDecAST liftExpASTmakeDecTemplateprettyPrintASTprettyPrintLiftExpTHprettyPrintLiftExpASTValD$fTypeable(,,,,,,,,,)$fTypeable(,,,,,,,,)$fTypeable(,,,,,,,)Tuple TupleOrUnary weak_tuple weak_untupletupleuntuple$fTuple(,,,,,,,,,)(,)$fTuple(,,,,,,,,)(,)$fTuple(,,,,,,,)(,)$fTuple(,,,,,,)(,)$fTuple(,,,,,)(,)$fTuple(,,,,)(,)$fTuple(,,,)(,)$fTuple(,,)(,) $fTuple(,)(,) $fTuple()()$fTupleOrUnary(,,,,,,,,,)(,)$fTupleOrUnary(,,,,,,,,)(,)$fTupleOrUnary(,,,,,,,)(,)$fTupleOrUnary(,,,,,,)(,)$fTupleOrUnary(,,,,,)(,)$fTupleOrUnary(,,,,)(,)$fTupleOrUnary(,,,)(,)$fTupleOrUnary(,,)(,)$fTupleOrUnary(,)(,)$fTupleOrUnarya(,)$fTupleOrUnary()()ZerozeroIntervalinterval sample_all sample_step sample_random sample_all0 sample_step0sample_random0 list_stepsafe_zipGHC.Listzip $fRandom[]$fRandom(,,,,,,)$fRandom(,,,,,)$fRandom(,,,,) $fRandom(,,,) $fRandom(,,) $fRandom(,) $fRandom()$fZero[]$fZero(,,,,,,) $fZero(,,,,,) $fZero(,,,,) $fZero(,,,) $fZero(,,) $fZero(,)$fZero() $fZeroBool $fZeroDouble $fZeroInteger $fZeroInt $fInterval[]$fInterval(,,,,,,)$fInterval(,,,,,)$fInterval(,,,,)$fInterval(,,,)$fInterval(,,) $fInterval(,) $fInterval()$fIntervalBool$fIntervalDouble$fIntervalInteger $fIntervalIntRandomCurrymcurrymuncurry IsomorphismMonadghc-prim GHC.TypesBoolIdStrbufBList+++BoollistXIntMapcontainers-0.5.0.0Data.IntMap.BaseIntMapapplyAt overwriteAthas_duplicates substituteintset_insertsData.IntSet.BaseIntSetinsert map_provide Data.Map.BaseMapintmap_ziprightxintmap_deletexintmap_deletesxintmap_insertxintmap_insertsxintmap_lookup Data.MaybeNothingxintmap_member xintmap_emptyxintmap_freshkeyxintmap_freshkeysxintmap_to_intmap xintmap_sizexintmap_touched xintmap_dirtyxintmap_reservexintmap_reservesxintmap_unreservexintmap_unreservesxintmap_makecleansequence_right Control.Monadsequencesequence_right_ zip_strictzip_strict_errmsgzip_rightstrictzip_rightstrict_errmsgzipWith_strictzipWithzipWith_rightstrictzipRightWithRightStrictMzipRightWithRightStrictM_foldRightPairMfoldRightPairM_fold_right_zipfold_right_zipMmmap monad_join1 map_either map_eitherMmap_pair map_pairM int_ceilingGHC.Realceiling integer-gmpGHC.Integer.TypeIntegerboollist_of_int_bhboollist_of_int_lhint_of_boollist_unsigned_bhint_of_boollist_signed_bhbool_xor boollist_xorstring_of_listoptionalTrue blist_of_list list_of_blist blist_empty blist_concatstrbuf_of_stringstring_of_strbuf strbuf_empty strbuf_concatid iso_forwards iso_backwardsgetIdgetBList$fCurry(->)(,)res $fCurryb()b$fShowIdentity $fFunctorId$fApplicativeId $fMonadId $fShowBList $fShowXIntMapinitlastzip3foldlreverse$GHC.ErrerrorString Data.Tuplesndoptfail parse_intparse_list_int parse_doubleDouble match_enum show_enum GHC.ClassesOrdFalse$fFunctorReadWrite$fApplicativeReadWrite$fMonadReadWrite$fShowRepeatFlag Data.EitherEither $fShowT_Gate$fControlSource(,,,,,,)$fControlSource(,,,,,)$fControlSource(,,,,)$fControlSource(,,,)$fControlSource(,,)$fControlSource(,)$fControlSource()$fControlSource[]$fControlSourceControlList$fControlSourceSigned$fControlSourceInt$fControlSourceBoolState NoCommentFlag empty_state initial_state get_state set_stateput_gate apply_gatedo_readrun_circ get_arityarity set_arity namespace get_clistclist set_clist get_ncflagncflag set_ncflagget_nocommentflag nocommentflagset_nocommentflagwiretype_of_endpointrepeat&identity_dynamic_transformer_with_lift%identity_dynamic_transformer_constantBitWire QubitWiregetCirc$fControlSourceBit$fControlSourceQubit$fControlSourceSigned0$fControlSourceB_Endpoint$fControlSourceSigned1 $fFunctorCirc$fApplicativeCirc $fMonadCirc$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[]$fFunctorLabelMonad$fApplicativeLabelMonad$fMonadLabelMonadGHC.Showshow undefinedShow$fShowBit_Leaf$fShowQubit_Leaf $fQCLeafBit $fQCLeafQubit$fQCDataPlus_Simpleqc$fQCData_Simpleqc$fQCDataPlusqc$fQShapebaqaca $fBDataba $fCDataca $fQDataqa$fSimpleType(,,,,,,,,,)$fSimpleType(,,,,,,,,)$fSimpleType(,,,,,,,)$fSimpleType(,,,,,,)$fSimpleType(,,,,,)$fSimpleType(,,,,)$fSimpleType(,,,)$fSimpleType(,,)$fSimpleType(,)$fSimpleType()$fSimpleTypeBit$fSimpleTypeQubit $fQCDataChar $fQCDataFloat$fQCDataDouble $fQCDataInt$fQCDataInteger$fQCDataSigned$fQCDataB_Endpoint $fQCData[]$fQCData(,,,,,,,,,)$fQCData(,,,,,,,,)$fQCData(,,,,,,,)$fQCData(,,,,,,)$fQCData(,,,,,)$fQCData(,,,,) $fQCData(,,,) $fQCData(,,) $fQCData(,) $fQCData() $fQCDataBit $fQCDataQubit circuit_type_structure_of_qcdata qc_controlqc_allocreverse_errmsg reverse_unarytransform_errmsg box_internal$fQCurry(->)(,)res$fQCurryCirc()b $fNumBoolEq$fQEqqc AnnGatecount Gatecount AnnGatetypeGatetype ControlTypeXarity 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_subroutinepromptrun_readwrite_asciiIOwhiteblack defaultStyle ps_escapestring_of_boxidassign_x_coordinateseasyrender-0.1.1.1Graphics.EasyRender.InternalX 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_bcircuitDocumentprint_bcircuit_formatprint_dbcircuit_formatsystem_pdf_viewerpreview_documentpreview_document_custompreview_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_subroutineprint_gatecounts_dbcircuitCustom print_errmsgAnnGatetypeSubroutineGatetypeSubroutine WireTypeMap&&||not==$fCircLiftingUnpackCircCirc$fCircLiftingUnpackCircCirc0$fCircLiftingUnpackCircCirc1$fCircLiftingUnpackCircCirc2$fCircLiftingUnpackCircCirc3$fCircLiftingUnpackCircCirc4$fCircLiftingUnpackCircCirc5$fCircLiftingUnpackCircCirc6$fCircLiftingUnpackCircCirc7$fCircLiftingUnpackCirc(->)