How to write code in F# for what functors do in OCaml?

后端 未结 3 2255
一个人的身影
一个人的身影 2021-02-19 19:21

I have many programs written in OCaml, some of them use functors. Now, I am considering of writing and re-writing a part of code in F# (to benefit some advantages that OCaml doe

3条回答
  •  一向
    一向 (楼主)
    2021-02-19 20:09

    Here is a bit different approach that achieves same outcome using a generic class and one object per type.

    type Comparison = Less | Equal | Greater
    
    type Set<'a>(compare : 'a -> 'a -> Comparison) =
    
        member this.Empty : 'a list = []
    
        member this.Add x s = 
             match s with
             | [] -> [x]
             | hd::tl ->
                 match compare x hd with
                 | Equal   -> s         (* x is already in s *)
                 | Less    -> x :: s    (* x is smaller than all elements of s *)
                 | Greater -> hd :: this.Add x tl
    
    
    let compare x y = if x = y then Equal else if x < y then Less else Greater
    
    let compareFloats (x : float) (y : float) = if x = y then Equal else if x < y then Less else Greater
    
    // Note that same generic compare function can be used for stringSet and intSet
    // as long as the type parameter is explicitly given
    let stringSet = Set(compare)
    let intSet = Set(compare)
    
    // Type parameter not needed, because compareFloats is not generic
    let floatSet = Set(compareFloats)
    
    let try1 () = stringSet.Add "foo" stringSet.Empty   // -> ["foo"]
    let try2 () = intSet.Add 2 intSet.Empty             // -> [2]
    let try3 () = floatSet.Add 3.0 floatSet.Empty       // -> [3.0]
    

提交回复
热议问题