Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing SML tuples by Index Variable

Tags:

tuples

sml

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!

like image 572
InnovWelt Avatar asked Jan 19 '13 17:01

InnovWelt


3 Answers

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.

like image 74
Sebastian Paaske Tørholm Avatar answered Nov 05 '22 08:11

Sebastian Paaske Tørholm


To clarify a bit, why you can't do that you need some more knowledge of what a tuple is in SML.

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

The difference of tuples and records is given away by the way you index elements in a tuple: #1, #2, ... (1, "foo", 42.0) is a derived form of (equivalent with) {1 = 1, 2 = "foo", 3 = 42.0}. This is perhaps better seen by the type that SML/NJ gives that record

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

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

Actually #id is not a function, and thus it can't be called with a variable as "argument". It is actually a derived form of (note the wildcard pattern row, in the record pattern match)

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

So in conclusion, you won't be able to do what you wan't, since these derived forms (or syntactic sugar if you will) aren't dynamic in any ways.

like image 30
Jesper.Reenberg Avatar answered Nov 05 '22 08:11

Jesper.Reenberg


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

like image 32
george Avatar answered Nov 05 '22 08:11

george