Search code examples
tuplessml

Accessing SML tuples by Index Variable


Question is simple.

How to access a tuple by using Index variable in SML?

val index = 5;
val tuple1 = (1,2,3,4,5,6,7,8,9,10);

val correctValue = #index tuple1 ??

I hope, somebody would be able to help out. Thanks in advance!


Solution

  • There doesn't exist a function which takes an integer value and a tuple, and extracts that element from the tuple. There are of course the #1, #2, ... functions, but these do not take an integer argument. That is, the name of the "function" is #5, it is not the function # applied to the value 5. As such, you cannot substitute the name index instead of the 5.

    If you don't know in advance at which place in the tuple the element you want will be at, you're probably using them in a way they're not intended to be used.

    You might want a list of values, for which the 'a list type is more natural. You can then access the nth element using List.nth.