ocaml

How to print a list of lists


I'm trying to print a specific list, but it doesn't work

let rec listes_paires l = match l with
  | [] -> []
  | x :: r -> 
    if List.length x mod 2 = 0 then 
      (x :: (listes_paires r))
    else 
      ((x @ x) :: (listes_paires r));;

List.iter print_int (listes_paires [[]; [1];[1;2];[1;2;3];[];[5;4;3;2;1]]);;

Error message says :

Line 5, characters 20-74:
Error: This expression has type int list list
       but an expression was expected of type int list
       Type int list is not compatible with type int 
val listes_paires : 'a list list -> 'a list list = <fun>

Solution

  • You're not trying to print a list, but a list of lists. The type of listes_paires, as you point out yourself, is 'a list list -> 'a list list

    You can print a list of lists just by adding another List.iter to iterate over the inner lists as well:

    List.iter 
      (List.iter print_int) 
      (listes_paires [[]; [1];[1;2];[1;2;3];[];[5;4;3;2;1]]);;