假设我们有一个名为 d 的类型:
type d = D of int * int
Run Code Online (Sandbox Code Playgroud)
我们想要对其进行一些模式匹配,这样是不是更好:
let dcmp = function
| D (x, y) when x > y -> 1
| D (x, y) when x < y -> -1
| _ -> 0
Run Code Online (Sandbox Code Playgroud)
或者
let dcmp = function
| D (x, y) ->
if x > y then 1 else if x < y then -1 else 0
Run Code Online (Sandbox Code Playgroud)
一般而言,将模式与许多“when”情况匹配或匹配一个模式并在其中放入“if-then-else”会更好吗?
我在哪里可以获得有关此类问题的更多信息,例如 OCaml 和语法糖等的良好实践?
performance ocaml functional-programming if-statement pattern-matching
我想编写一个函数,该函数采用实现特定签名的模块和与这些模块相同类型的实例,但显然我不能这样做,因为与模块范围相关的问题(模块及其实例是两个参数,因此实例不知道模块的类型)。
下面是一个例子:
let f (type a) (module M: Set.S with type elt = a) (pr: a -> unit) (m: M.t) =
M.iter pr m;;
Run Code Online (Sandbox Code Playgroud)
其中M是具有 type 元素的 Set 模块a,并且pr可以是 type 元素的打印机a。以及由此引起的错误消息(我觉得不是很清楚):
Line 1, characters 69-78:
Error: This pattern matches values of type M.t
but a pattern was expected which matches values of type 'a
The type constructor M.t would escape its scope
Run Code Online (Sandbox Code Playgroud)
我试图通过考虑问题是由仅覆盖函数体的参数范围引起的来解决这个问题,所以我将最后一个参数放在函数体中,如下所示:
let f (type a) (module M: Set.S with type …Run Code Online (Sandbox Code Playgroud) 如果我们有两个列表l1并且l2我们想要连接它们,我们可以使用@or appendwhich is in O(n1)where n1is 的长度l1。或者我们可以rev_append根据文档使用:
equivalent to List.rev l1 @ l2, but rev_append is tail-recursive and more efficient.
Run Code Online (Sandbox Code Playgroud)
那么是rev_append比 更有效@还是比 更有效List.rev + @?当我们不关心顺序时,使用它代替@and是否更好?append