What are row types? Are they algebraic data types?

后端 未结 3 786
小鲜肉
小鲜肉 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:29

    Row types are weird. And very powerful.

    Row types are used to implement objects and polymorphic variants in OCaml.

    But first, here's what we cannot do without row types:

    type t1 = { a : int; b : string; }
    type t2 = { a : int; c : bool; }
    
    let print_a x = print_int x.a
    
    let ab = { a = 42; b = "foo"; }
    let ac = { a = 123; c = false; }
    
    let () =
     print_a ab;
     print_a ac
    

    This code will of course refuse to compile, because print_a must have a unique type: either t1, or t2, but not both. However, in some cases, we may want that exact behavior. That's what row types are for. That's what they do: a more "flexible" type.

    In OCaml, there are two main uses of row types: objects and polymorphic variants. In terms of algebra, objects give you "row product" and polymorphic variants "row sum".

    What's to note about row types is that you can end up with some subtyping to declare, and very counter intuitive typing and semantics (notably in the case classes).

    You can check this paper for more details.

提交回复
热议问题