It's - pure and simple - a plot point. Hamlet has been sent by Claudius to England, and, with exceptional brevity, Shakespeare has Horatio read out a letter from Hamlet.
Thematically, I don't really think it has a huge "function", other than to return Hamlet to Denmark ready for Ophelia's funeral, the duel, and all the deaths at the end of the play: note too the way the play "cuts" forward - in the letter, Horatio is told to deliver several letters to Claudius and to come immediately to Hamlet's side, and the next time we see the two of them, they are reunited.
The function of the scene to provide some way to get Hamlet back to Denmark so he can resolve his problem with Claudius.It also allows Hamlet to return privately so that he can view the funeral of Ophelia. Many critics have remarked that the scenario of being captured by pirates and returned to Denmark is improbable but they add that it does remind the audience of Hamlet's repeated reference to fate and the role it plays in life.