What are row types? Are they algebraic data types?

后端 未结 3 780
小鲜肉
小鲜肉 2020-12-14 01:46

I often hear that F# lacks support for OCaml row types, that makes the language more powerful than F#.

What are they? Are they algebraic data types, such as sum type

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 02:30

    I'll complete PatJ's excellent answer with his example, written using classes.

    Given the classes below:

    class t1 = object
      method a = 42
      method b = "Hello world"
    end
    
    class t2 = object
      method a = 1337
      method b = false
    end
    

    And the objects below:

    let o1 = new t1
    let o2 = new t2
    

    You can write the following:

    let print_a t = print_int t#a;;
    val print_a : < a : int; .. > -> unit = 
    
    print_a o1;;
    
    42
    - : unit = ()
    
    print_a o2;;
    
    1337
    - : unit = ()
    

    You can see the row type in print_a's signature. The < a : int; .. > is a type that literally means "any object that has at least a method a with signature int".

提交回复
热议问题