Seq.unfold and creating bit masks

In the course of working on ParsecClone I needed some code that could take in an arbitrary byte array and convert it to a corresponding bit array. The idea is if I have an array of

[|byte 0xFF;byte 0x01|]

Then I should get

[|1;1;1;1;1;1;1;0;0;0;0;0;0;0;1|]

I’ve done plenty of bit slingin’ in my day, and the trick is just to apply a sequence of bit masks to each byte and collect all the bit arrays. In other languages this is always a little bit of a pain, but in F# the solution was amazingly elegant

While a fold takes a list and a seed and returns a single accumulated item, an unfold takes a seed and generates a list. For those not familiar, unfold takes a function of the signature

(State -> ('a * State) option) -> State -> Seq<'a>

Unfold takes a function with an argument that is the state, and returns an item * state option tuple. The first element of the option is the element to be emitted in the sequence. The second item is the next state. If you return None instead of Some the infinite sequence will end. You can see that my state is the exponent n of 2^n which gives you the bit mask. The first iteration is 2^0, then 2^1, then 2^2, etc. By reversing it, I now have a bitmask that look like this: