I’ve just started learning F#.
I wonder how can I determine whether the argument of a function is a tuple?
let tuple = (1, 2)
let notTuple = 3
let isTuple t = // returns 'true' if t is a tuple, 'false' otherwise
printfn "%b" isTuple tuple // true
printfn "%b" isTuple notTuple // false
FSharpType.IsTuple
[MSDN] does this.
let isTuple value =
match box value with
| null -> false
| _ -> FSharpType.IsTuple(value.GetType())
There is probably, technically, a way to do this, since CLR supports run-time type checks. But you shouldn't want to do it. It goes against the polymorphism philosophy of the ML familiy -- if you need such a check it indicates that your algorithm and/or datastructure design is not well suited to the programming language. (The exception is if you need to interface with existing .net libraries that don't follow this philosophy).
More specifically, parametric polymorphism is based on the concept that whenever you have something that you don't already know what type it is, it is because you want to handle everything identically and not look inside the data to see what it is. Not following this rule amounts to working against the grain of the programming language, and will make your code harder to understand, because the types will not carry the usual information about how your functions treat data.
If you want to create some code that you can pass either a tuple or a single number, and have that code be aware of the difference, you should define an explicit variant type such that you can tell the possibilities apart using pattern matching, and it will be explicit in the types of the functions that they provide the caller with such a choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With