How do you manage a list of tuples in SML?

I am new to SML, and I was wondering how to get an item in the list of tuples. For example, in the list [("abc", 4), ("def", 6)] , how could you extract "abc" ? I tried

 x::xs => #1(x) 

but I keep getting the "unresolved flexible record." Any suggestions?

+4
source share
4 answers

The error you encountered is related to the fact that things like #1 are special and their type depends on what it is used for. For example, in #1 (1,2) type #1 is 'a * 'b -> 'a ; whereas in #1 (1,2,3) type #1 is equal to 'a * 'b * 'c -> 'a . There is no type like 'a * ... -> 'a that will work for everything, so the compiler must be able to determine the type in which it will be used (basically, how many elements are in the tuple).

So this does not work:

 fun f lst = case lst of x::xs => #1 x | [] => "The list is empty" 

because he just knows that it is "some kind of list", and x - "some value of some type". But he does not know what kind of motorcade this is.

Just adding a type guard or some other context that allows the compiler to tell you what type of tuple it will work:

 fun f (lst : (string * 'a) list) = case lst of x::xs => #1 x | [] => "The list is empty" 
+5
source

I would extract it like this:

 fun foo ((x,y)::xs) = x; 

to extract a tuple from the list and bind x to abc and y to 4 , and then just return x . for example, you can also combine tuples and return a list of only rows:

 fun f [] = [] | f ((x,y)::xs) = x ^ Int.toString(y) :: f(xs); 

given the list [("abc",4),(def",6)] , it will return the list ["abc4","def6"]

+4
source

You can simply extract it using pattern matching.

 let val lst = [("abc", 4), ("def", 6)] in case lst of (str,_)::xs => str | [] => "The list is empty" end 

Will return "abc" .

+2
source

you may have a function to get the tuple value, for example:

 fun getname(name:string, x:int) = name; 

if you have a list:

 val lst = [("abc", 4), ("def", 6)] 

then you can extract the name of the first tuple (hd) by doing:

 getname(hd lst) 

Will return "abc"

+1
source

All Articles