I have a String x which may or may not be gzip-compressed. Using the zlib library, I want to try decompressing x -- if it succeeds, the function shall return the compressed String. If not (i.e. x is not gzip-compressed) I want to simply return x.
As GZip.decompress generates an error if applied to a non-gzip string, I could use catch or similar, but I'm specifically asking for a solution that uses the zlib error handling mechanism.
How can I write a function, say decompressIfPossible :: ByteString -> ByteString that has the previously described characteristics? I'd prefer a Either String ByteString to represent either the error or the decompression result.
Note: This question intentionally does not show research effort, as it was immediately answered in a Q&A-style manner.