2013-01-08 50 views
2

我想通過一個類型名稱(如intstring,或者甚至是用戶定義類型的名稱)作爲函數參數。目前,我做了以下內容:在F#中,如何將類型名稱作爲函數參數傳遞?

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]) 

但上面的d的存在是偶然的。表達上述邏輯的慣用F#方式是什麼?

在此先感謝您的幫助。

回答

5

你可以使用一個類型ARG:

let f<'T> (n : int) = 
    if typeof<'T> = typeof<int> then Integer(n) 
    else IntegerList([0 .. n]) 
+0

謝謝,我會用這個。 – Shredderroy

+0

很好的答案謝謝。 – AntonB

相關問題