You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印列表的列表?OCaml代码类型不匹配报错求助

OCaml类型不匹配问题解决:嵌套列表打印错误

你的listes_paires函数返回类型是'a list list(针对输入的整数列表列表,具体为int list list),但List.iter print_int要求传入的是int list——因为print_int仅接受单个整数作为参数,List.iter会将传入列表的每个元素传递给print_int,而你现在传递的列表元素是int list(子列表),因此触发类型不匹配错误。

以下是两种可行的解决方法:

方案一:嵌套遍历打印(保留原结构)

通过两层List.iter实现:外层遍历每个子列表,内层遍历子列表中的每个整数并打印,同时添加分隔符提升可读性。

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 (fun inner ->
    (* 打印当前子列表的所有元素,用空格分隔 *)
    List.iter (fun num -> print_int num; print_string " ") inner;
    (* 每个子列表打印完换行 *)
    print_newline()
) (listes_paires [[]; [1];[1;2];[1;2;3];[];[5;4;3;2;1]]);;

执行后输出:

1 1 
1 2 
1 2 3 1 2 3 

5 4 3 2 1 5 4 3 2 1 

方案二:展平列表后打印(合并为单列表)

使用OCaml标准库的List.flatten函数将嵌套列表int list list转换为单层的int list,再直接用List.iter print_int打印:

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 (fun num -> print_int num; print_string " ") 
  (List.flatten (listes_paires [[]; [1];[1;2];[1;2;3];[];[5;4;3;2;1]]));;

执行后输出:

1 1 1 2 1 2 3 1 2 3 5 4 3 2 1 5 4 3 2 1 

内容的提问来源于stack exchange,提问作者user21450992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:34:52