Square a list of lists - ocaml

别来无恙 提交于 2019-12-11 11:09:46

问题


I know how to square elements of a list, but how to square in list of lists?

To square an element of a list i could use, for example:

List.map (fun x -> x*x) [1; 2; 3];;

How to do this on list of lists?

[[1; 2]; [2; 3]]  --> [[1; 4]; [4; 9]]

or

[[1; 2; 3]; [4; 2; 0]] --> [[1; 4; 9]; [16; 4; 0]]

for example.

Thanks


回答1:


let square = fun x -> x * x;;
(* val square : int -> int = <fun> *)

List.map square;;
(* - : int list -> int list = <fun> *)

List.map (List.map square);;
(* - : int list list -> int list list = <fun> *)

List.map (List.map (fun x -> x*x)) [[1; 2]; [2; 3]];;
(* - : int list list = [[1; 4]; [4; 9]] *)


来源:https://stackoverflow.com/questions/16129606/square-a-list-of-lists-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!