Reputation: 2920
I would like to pass a type name (such as int
, or string
, or even the name of a user-defined type) as a function parameter. Currently I am doing the following:
type IntegerOrIntegerList =
| Integer of int
| IntegerList of int list
let f (n : int) (d : 'T) : IntegerOrIntegerList =
match (box d) with
| :? int as i -> Integer(n)
| _ -> IntegerList([0 .. n])
But the presence of d
above is adventitious. What would be the idiomatic F# way to express the above logic?
Thanks in advance for your help.
Upvotes: 3
Views: 2724
Reputation: 47914
You could use a type arg:
let f<'T> (n : int) =
if typeof<'T> = typeof<int> then Integer(n)
else IntegerList([0 .. n])
Upvotes: 9