int * int vs (int * int) in OCaml sum type

后端 未结 4 775
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 01:15
type foo = A of int * int | B of (int * int)

What is the difference between int * int and (int * int) there? The only dif

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 02:18

    As already said, the constructor of A takes two int, whereas the constructor of B takes an ordered pair.

    so you can write

    let bar = A (1, 2)
    

    or

    let bar = B (1, 2)
    

    or

    let bar = (1, 2)
    let baz = B bar
    

    but you cannot write

    let bar = (1, 2)
    let baz = A bar
    

    Moreover, in your pattern matching, you can still match the content of B as two int, but you cannot match the content of A as value bound to an ordered pair

    let test_foo = function
      | A a -> a (* wrong *)
      | B (f, s) -> (f, s) (* ok *)
    

提交回复
热议问题