haskell / bytestring

An efficient compact, immutable byte string type (both strict and lazy) suitable for binary or 8-bit character data.
http://hackage.haskell.org/package/bytestring
Other
291 stars 141 forks source link

Pattern synonym for empty bytestring #399

Open andrewthad opened 3 years ago

andrewthad commented 3 years ago

It would occasionally be useful have a pattern synonym for the empty bytestring:

pattern Empty :: ByteString
pattern Empty <- (ByteString.null -> True)
  where
  Empty = ByteString.empty

This makes it possible to rewrite guards like:

| Just (a',extra) <- BC8.readInt a, BC8.null extra, a' >= 0 -> ...

to

| Just (a',Empty) <- BC8.readInt a, a' >= 0 -> ...

The second form is more clear, and it avoids leaving the extra binding in scope for an entire clause that doesn't need it. I've already written this synonym in a project at work, and it works well. What are the maintainers thoughts on including this in bytestring itself.

Bodigrim commented 3 years ago

I'm a bit worried about an overlap with Data.ByteString.Lazy.Empty.

sjakobi commented 3 years ago

@andrewthad, have you considered simply using "" with OverloadedStrings or [] with OverloadedLists?

I'm not very opposed to adding an Empty pattern synonym though – if we add it, I suspect we'll eventually get requests for pattern synonyms for non-empty bytestrings.

Regarding the Empty constructor for lazy bytestrings: we could probably rename it – it's exposed only via Internal modules.

Bodigrim commented 2 years ago

I'm weakly against it, mostly because there is no prior art in other containers. I'm also unconvinced by the motivating example. Instead of

| Just (a',extra) <- BC8.readInt a, BC8.null extra, a' >= 0 -> ...

you can write

| Just (a', BC8.null -> True) <- BC8.readInt a, a' >= 0 -> ...

which is no worse than

| Just (a',Empty) <- BC8.readInt a, a' >= 0 -> ...