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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With