如何在VS Code终端的utop中仅显示程序输出而非所有指令
VS Code中OCaml代码执行输出不易查看的解决办法
我有一段OCaml代码:
(*redefining the power function for integers*) let rec ( ** ) v n = if n = 0 then 1 else v * (( ** ) v (n-1));; let rec sommation n = if n = 0 then 0 else -1**(n/3) * n**(2+ (-1)**n) + sommation (n-1);; print_int (sommation 7);;
在VS Code中选中所有代码按Ctrl+Enter运行时,utop终端会逐行输出代码、类型定义信息,最终程序输出(160)被夹杂在中间,显示延迟且不易识别:
└──────────────────────────────────────────────────────────────┘ Type #utop_help for help about using utop. ─( 17:07:51 )─< command 0 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # (*redefining the power function for integers*) let rec ( ** ) v n = if n = 0 then 1 else v * (( ** ) v (n-1));; val ( ** ) : int -> int -> int = <fun> ─( 17:07:51 )─< command 1 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # let rec sommation n = if n = 0 then 0 else -1**(n/3) * n**(2+ (-1)**n) + sommation (n-1);; val sommation : int -> int = <fun> ─( 17:07:54 )─< command 2 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # print_int (sommation 7);; 160- : unit = () ─( 17:07:54 )─< command 3 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─
解决办法
- 批量加载文件执行:将代码保存为
.ml后缀的文件(比如calc.ml),在utop终端中执行#use "calc.ml";;。这种方式会一次性执行所有代码,仅输出必要的类型信息和最终程序结果,不会逐行重复展示代码。 - 调整VS Code插件执行配置:打开VS Code设置(快捷键Ctrl+,),搜索OCaml相关的执行配置(比如
OCaml Platform: Eval Selection),将代码发送模式改为一次性发送选中的全部代码,而非逐行拆分发送。不同插件的具体选项名称可能略有差异,找到控制代码发送粒度的选项调整即可。 - 简化终端输出:如果只是想快速查看程序输出,可以在代码末尾添加
print_newline();;让输出单独占一行;同时可以在utop中执行#utop_prompt_dummy ();;临时关闭命令编号和时间戳显示,让终端输出更简洁。
内容的提问来源于stack exchange,提问作者Programmeur4
相关产品推荐
相关产品推荐

