【问题标题】:Ocaml - unexpected outputOcaml - 意外输出
【发布时间】:2020-06-22 11:46:26
【问题描述】:

我有以下代码:

let str = "AA";;
let i =ref 0;;
let tam_str = String.length str -1;;
let aux_char = 'A';;
let b_aux1 = ref false;;
exception Out_of_loop;;

try
  while !i <= tam_str do
    let c_r = str.[!i] in
    if c_r = aux_char then(
      b_aux1 := true;
      i := !i +1;
    )
    else(
      b_aux1 := false;
      raise Out_of_loop
    )
  done;
with Out_of_loop ->();
if !b_aux1 then
  print_endline "1"
else
  print_endline "0";
;;

我希望程序写入字符串“1”,但它返回的是“单位”。但我不明白为什么......有人可以解释为什么吗?

【问题讨论】:

    标签: output ocaml


    【解决方案1】:

    注意各种构造的优先级。你写了

    try ...
    with Out_of_loop ->
      begin
        ();
        if !b_aux1 then ...
      end
    

    我猜你想写

    begin
      try ...
      with Out_of_loop -> ()
    end;
    if !b_aux1 then ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多