OCaml代码编译报错:类型unit与'a Client.io不匹配
问题原因
错误的核心是Lwt的绑定操作(>>=)要求回调函数返回Lwt promise类型(即'a Lwt.t,这里显示为'a Client.io),但你所有分支里的printf调用返回的是普通unit类型,和预期的Lwt promise类型不匹配。
解决方案
你需要让每个分支的返回值都变成unit Lwt.t,有两种简单的实现方式:
方式1:用Lwt.return包装同步打印结果
Lwt.return可以把普通值包装成Lwt promise,只需在每个printf后补充Lwt.return ()即可:
if code == 200 then if member "usage_type" json <> `Null then let usage_type = json |> member "usage_type" |> to_string in printf "usage_type: %s\n" usage_type; Lwt.return () else printf "ERROR: The usage_type field requires a paid subscription to the \ Starter plan or higher.\n"; Lwt.return () else if (code == 400 || code == 401) && member "error" json <> `Null then let error_message = json |> member "error" |> member "error_message" |> to_string in print_endline ("ERROR: " ^ error_message); Lwt.return () else ( print_endline ("HTTP Code: " ^ Int.to_string code); Lwt.return () )
方式2:使用Lwt异步打印函数Lwt_io.printf
Lwt_io.printf是Lwt提供的异步打印函数,直接返回unit Lwt.t,完全符合>>=回调的返回类型要求,代码更简洁:
修改后的完整代码
open Printf open Lwt open Cohttp open Cohttp_lwt_unix open Yojson let () = let ip = "8.8.8.8" in let key = "" in let uri = Uri.of_string ("https://api.ip2location.io/?format=json&key=" ^ key ^ "&ip=" ^ ip) in Lwt_main.run ( Client.get uri >>= fun (resp, body) -> let code = resp |> Response.status |> Code.code_of_status in body |> Cohttp_lwt.Body.to_string >>= fun json_string -> let json = Basic.from_string json_string in let open Yojson.Basic.Util in if code == 200 then if member "usage_type" json <> `Null then let usage_type = json |> member "usage_type" |> to_string in Lwt_io.printf "usage_type: %s\n" usage_type else Lwt_io.printf "ERROR: The usage_type field requires a paid subscription to the \ Starter plan or higher.\n" else if (code == 400 || code == 401) && member "error" json <> `Null then let error_message = json |> member "error" |> member "error_message" |> to_string in Lwt_io.printf "ERROR: %s\n" error_message else Lwt_io.printf "HTTP Code: %d\n" code )
注意:原代码中
printf "ERROR: " ^ error_message是错误写法,因为printf返回unit,无法和字符串做^拼接,上述修改已修复该问题。
内容的提问来源于stack exchange,提问作者Vlam
相关产品推荐
相关产品推荐

