调用后打印功能(ocaml)

时间:2020-01-25 00:24:24

标签: ocaml

我对ocaml很陌生!我正在使用以下代码:https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists#OCaml

我一直在尝试找出运行product函数后如何打印结果的方法,非常感谢!

open Printf

let rec product l1 l2 = (* Create a recursive function (rec) named product that has 2 parameters *)
    (*ignore (Printf.printf "Debug: %s\n" 1);*)
    match l1, l2 with
    | [], _ | _, [] -> []
    | h1::t1, h2::t2 -> (h1,h2)::(product [h1] t2)@(product t1 l2)
;;

let test =
    product [1;2] [3;4];;
    ignore (Printf.printf "test: %d*" 1);
(*- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]*)
product [3;4] [1;2];;
(*- : (int * int) list = [(3, 1); (3, 2); (4, 1); (4, 2)]*)
product [1;2] [];;
(*- : (int * 'a) list = []*)
product [] [1;2];;
(*- : ('a * int) list = []*)

1 个答案:

答案 0 :(得分:1)

您的功能product具有以下类型:

'a list -> 'b list -> ('a * 'b) list

由于结果没有特定类型,因此没有内置方法可以打印出此函数的结果。结果的类型取决于两个输入列表的类型。由于OCaml是一种强类型语言,因此通常无法在运行时检查类型并根据类型进行不同的打印。

如果您在顶层(OCaml的REPL)中运行代码,它将为您写出结果。它使用普通的OCaml程序实际上不可用的代码:

# product [1;2] [3;4];;
- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]
# product [1.; 2.] ['a'; 'b'];;
- : (float * char) list = [(1., 'a'); (1., 'b'); (2., 'a'); (2., 'b')]

如果您希望将自己限制为整数列表,则可以使用此功能来打印类型为(int * int) list的列表:

let print_ints pair_list =
    let pair_str (i, j) = Printf.sprintf "(%d, %d)" i j in
    print_string
        ("[" ^ String.concat "; " (List.map pair_str pair_list) ^ "]\n")

如果在顶层运行它,则看起来像这样:

# print_ints (product [2;3] [4;5]);;
[(2, 4); (2, 5); (3, 4); (3, 5)]
- : unit = ()
相关问题