prmz
prmz

Reputation: 311

Square a list of lists - ocaml

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

Upvotes: 1

Views: 1724

Answers (1)

gasche
gasche

Reputation: 31459

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]] *)

Upvotes: 5

Related Questions