user1836292
user1836292

Reputation: 99

How do I use List.map to apply a function on a int list list?

Suppose I have a (int list list) x = [[1;1;1]; [2;2;2]; [3;4;5]] and a function f. The result should be [f [1;1;1]; f [2;2;2]; f[3;4;5]]. The built in List.map works only for int list but not for int list list.The i-th entry in this new column is computed by the function f which is taking as input the i-th element from each column in the spreadsheet and forms a new element.

let newList x f = List.map f x (* this is the only map function that I know *)

Upvotes: 2

Views: 2517

Answers (1)

thor
thor

Reputation: 22520

You can use List.map f as a function, which works on one dimensional lists, and then map that function on the two-dimensional list as follows:

let x = [[1;1;1]; [2;2;2]; [3;4;5]];; 
let f x = x + 1;; 
List.map (List.map f) x;;

output:

- : int list list = [[2; 2; 2]; [3; 3; 3]; [4; 5; 6]]

my function will take as input two arguments, an int list list and a function f. It will output a new int list. Input = m = [[x1;x2;x3] ; [y1;y2;y3] ; [z1;z2;z3]] and function f Output = [f [x1;y1;z1] ; f [x2;y2;z2] ; f [x3;y3;z3]]

It seems that you wanted to transpose (https://stackoverflow.com/a/3989823/4196578) your 2-D array and then map f. In that case, you can do:

let rec transpose list = match list with
| []             -> []
| []   :: xss    -> transpose xss
| (x::xs) :: xss ->
    (x :: List.map List.hd xss) :: transpose (xs :: List.map List.tl xss);;

let myfunc m f = List.map f (transpose m);;

Upvotes: 2

Related Questions