GeorgeWChubby
GeorgeWChubby

Reputation: 808

Using List.nth on an 'a list list in SML

I'm trying to declare a function takelist : 'a list list -> int -> 'a list, so that calling takelist xs n will return the elements in spot number n in the lists from xs.

takelist [[#"3", #"6"], [#"6", #"2"], [#"5", #"9"]] 1;

should return [#"6", #"2", #"9"].

This is what I have:

fun tagliste (x::xs) n = List.nth(x,n);

I does half of what I want, and I can't figure how to get everything. I'm just getting the n from the first list instead of all of them. I've been told that map will be able to help, but so far I haven't had any luck using it correctly.

Any help is appreciated!

Upvotes: 0

Views: 3732

Answers (1)

sepp2k
sepp2k

Reputation: 370092

map takes a function f and a list [x0, x1, ..., xn] and returns [f x0, f x1, ..., f xn].

So if we define f x to be List.nth(x,n), you get back [List.nth (x0, n), List.nth (x1, n), ..., List.nth (xn, n)], which is exactly what you want.

Upvotes: 3

Related Questions