A method for implementing adjoint calculations in the discrete case