OCaml中有pair构造函数吗?

问题描述 投票:0回答:1

使用 scanf 解析输入时,例如使用模式“%d %d ”,我经常需要写

fun x y -> x, y

标准库中有函数可以替代这个表达式吗?对,元组,(,),好像没有定义。

ocaml
1个回答
0
投票

据我所知,这并不作为

Stdlib
的一部分存在。

拥有

make2tuple
功能似乎很简单:
let make2tuple a b = (a, b)
,但
make3tuple
make4tuple
等也是如此。什么时候才足够呢?你在哪里划清界限?

这似乎并不比根据需要编写

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)
© www.soinside.com 2019 - 2024. All rights reserved.