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

OCaml方法返回布尔值报错:期望bool类型却得到unit类型

问题修复:OCaml addVehicle方法返回类型错误

错误原因

报错 Error: This expression has type unit but an expression was expected of type bool 核心原因:

  • match isSuccess with | _ -> !isSuccess; 中的分号会将表达式转为 unit 类型(分号代表序列操作,等价于 !isSuccess; (),最终返回空值 ()),而方法要求返回 bool 类型,类型不匹配导致报错。

修复后的代码

method addVehicle licensePlate : bool = 
  let isSuccess = ref false in
  try
    (* get current time to make sure unique id *)
    id <- int_of_float (Unix.time ());

    (* ask to what kind of vehicle to input *)
    let kind = ref 0 in 
    let quit_loop = ref false in
    while not !quit_loop do
      print_string "What kind of vehicle: {0-Car, 1-Motobike, 2-Wheelchair, -1-Exit}? ";
      kind := read_int ();

      if !kind == 0 then 
        (vehicle <- new car licensePlate 60;
         quit_loop := true;)
      else  if !kind == 1 then
        (* 修正:创建motorbike而非car *)
        (vehicle <- new motorbike licensePlate 60;
         quit_loop := true;)
      else if !kind == 2 then
        (vehicle <- new wheelchair licensePlate 60;
         quit_loop := true;)
      else if !kind == -1 then
        quit_loop := true
      else 
        print_endline "Invalid vehicle!"
           
      (* match !kind with
         |  0 -> vehicle <- new car licensePlate 60;        quit_loop := true;
         |  1 -> vehicle <- new motorbike licensePlate 60;  quit_loop := true;
         |  2 -> vehicle <- new wheelchair licensePlate 60; quit_loop := true;
         | -1 -> quit_loop := true;
         |  _ -> print_endline "Invalid vehicle!"; *)
    done;

    (* ask start time *)
    if not (!kind == -1) then 
      let quit_loop = ref false in
      while not !quit_loop do
        print_string "Input start time (format yyyy-MM-dd hh:mm): ";

        let input = read_line () in 
        try
          let (year, month, day, hour, minute) = sscanf input "%d-%d-%d %d:%d" (fun x y z t w -> (x, y, z, t, w)) in
          startTime <- snd (mktime { 
            tm_sec = 0; tm_min = minute; tm_hour = hour; tm_mday = day; 
            tm_mon = month - 1; tm_year = year - 1900; tm_wday = 0; tm_yday = 0; tm_isdst = false;
          });

          quit_loop := true;
          isSuccess := true;
        with
        | _ -> print_endline "Invalid start time!";
      done;
  with
  | _ -> print_endline "Something went wrong when adding vehicle";

  (* 移除末尾分号,确保返回bool类型 *)
  match isSuccess with
  | _ -> !isSuccess

关键修改点

  1. 移除match分支的分号:将 | _ -> !isSuccess; 改为 | _ -> !isSuccess,让match表达式返回 bool 类型,匹配方法的返回要求。
  2. 修正逻辑错误:当用户选择1(Motobike)时,创建motorbike实例而非car,修复原代码中的逻辑bug。
  3. 优化提示信息:将错误提示的print_string改为print_endline,自动换行提升用户体验。

内容的提问来源于stack exchange,提问作者Trần Văn Đan Trường

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:40:44