All of you probably know that F# has a set of predefined numerical literals that allow you to clarify meaning of numbers. For example, number 32 will be interpreted as int by default. If you add ‘L’ suffix – 32L, you will get int64 number. If you add ‘I’ suffix- 32I, you will get System.Numerics.BigInteger number.
But F# has an extensible point here: you can define custom interpretation for suffixes Q, R, Z, I, N, G. The trick is that you need to declare an F# module with a special name and define converters functions. (For example NumericLiteralZ for Z literal).
module NumericLiteralZ = let FromZero() = 0 let FromOne() = 1 let FromInt32 n = let rec sumDigits n acc = if (n=0) then acc else sumDigits (n/10) (acc+n%10) sumDigits n 0 //let FromInt64 n = ... //let FromString s = ... let x = 11111Z //val x : int = 5 let y = 123Z //val y : int = 6
Have fun, but be careful.
Update: Note that you cannot use constants integer literals with suffixes Q, R, Z, I, N, G in pattern matching.
One thought on “F# Kung Fu #2: Custom Numeric Literals.”