首页 > 解决方案 > 如何将 OCaml 库引用添加到原因代码文件?

问题描述

今天刚从 Reason 和 OCaml 开始。我从https://github.com/esy-ocaml/hello-reason示例开始。我想进行 HTTP API 调用,所以我已经安装了ocaml-cohttpesy add @opam/cohttp-lwt

现在我想在 hello-reason 入门示例中使用该库(或任何您可能有的建议)。

我找不到有关如何导入它的参考文档。我试过了:

open cohttp-lwt

我可以在 Reason 代码文件中使用 OCaml 库吗?

标签: ocamlreason

解决方案


是的,唯一的区别是语法。客户端教程可以直接翻译,自动翻译成这样:

open Lwt;
open Cohttp;
open Cohttp_lwt_unix;

let body =
  Client.get(Uri.of_string("https://www.reddit.com/"))
  >>= (
    ((resp, body)) => {
      let code = resp |> Response.status |> Code.code_of_status;
      Printf.printf("Response code: %d\n", code);
      Printf.printf(
        "Headers: %s\n",
        resp |> Response.headers |> Header.to_string,
      );
      body
      |> Cohttp_lwt.Body.to_string
      >|= (
        body => {
          Printf.printf("Body of length: %d\n", String.length(body));
          body;
        }
      );
    }
  );

let () = {
  let body = Lwt_main.run(body);
  print_endline("Received body\n" ++ body);
};

编辑:hello-reason使用,因此您还必须添加cohttp-lwt-unixlibraries项目dune文件中的节中,如这里的客户端教程所示


推荐阅读