Access SML tuples using an index variable

The question is simple.

How to access a tuple using an index variable in SML?

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

Hope someone can help. Thanks in advance!

+7
source share
3 answers

There is no function that takes an integer value and a tuple and extracts this element from the tuple. Of course, there are functions #1 , #2 , ..., but they do not accept an integer argument. That is, the name of the “function” #5 is not function # applied to the value 5 . Thus, you cannot replace the name index instead of 5 .

If you don’t know in advance where the item you want is located in the tuple, you are probably using them the way they are not intended for use.

You may need a list of values ​​for which the 'a list more natural. Then you can access the n th element with List.nth .

+8
source

To clarify a little why you cannot do this, you need to know more about what a tuple is in SML.

Tuples are actually represented as entries in SML. Remember that entries are of the form {id = expr, id = expr, ..., id = expr} , where each identifier is a label.

The difference in tuples and records is given by how you index the elements in the tuple: # 1, # 2, ... (1, "foo", 42.0) is a derived form (equivalent to c) {1 = 1, 2 = "foo", 3 = 42.0} . This is perhaps best seen by the type that SML / NJ gives to this entry.

 - {1 = 1, 2 = "foo", 3 = 42.0}; val it = (1,"foo",42.0) : int * string * real 

Note. The type is not displayed as a record type, for example {1: int, 2: string, 3: real} . The tuple type is again a derived form of the record type.

In fact, #id not a function, and therefore it cannot be called with a variable as an "argument". This is actually a derived form (note the line of the wildcard pattern matching the pattern)

 fn {id=var, ...} => var 

So, in conclusion, you will not be able to do what you do not want, because these derived forms (or syntactic sugar, if you want) are not dynamic.

+9
source

One way, as Sebastian Paasque said, is to use lists. The disadvantage is that you need O (n) calculations to access the nth element of the list. If you need to access an element in O (1), you can use arrays that are in the sml base library. You can find ore about arrays at: http://sml-family.org/Basis/array.html

+1
source

All Articles