I'm implementing a simple conversion string to integer convertor in F#; the logic is, e.g from string to uint32:
let inline sToUint s =
let mutable v = 0u
for c in s do
v <- v * 10u + uint32 c - uint32 '0'
v
Now I would like to use this implementation for other integer types, e.g. uint64. How can I implement a single generic function to do that?
Thank for all, SRTP (as used in the answers) is what I need for such a situation. The following implementation is just slightly changed from the answer of @Brian Berns
// (char -> ^a) -> (string -> ^b)
let inline sToNum f =
let tenTimes v = (v <<< 3) + (v <<< 1)
fun (s: string) ->
let mutable v = Unchecked.defaultof<_>
for c in s do
v <- (tenTimes v) + f c - f '0'
v