How to get element of new type in ML?

154 views Asked by At

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...

2

There are 2 answers

2
Michael Rawson On BEST ANSWER

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;
0
AudioBubble On

You can use the #n operator to get the n-th element of any tuple. In the REPL:

- #1("one", "two");
val it = "one" : string
- #2("one", "two");
val it = "two" : string