2 people like it.

Convert booleans to bits using fold

@Samuel - saw your post and thought one part was similar to bit shifting I was playing with yesterday, so rewrote the FromBooleans function using a fold instead of ref cells. Probably not as readable as your version though :)

1: 
2: 
3: 
4: 
5: 
6: 
let FromBooleans (bools:bool []) =
    let bit b = if b then 1uy else 0uy
    let folder (acc,lst,sh) item = if sh >= 8 then (bit(item),acc::lst,1) 
                                   else (acc ||| (bit(item)<<<sh),lst,sh+1)
    let (acc,lst,_) = bools |> Seq.fold folder (0uy,[],0)
    acc::lst |> Array.ofList |> Array.rev
val FromBooleans : bools:bool [] -> byte []

Full name: Script.FromBooleans
val bools : bool []
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
val bit : (bool -> byte)
val b : bool
val folder : (byte * byte list * int -> bool -> byte * byte list * int)
val acc : byte
val lst : byte list
val sh : int
val item : bool
module Seq

from Microsoft.FSharp.Collections
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State

Full name: Microsoft.FSharp.Collections.Seq.fold
module Array

from Microsoft.FSharp.Collections
val ofList : list:'T list -> 'T []

Full name: Microsoft.FSharp.Collections.Array.ofList
val rev : array:'T [] -> 'T []

Full name: Microsoft.FSharp.Collections.Array.rev
Raw view Test code New version

More information

Link:http://fssnip.net/nd
Posted:10 years ago
Author:Chris Ballard
Tags: bit shifting , fold