Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an append operator for ByteString?

For String there is ++, which has type

> :t (++)
(++) :: [a] -> [a] -> [a]

Evidently it doesn't work on ByteString because it isn't a list. I see the append function but is there an operator for it?

like image 597
Matt Joiner Avatar asked Feb 21 '18 09:02

Matt Joiner


People also ask

Can you concatenate bytes in Python?

Concatenating many byte strings In case you have a longer sequence of byte strings that you need to concatenate, the good old join() will work in both, Python 2.7 and 3. x. In Python 3, the 'b' separator string prefix is crucial (join a sequence of strings of type bytes with a separator of type bytes).

How do you add a string to a byte?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.

How do you combine two bytes in Python?

To join a list of Bytes, call the Byte. join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError , so make sure to call it on a Byte object b' '. join(...)

What is a byte string Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable.


2 Answers

ByteString has a Semigroup instance, so it can be combined in the usual way that semigroups are combined, with (<>).

The same operator works for strings as well, because String ~ [Char], and [a] has a Semigroup instance where (<>) = (++).

Prelude Data.ByteString.Char8> unpack $ pack "abc" <> pack "def"
"abcdef"

Here I convert two Strings to ByteStrings, combine them as ByteStrings, and then convert back to String to demonstrate that it's worked.

like image 104
amalloy Avatar answered Nov 11 '22 16:11

amalloy


concat :: [ByteString] -> ByteString

O(n) Concatenate a list of ByteStrings.

like image 22
Mikhail Baynov Avatar answered Nov 11 '22 17:11

Mikhail Baynov