How to create a function that accepts only int32 or int64

How to define a function in F # fthat takes only an argument xthat is type-limited int32or int64?

+4
source share
2 answers

Here you can limit it at compile time. First create a generic version of your function:

let inline twice x = x + x

Then restrict it to the required types using overload resolution and static element constraints:

type T = T with
    static member ($) (T, x:int  ) = twice x
    static member ($) (T, x:int64) = twice x

let inline restrictedTwice x = T $ x

Tests:

restrictedTwice 4  //val it : int = 8

restrictedTwice 5L //val it : int64 = 10L

restrictedTwice 5u // doesn't compile
+7
source

Overload

If you can live with defining a function as a class method, you can use the usual .NET method overload:

type Foo =
    static member Bar (x : int)   = sprintf "32-bit integer: %i" x
    static member Bar (x : int64) = sprintf "64-bit integer: %i" x

FSI Examples:

> Foo.Bar 42;;
val it : string = "32-bit integer: 42"
> Foo.Bar 42L;;
val it : string = "64-bit integer: 42"

Discriminative Unions

, . , int, int64:

type DUInt =
| NormalInt of int
| BiggerInt of int64

, , Int32 int64, , System .

, :

let foo = function
    | NormalInt x -> sprintf "32-bit integer: %i" x
    | BiggerInt x -> sprintf "64-bit integer: %i" x

DUInt -> string.

FSI:

> foo (NormalInt 42);;
val it : string = "32-bit integer: 42"
> foo (BiggerInt 42L);;
val it : string = "64-bit integer: 42"
+4

Source: https://habr.com/ru/post/1628081/


All Articles