krokodil
krokodil

Reputation: 1366

OCaml map on a tuple

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?

Upvotes: 3

Views: 3168

Answers (2)

gsg
gsg

Reputation: 9377

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.

Upvotes: 7

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

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.

Upvotes: 6

Related Questions