Does F # support templates or generics?

I want to implement a heap data structure and want to apply the code to any type that supports comparison, i.e. => <=> = operations.

How to do this in F # since it is statically typed.

+3
source share
3 answers

It does, but you should annotate the following:

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

Try replacing Thing<'a when 'a:comparison>with Thing<'a when 'a:equality>to see how the method works InOrder(), but Equal()it still works. Replace Thing<'a when 'a:comparison>with Thing<'a>and both methods will not work.

+9
source

, - .

+3
source

Source: https://habr.com/ru/post/1727607/


All Articles