Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml map on a tuple

Tags:

ocaml

I have several places in my code which look like this:

let (a,b,c) = (f "a", f "b", f "c")

It would be nice if I can write something like:

let (a,b,c) = map f ("a", "b", "c")

If there is way to do something like this in OCaml?

like image 676
krokodil Avatar asked Mar 09 '26 15:03

krokodil


2 Answers

You can easily write map for triples of one type of element:

let map_triple f (a, b, c) = (f a, f b, f c)

let a, b, c = map_triple String.length ("foo", "bar", "quux")

It will only work for one length of tuple, however.

It would be possible to write a GADTified tuple type and write a map over that type that is polymorphic in the length of the tuple, but that kind of trickery is best avoided unless the advantage is large, which does not seem to be the case here.

like image 65
gsg Avatar answered Mar 12 '26 09:03

gsg


The best answer is that you can't do this, if you want it to work for tuples of different sizes. Each tuple size is a different type in OCaml. So there's no OCaml type representing the idea of "a tuple of any size whose elements are strings."

But in fact this sounds like a list more than a tuple. If you can use lists instead of tuples, you can use the plain old List.map function.

like image 26
Jeffrey Scofield Avatar answered Mar 12 '26 10:03

Jeffrey Scofield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!