Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to take a substring of a ByteString

I need to make extensive use of:

slice :: Int -> Int -> ByteString -> ByteString
slice start len = take len . drop start

Two part question:

  1. Does this already have a name? I can't find anything searching for that type on Hoogle, but it seems like it should be a really common need. I also tried searching for (Int, Int) -> ByteString -> ByteString and some flip'd versions of same. I also tried looking for [a] versions to see if there was a name in common use.
  2. Is there a better way to write it?

I'm suspicious that I'm doing something wrong because I strongly expected to find lots of people having gone down the same road, but my google-fu isn't finding anything.

like image 807
Doug McClean Avatar asked May 31 '13 03:05

Doug McClean


Video Answer


1 Answers

The idiomatic way is via take and drop, which has O(1) complexity on strict bytestrings.

slice is not provided, to discourage the reliance on unsafe indexing operations.

like image 50
Don Stewart Avatar answered Nov 11 '22 14:11

Don Stewart