【问题标题】:OCaml: List that could contain two types?OCaml:可以包含两种类型的列表?
【发布时间】:2009-09-15 18:00:51
【问题描述】:

我可以指定一个列表,其成员必须是字符串或整数,而不是指定一个整数列表或字符串列表,而不是指定一个列表?

【问题讨论】:

    标签: list types ocaml


    【解决方案1】:

    你可以这样做:

    type element = IntElement of int | StringElement of string;;
    

    然后使用elements 的列表。

    【讨论】:

      【解决方案2】:

      一个选项是polymorphic variants。您可以使用以下方式定义列表的类型:

      # type mylist = [`I of int | `S of string] list ;;
      type mylist = [ `I of int | `S of string ] list
      

      然后定义值如:

      # let r : mylist = [`I 10; `S "hello"; `I 0; `S "world"] ;;
      val r : mylist = [`I 10; `S "hello"; `I 0; `S "world"]
      

      您必须小心添加类型注释,因为多态变体是“开放”类型。例如,以下是合法的:

      # let s = [`I 0; `S "foo"; `B true]
      val s : [> `B of bool | `I of int | `S of string ] list =
        [`I 0; `S "foo"; `B true]
      

      要防止列表类型允许非整数或字符串值,请使用注释:

      # let s : mylist = [`I 0; `S "foo"; `B true];;
      This expression has type [> `B of bool ] but is here used with type
        [ `I of int | `S of string ]
      The second variant type does not allow tag(s) `B
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        相关资源
        最近更新 更多