Search code examples
smlsmlnjml

How to get element of new type in ML?


for example if I create a new type

type map = int * string;

val a = (1,"a") : int * string;

and then I want to get the inner "a" string from variable a, how can I get that? I have tried a[1], a[2], a(2) and they don't work...


Solution

  • Since the new type is just a two-tuple, you may use pattern-matching, just as you would for other types:

    - val a = (1, "a");
    val a = (1,"a") : int * string
    
    - case a of (_, str) => str;
    val it = "a" : string
    
    - (fn (_, str) => str) a;
    val it = "a" : string
    

    If this becomes a common operation, you might consider using a utility function:

    fun unpackStr (_, str) = str;