Shakespeare wrote the play "Hamlet" in 1601, in 1556 Shakespeare's only son died of an unknown illness. The death of his son was believed to be the reason of "Hamlet".
What was the purpose of Shakespeare writing Hamlet?
Hamlet's purpose, ostensibly, is to exact vengeance for the murder of his father. That, of course, is the short answer to your question. The long answer is that in looking for a clear-cut purpose either on the part of Hamlet, the other characters, or Shakespeare himself, we are perhaps somewhat missing the point.
Where did Shakespeare get the idea for Hamlet?
The story of Shakespeare's Hamlet was derived from the legend of Amleth, preserved by 13th-century chronicler Saxo Grammaticus in his Gesta Danorum, as subsequently retold by the 16th-century scholar François de Belleforest.