Types OCAML:具有多种类型的参数

Types OCAML:具有多种类型的参数,types,ocaml,reusability,Types,Ocaml,Reusability,在Ocaml中是否可以有一个具有多种类型的参数 我定义了两种不同的类型,这两种类型都有一个地址字段: type symbol = { address : string; name : string; } type extern_symbol = { address : string; name : string; ... } 我还有一个函数,它将符号列表作为参数,并检查地址字段。现在,我想将函数的代码重新用于外部符号列表。该函数将对其

在Ocaml中是否可以有一个具有多种类型的参数

我定义了两种不同的类型,这两种类型都有一个地址字段:

type symbol =
  {
    address : string;
    name : string;
  }


type extern_symbol =
  {
    address : string;
    name : string;
    ...
  }

我还有一个函数,它将符号列表作为参数,并检查地址字段。现在,我想将函数的代码重新用于外部符号列表。该函数将对其他列表执行完全相同的操作。有没有一种方法可以在不必编写重复代码的情况下完成此操作?

您不能直接使用记录参数来完成此操作,因为所有记录类型都是不同的。“任何字段名为
address
的字符串类型的记录”的概念没有类型。因此,您不能拥有该类型的参数

当然,如果需要的话,您可以将地址传递给函数,而不是整个记录

或者,您可以传递一个提取地址的函数:

let myfun address_of r =
    do_what_you_want (address_of r)

let internal_addr (r: symbol) = r.address
let external_addr (r: extern_symbol) = r.address

myfun internal_addr r1
myfun external_addr r2
因此,
myfun
的类型如下:

(a -> string) -> a -> result
这将推广到可应用于这两种记录类型的其他操作

也可以使用对象类型而不是记录。“具有名为
address
且返回字符串的方法的任何对象”的概念有一种类型:

那么,通过相同的功能处理它们就不会有任何问题:

let myfun3 sym =
    let addr =
        match sym with
        | Internal x -> x.address
        | External x -> x.address
    in
    do_what_i_wanted addr

您不能直接使用记录参数执行此操作,因为所有记录类型都是不同的。“任何字段名为
address
的字符串类型的记录”的概念没有类型。因此,您不能拥有该类型的参数

当然,如果需要的话,您可以将地址传递给函数,而不是整个记录

或者,您可以传递一个提取地址的函数:

let myfun address_of r =
    do_what_you_want (address_of r)

let internal_addr (r: symbol) = r.address
let external_addr (r: extern_symbol) = r.address

myfun internal_addr r1
myfun external_addr r2
因此,
myfun
的类型如下:

(a -> string) -> a -> result
这将推广到可应用于这两种记录类型的其他操作

也可以使用对象类型而不是记录。“具有名为
address
且返回字符串的方法的任何对象”的概念有一种类型:

那么,通过相同的功能处理它们就不会有任何问题:

let myfun3 sym =
    let addr =
        match sym with
        | Internal x -> x.address
        | External x -> x.address
    in
    do_what_i_wanted addr