0

How can I abstract away the methods on Int32 and Int64 types?

Specifically, how can I refactor these similar functions into a core function?

let private tryParseInt64 (text:string) =

    let mutable (number:Int64) = 0L

    if Int64.TryParse(text, ref number)
    then Some number
    else None

let private tryParseInt32 (text:string) =

    let mutable (number:Int32) = 0

    if Int32.TryParse(text, ref number)
    then Some number
    else None
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • 2
    What do you want to achieve? The methods return different types, so you would have to make your "core function" generic; however, you can't restrict a generic type parameter to "number", so that would still be less than optimal. – TeaDrivenDev Oct 04 '18 at 19:48
  • 3
    If you want it to be truly generic, then the SRTPs in the linked duplicate are the only way. If you just want to factor out the identical logic, you could have the actual parser function be your first parameter, and then use this logic in one place to call whatever parser is passed to you. You can then partially apply different parsing methods to create bespoke parsers for different types without duplicating the code. – Aaron M. Eshbach Oct 04 '18 at 20:49
  • As mentioned by the previous commenters, you can either build a generic scaffolding function that takes the particular parser function as a parameter, then apply it partially to build your final parsers, or use statically resolved type parameters to build a single inline function, but you may need to specify types to help the compiler out. Please see https://repl.it/repls/ImprobableJudiciousDegrees for an example I created. – dumetrulo Oct 05 '18 at 10:08

0 Answers0