Ocaml中函数的命名约定

Sof*_*mur 2 ocaml naming-conventions

由于Ocaml不接受函数重载,有时我必须为不同类型定义一些类似的函数.例如,

let reduce_a (a: A): A = ...
let reduce_b (b: B): B = ...

let a_compare (a0: A) (a1: A): bool = ...
let b_compare (b0: B) (b1: B): bool = ...
Run Code Online (Sandbox Code Playgroud)

我知道,最好的办法是有两个模块AB,使2个功能A.reduceB.reduce.但在创建模块之前,我只想知道命名函数的最佳约定.

人们通常喜欢命名reduce_a(a_reduce类型前的动词)还是(动词前的类型)?我们能在标准库中找到一些例子吗?

nlu*_*oni 6

另一种选择是将它们放在自己的模块中,比如

module A = struct

    type t = ...
    let reduce x = ...
    let compare x y = ...

end

module B = struct ... (* you get the point *) end
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您无需担心函数是否为compare_a或者a_compare,因为它必须是A.compare.你必须克制自己(除了当地之外)打开模块.当然,此解决方案的工作能力取决于您正在处理的类型.