简体   繁体   English

在ocaml中打印列表

[英]Printing list in ocaml

I would write (for debugging) a printer for a list of ((string * string) * 'a) 我会写(用于调试)打印机以获取((string * string) * 'a)

I tried with: 我尝试了:

(* print a list of ((string * string) * 'a)  *)
let rec print_list = function
[] -> Printf.printf "\n empty list \n %!"; ()
| ((s1,s2),a)::l -> Printf.printf "\n(s1,s2)= %s %s  \n %!" s1 s2; print_list l;;

but it doesn't print anything. 但它不会打印任何内容。

It should print at least empty list , right? 它应该至少打印empty list ,对不对?

In many languages (C and Ocaml) you'll better put the \\n at end of printf format control string, or force the stdout to be flushed. 在许多语言(C和Ocaml程序编写),你最好把\\n年底 printf格式控制字符串,或强制刷新标准输出。 Output to stdout is usually buffered (for performance reasons). 通常会缓冲对stdout的输出(出于性能原因)。

You should read the documentation of Ocaml before coding in Ocaml. 在使用Ocaml编码之前,您应该阅读Ocaml文档

You may also want to call (from Pervasives ) print_newline ; 您可能还想致电(从Pervasivesprint_newline ; read carefully documentation of Printf module ; 仔细阅读Printf模块的文档; you could end your printf format string with %! 您可以用%!结束printf格式字符串%!

Here is an example (copied from your edited question) with Ocaml 4.01: 这是Ocaml 4.01的示例(从您已编辑的问题中复制):

% ocaml
    OCaml version 4.01.0

 # (* print a list of ((string * string) * 'a)  *)
 let rec print_list = function
   [] -> Printf.printf "\n empty list \n %!"; ()
   | ((s1,s2),a)::l -> Printf.printf "\n(s1,s2)= %s %s  \n %!" s1 s2; 
                       print_list l;;    

val print_list : ((string * string) * 'a) list -> unit = <fun>

# print_list [];;

empty list 
- : unit = ()
# 

As you can see, empty list gets printed. 如您所见,将打印empty list In the above code, % is a shell prompt, # is an ocaml toplevel prompt. 在上面的代码中, %是shell提示符, #是ocaml顶级提示符。 Your function is copied verbatim. 您的函数被逐字复制。 print_list [];; is input at toplevel. 在顶级输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM