2010-01-07 75 views
3

我想實現一個堆數據結構,並希望將代碼應用於支持比較的任何類型,即< => < => =操作。F#支持模板還是泛型?

如何在F#中執行此操作,因爲它是靜態類型的。

回答

9

它,但你必須標註如下:

type Thing<'a when 'a:comparison> = 
    | Pair of ('a*'a) 
    with 
     member m.InOrder() = 
     match m with 
     | Pair (a,b) when a<=b -> true 
     | _ -> false 
     member m.Equal() = 
     match m with 
     | Pair (a,b) when a=b -> true 
     | _ -> false 

Pair(1,2).InOrder() //true 
Pair(3,2).InOrder() //false 
Pair(42,42).Equal() //true 

嘗試更換Thing<'a when 'a:comparison>通過Thing<'a when 'a:equality>觀看InOrder()方法失敗,而Equal()仍然有效。用Thing<'a>替換Thing<'a when 'a:comparison>,這兩種方法都不起作用。

3

是的,它支持仿製藥 - 以this爲例。