假设我有一个 (int list list) x = [[1;1;1]; [2;2;2]; [3;4;5]]
和函数 f。结果应该是[f [1;1;1]; f[2;2;2]; f[3;4;5]].
内置的 List.map 仅适用于 int 列表,但不适用于 int 列表 list。此新列中的第 i 个条目由函数 f 计算,该函数取作为输入电子表格中每列的第 i 个元素并形成一个新元素。
let newList x f = List.map f x
(*这是我知道的唯一 map 函数*)
最佳答案
您可以使用 List.map f
作为一个函数,它适用于一维列表,然后 map
该函数适用于二维列表,如下所示:
let x = [[1;1;1]; [2;2;2]; [3;4;5]];;
let f x = x + 1;;
List.map (List.map f) x;;
输出:
- : 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]]
您似乎想转置 ( https://stackoverflow.com/a/3989823/4196578 ) 二维数组,然后映射 f
。在这种情况下,您可以这样做:
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);;
关于list - 如何使用 List.map 在 int list 列表上应用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26645336/