# Qiskit: How to implement a classical function?

I'm quite lost, I have to implement the following function with qiskit $$f(x,y,z) = (\lnot x \land y \land z) \lor (x \land \lnot y \land z)$$ but how can we do that ? I don't understand how to do the mapping between classical gates (OR, AND, XOR...) and quantum gates (CNOT, H, X...)

Can someone help me ?

The easiest way to do this is to use the classical function compiler to build a boolean function and synthesize a quantum circuit object from that function. For example, using your boolean logic function there you could do:

from qiskit.circuit import classical_function, Int1

@classical_function
def my_function(x: Int1, y: Int1, z: Int1) -> Int1:
return (not x and y and z) or (x and not y and z)

which will define your boolean function. Then you can synthesize a circuit from it with:

qc = my_function.synth()

if you draw qc you'll get:

print(qc)

q_0: ──■───────
│
q_1: ──┼────■──
│    │
q_2: ──■────■──
┌─┴─┐┌─┴─┐
q_3: ┤ X ├┤ X ├
└───┘└───┘

If you want to see what that looks like as just 1 and 2 qubit gates (instead of toffolis) you can decompose it and draw it which will yield:

print(qc.decompose())
┌───┐
q_0: ───────────────────■─────────────────────■────■───┤ T ├───■──────────────────────────────────────────────────────────
│                     │    │   └───┘   │                                               ┌───┐
q_1: ───────────────────┼─────────────────────┼────┼───────────┼────────────────■─────────────────────■────■───┤ T ├───■──
│             ┌───┐   │  ┌─┴─┐┌─────┐┌─┴─┐              │             ┌───┐   │  ┌─┴─┐┌┴───┴┐┌─┴─┐
q_2: ───────■───────────┼─────────■───┤ T ├───┼──┤ X ├┤ Tdg ├┤ X ├──■───────────┼─────────■───┤ T ├───┼──┤ X ├┤ Tdg ├┤ X ├
┌───┐┌─┴─┐┌─────┐┌─┴─┐┌───┐┌─┴─┐┌┴───┴┐┌─┴─┐├───┤└┬───┬┘├───┤┌─┴─┐┌─────┐┌─┴─┐┌───┐┌─┴─┐┌┴───┴┐┌─┴─┐├───┤└┬───┬┘└───┘
q_3: ┤ H ├┤ X ├┤ Tdg ├┤ X ├┤ T ├┤ X ├┤ Tdg ├┤ X ├┤ T ├─┤ H ├─┤ H ├┤ X ├┤ Tdg ├┤ X ├┤ T ├┤ X ├┤ Tdg ├┤ X ├┤ T ├─┤ H ├──────
└───┘└───┘└─────┘└───┘└───┘└───┘└─────┘└───┘└───┘ └───┘ └───┘└───┘└─────┘└───┘└───┘└───┘└─────┘└───┘└───┘ └───┘

• Ahh, that's nice. Does Qiskit's code just convert the classical circuit to compute that function into a reversible one? May 20, 2022 at 20:14
• I assume that the output is always stored in the bottom-most qubit? (In this case q_3)? If you look at this page qiskit.org/documentation/apidoc/classicalfunction.html, the sentence "The resulting..." is cut off. Mar 13, 2023 at 15:23