I am writing a very performance intense program and have been using C, but somebody told me how cool functional programming is, so I’ve decided to rewrite it in F#.
Anyway, the particular function I am having a hard replicating the algorithm in F# is Duff’s device. Instead of the typical iteration, it unwinds the loop so it can copy 8 bytes per iteration instead of just one.
void copy_memory( char* to, char* from, size_t count ) {
size_t n = (count+7)/8;
switch( count%8 ) {
case 0: do{ *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
}while(--n>0);
}
}
This takes advantage of case fallthrough and the ability to jump to the middle of a loop in C, which, as far as I can tell, are unfortunately features that F# seems to be missing.
I read some stuff on MSDN, and figured that F#’s match feature would be the closest I could get to C’s switch. So, I started to write this bit of code
open System.Reflection
let copyMemory (pTo : Pointer) (pFrom : Pointer) length =
let n = (length + 7) / 8
match n % 8 with
| 0 ->
and then I couldn’t figure out what to do. It wouldn’t let me start a loop here and end it in another case.
Is there something in F# that I can use to do case fall-through and jump into the middle of a loop? If you can do that for me, I think I can figure out the rest myself.
Here’s the idiomatic way to fiddle memory in F# 🙂
But this is probably more in the spirit of Duff’s
But seriously