4

It turns out that there is no instance of Foldable available for ByteString. I'd like to write a function that uses foldl' on either [Word8] or ByteString but I can't. Since a ByteString is, data-wise, the same as [Word8], it seems that I should be able to.

Is there a package available that integrates the two or must I roll my own with a type class?

rityzmon
  • 1,945
  • 16
  • 26

2 Answers2

9

Have a look at the MonoFoldable class defined in mono-traversable package.

It has instances for both ByteString and [a].

ErikR
  • 51,541
  • 9
  • 73
  • 124
7

ErikR's answer is great. I just want to insert a sidenote. If you have lens you have the bytes traversal:

λ> import Data.ByteString.Lens
λ> import Control.Lens
λ> :t foldrOf bytes
foldrOf bytes
  :: IsByteString s => (GHC.Word.Word8 -> r -> r) -> r -> s -> r

In a sense the question you are asking is the motivation for the lens package: can we extend the functions in Data.Foldable and Data.Traversable to consume not only regular instances of Foldable and Traversable but also objects that behave and compose like foldables and traversables?

hao
  • 10,138
  • 1
  • 35
  • 50