OCaml 中有结对构造函数吗?

Is there a pair construction function in OCaml?

提问人:richardIII 提问时间:10/28/2023 最后编辑:ChrisrichardIII 更新时间:10/28/2023 访问量:48

问:

在解析输入时,例如用模式,我经常需要写。scanf"%d %d\n"fun x y -> x, y

标准库中是否有函数可以替换此表达式?pair、tuple、(,)、似乎没有定义。

元组 ocaml

评论


答:

3赞 Chris 10/28/2023 #1

据我所知,这不作为 Stdlib 的一部分存在。

拥有一个函数似乎很简单:,但 和 、 等也是如此。什么时候够了?你在哪里划线?make2tuplelet make2tuple a b = (a, b)make3tuplemake4tuple

这似乎并不比写作或根据需要更好。如果经常需要它们,可以在代码中为此创建实用工具函数。fun a b -> (a, b)fun a b c -> (a, b, c)

如果您尝试使用部分函数应用程序,请注意值限制

# let mk2tuple a b = (a, b);;
val mk2tuple : 'a -> 'b -> 'a * 'b = <fun>
# let make_tuple_with_5 = mk2tuple 5;;
val make_tuple_with_5 : '_weak1 -> int * '_weak1 = <fun>
# make_tuple_with_5 2;;
- : int * int = (5, 2)
# make_tuple_with_5;;
- : int -> int * int = <fun>
# make_tuple_with_5 7.3;;
Error: This expression has type float but an expression was expected of type
         int
# mk2tuple 5 7.3;;
- : int * float = (5, 7.3)