Accessing SML tuples by Index Variable

六眼飞鱼酱① 提交于 2019-12-23 08:54:05

问题


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!


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/14416900/accessing-sml-tuples-by-index-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!