Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#. Tuple or not

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
like image 799
user1067514 Avatar asked Nov 27 '11 02:11

user1067514


2 Answers

FSharpType.IsTuple[MSDN] does this.

let isTuple value = 
  match box value with
  | null -> false
  | _ -> FSharpType.IsTuple(value.GetType())
like image 156
Daniel Avatar answered Oct 19 '22 13:10

Daniel


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.

like image 28
hmakholm left over Monica Avatar answered Oct 19 '22 12:10

hmakholm left over Monica