mechanism to get element from the list

rookie picture rookie · Jan 12, 2011 · Viewed 7.8k times · Source

is it possible to get element from the list in SML of New Jersey without using function head and tail, something like that:

val a = [1,2,3];
a[1];

thanks in advance

Answer

sepp2k picture sepp2k · Jan 12, 2011

You can use the function List.nth, which takes a tuple containing a list and an index and returns the element at that index. So in your example, it'd be List.nth (a, 1).

Note however that accessing the nth element of a linked list is O(n), so if you use List.nth to iterate through a list, you'll end up with quadratic running time.