f# - Function working for all numerical data types -


i've written simple function reverses given number:

let reversenumber x =     let rec innerfunc acc elem =         if elem = 0             acc             else                  let rem = elem % 10                 innerfunc (10 * acc + rem) (elem / 10)      innerfunc 0 x 

the problem works ints. e.g. int64 need create version uses 0l , 10l instead of 0 , 10 respectively.

i've heard it's possible write more generic functions using inline keyword , languageprimitives, latter doesn't contain neither reminder operation nor 'genericten' (although might obtained 'genericone + genericone + ... ).

could ?

ignoring completeness of @kvb's linked answers, minimal work make generic:

module numericliteralg =     let inline fromzero () = languageprimitives.genericzero     let inline fromone () = languageprimitives.genericone  let inline reversenumber (x:^a) =     let ten:^a = 1g + 1g + 1g + 1g + 1g + 1g + 1g + 1g + 1g + 1g     let rec innerfunc (acc:^a) (elem:^a) =         if elem = 0g acc         else             let (rem:^a) = elem % ten             innerfunc (ten * acc + rem) (elem / ten)     innerfunc 0g x 

the type annotations not strictly necessary, , present reduce type constraints listed in intellisense; code work identically without them.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -