2010-01-07 76 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为例。