Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a pair construction function in OCaml?

When parsing input with scanf, for example with the pattern "%d %d\n", I often need to write fun x y -> x, y.

Is there a function in the standard library to replace this expression? pair, tuple, (,), don’t seem to be defined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To the best of my knowledge this does not exist as part of Stdlib.

Having a make2tuple function seems straightforward: let make2tuple a b = (a, b), but so does make3tuple and make4tuple, etc, etc. When is enough enough? Where do you draw the line?

This doesn’t seem particular better than writing fun a b -> (a, b) or fun a b c -> (a, b, c) as needed. If they’re needed often, you can create utility functions for this in your code.

Just be aware of the value restriction if you try to use partial function application with this:

# 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading