Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folding over [Word8] and ByteString with same function?

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?

like image 557
rityzmon Avatar asked Dec 05 '22 00:12

rityzmon


2 Answers

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

It has instances for both ByteString and [a].

like image 141
ErikR Avatar answered Dec 06 '22 12:12

ErikR


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?

like image 32
hao Avatar answered Dec 06 '22 13:12

hao