I'm trying to rekindle my knowledge of F#. For practice I built an implementation of calculating the FNV1a32 hash of a string in F#.
This is the code I came up with:
let XorWithHash b hash =
hash ^^^ b
let MultiplyByPrimeFactor hash =
let Prime = 16777619un
hash * Prime
let GetNthByteOfString (s:string) n =
if (n < Encoding.UTF8.GetByteCount(s)) then Some(unativeint (Encoding.UTF8.GetBytes(s).[n])) else None
let GetFNV1a32 s =
let rec transformString s n (acc:unativeint)=
let b = GetNthByteOfString s n
match b with
| Some b ->
XorWithHash b acc
|> MultiplyByPrimeFactor
|> transformString s (n+1)
| None -> acc
let OffsetBasis = 2166136261un
transformString s 0 OffsetBasis
let Main =
let answer = GetFNV1a32 "Test String"
answer
And it works correctly and I'm fine with that. My question is this: I think I could simplify the implementation of transformString if I could use a fold or some other sort of reduce but I can't quite seem to figure it out. Can anyone help me out with an implementation of transformString that uses a fold or reduce of some sort? Or is this as good as I'm likely to get?