There are two particular reasons why Shakespeare might have chosen to include this darkly humorous scene in Hamlet. First, Hamlet, by and large, is a dark and violent play with little in the way of humor (especially in the first three and final acts). Shakespeare might've included the scene in order to provide some humor and levity for his audience in order to liven their spirits and retain their attention. In essence, this scene provides some measure of "comic relief" for the audience. Shakespeare's second reason for including this scene might have been to make a particular point in connection to one of the play's main themes: human mortality. In this scene, Hamlet comes to realize that death, ultimately, serves as something of a level playing field. No matter who - or how insignificant or powerful - a person is in their life, he or she will die and return to the dust from which he or she came.