1

How can I get nth byte of ByteString in Haskell?

I tried to find function like !! for ByteStrings, but found nothing.

Malyutin Egor
  • 127
  • 1
  • 10

1 Answers1

6

ByteString.index is the function you're looking for.

Most of the "containerish" types emulate the extended list interface; you also want to be careful because that index function will crash the program if you feed it a string that's too short (as will !! on ordinary lists). A better implementation might be

import Data.ByteString as B
nthByte :: Int -> B.ByteString -> Maybe Word8
nthByte n bs = fst <$> B.uncons (B.drop n bs)

which, reading inside out, drops the first n bytes (maybe producing an empty byte string), then attempts to split the first character from the remainder, and if successful, ignores the rest of the string.

David Maze
  • 130,717
  • 29
  • 175
  • 215