0

Just picked up Ocaml and have been looking into recursive iteration and all that. I was trying to iterate through a tuple but got stumped. Let's say I want to iterate through a tuple and divide each element by half, how do I go about doing it? Especially if the size of the tuple is not known but simply given as a variable? Now if i knew it was a 2 element tuple I could do

let rec divide n = match with (a,b) -> ...

So this is where I'm stuck. How do I figure out what to match the argument with? I know tuples are fixed once created so I can't modify it in place so then how would I go about creating a new tuple that contains elements from the original tuple/2. Any help appreciated.

  • 6
    I am not 100% sure about Ocaml, but in the closely related language ML it is simply impossible to write code which is polymorphic over tuples of arbitrary arity. See this: http://stackoverflow.com/q/14416900/4996248 – John Coleman Sep 19 '16 at 03:41

1 Answers1

3

John Coleman is correct, there's no way to write OCaml code that's polymorphic over tuples of different sizes. You can write code that works for a certain size of tuple. You can also write code that works for any number of values of a given type--for that, you would use a list rather than a tuple.

Most likely you can get your code working using lists.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108