There are occurrences where a mandate of the Torah seems to be contradicted by the apparent moral lesson of a story within the Torah. One such example is the matter of our reaction to those who have harmed us.
The Torah writes explicitly: "Do not take revenge or harbor ill feeling" (Vayikra 19:18). This certainly seems to preclude our ability to punish the wicked in response to the harm they cause us. On the other hand, a basic moral principle is to emulate Hashem, and the Torah calls Him a "G-d who is jealous and takes revenge" (Shemot 20:4). So, if revenge is apparently a positive trait, why are we forbidden to use it? Furthermore, when the Torah talks about payment for damages that one causes another person, it says: "As he did, so shall it be done to him" (Vayikra 24:19). Although we interpret this rule to be referring to financial payment, that appears to only be the manner in which the reaction is taken, but conceptually there is an element of retribution.
The key to answering this vexing question may be held in the hands of the Ramban and Seforno on our parasha’s last pasuk. Bnei Yisrael stoned the blasphemer [who was a partial foreigner who fought with a Jew and then cursed Hashem] "as Hashem commanded Moshe." Both commentators stress that they acted without feelings of revenge and hatred but because that is what Hashem asked them to do. There is, thus, a difference between punishment for the sake of Divinely ordained punishment and punishment for the sake of revenge. We do not do to the perpetrator to make it up to the victim but we take the steps that the perpetrator deserves for the injustice he was involved in. The truth is that the guilty should actually be interested in paying the price in order to deserve atonement, even though it is beit din’s job to implement the matter. With such an outlook, there is no room for mercy on the criminal, as the steps ‘against him’ are actually for his benefit.
When carrying out the punishment of the blasphemer, why was it wrong to include the people’s personal feelings if it did not alter the punishment? The answer is that then it would not have been a direct and complete fulfillment of the will of Hashem and as such it would have ruined the purity of the action of punishment. Only for Hashem, who is bereft of any ulterior feelings, is it permitted to act with what we would call vengeance. It is very different for human beings who, even when they are ostensibly acting in the name of Heaven, are actually also looking for an excuse to get back at somebody for past animosity. Therefore, we have to be careful to remove all feelings of revenge from our thought process and act as Hashem tells us through the Torah.