I need a little utility function that generates a checksum from an array of 8 bytes.
Now, this itself is trivial, except that I can’t use byte Checksum(byte[8] input) in C# as a method declaration – I can’t specify size of array, so I have to use byte[] which can be any size, and in the method body I then need to check that input is not null and length == 8.
I’m just wondering if F# can do that? I heard that F# has a lot more options to limit acceptable parameters to a function (e.g., Discriminated Unions)?
Granted, in this trivial example F# would be overkill, but I’m curious.
Neither of the two languages can specify that a function takes an array of specific length. The problem with this is that checking whether the caller actually provides array with that length is quite difficult. It can be checked when the array is created directly by
new byte[8], but all other cases require some tricky techniques.This is partly done by Code Contracts, which is a tool for additional checking that can be installed into Visual Studio and used with both C# and F#. It allows you to write something like:
Code Contracts come with a tool that gives you a warning at compile-time when you call
CheckSumwith a wrongly sized array. It can also generate runtime check (when it cannot statically determine that the call is correct).