문제

I'm new in F#.

How do I check whether a variable is an integer or another type.

Thanks.

도움이 되었습니까?

해결책

One way is listed by @ildjarn in the comments:

let isInt x = box x :? int

An idiomatic way would be to use pattern matching. First, define a discriminated union which defines the possible options:

type Test =
| IsAnInteger of int
| IsADouble of double
| NotANumber of Object

then use a match statement to determine which option you got. Note that when you initially create the value you wish to use with a match statement, you need to put it into the discriminated union type.

let GetValue x =
    match x with
    | IsAnInteger(a) -> a
    | IsADouble(b) -> (int)b
    | NotAnInteger(_) -> 0

Since you're probably going to use your test to determine control flow, you might as well do it idiomatically. This can also prevent you from missing cases since match statements give you warnings if you don't handle all possible cases.

>GetValue (NotAnInteger("test"));;
val it : int = 0

>GetValue (IsADouble(3.3))
val it : int = 3

>GetValue (IsAnInteger(5))
val it : int = 5

다른 팁

Considering that you tagged this question "c#-to-f#" I'm assuming you're coming to F# from a C# background. Therefore I think you may be a bit confused by the type inference since you're probably used to explicitly typing variables.

You can explicitly declare the type of a value if you need to.

let x:int = 3

But it's usually easier and better to let the type inference do this work for you. You'll note that I said value--the declaration above is not a variable because you cannot do a destructive assignment to it. If you want a variable then do this:

let mutable x:int = 3

You can then assign a new value to x via this construct

x <- 5

But, as a rule, you'll want to avoid mutable values.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top