---
breaks: false
tags: public-tech
---
# 外部ライブラリの関数を対話型インタプリタ(utop)で使う
この記事は [OCaml Tips Advent Calendar 2022](https://adventar.org/calendars/8396) の16日目です。
OCaml で開発を行っていると、OCaml コード片の動作を簡単に確認したくなることが
あります。このような場合には対話型インタプリタが便利で、例えば `ocaml` コマンドや、
それを強化した `utop` コマンドを使うことができます。
しかし、単純に起動した対話型インタプリタでは、すでに書いたコードで定義した関数や、
外部ライブラリで定義された関数の呼び出しを行うことができません。
インタプリタを起動するたびに、動作を確認したいコードで使用されている関数を
全て定義しなければならないのは億劫です[^number-load]。
[^number-load]: `#require` を使って比較的簡単にライブラリを読み込むことはできますが、それも毎回するのは面倒です。
```
$ vim bin/dune
(executable
(public_name yourfavname)
(name main)
(libraries yourfavname sha))
$ vim lib/hello.ml
let hello () = "Hello, World!"
$ utop
...
utop # Sha256.("foo" |> string |> to_hex);;
Error: Unbound module Sha256 (* 外部ライブラリが見つからない *)
utop # Yourfavname.Hello.hello ();;
Error: Unbound module Yourfavname (* 自分で定義したモジュールが見つからない *)
```
このような場合、dune を使用しているプロジェクトでは `dune utop` コマンドを
実行することで、そのプロジェクトで定義したモジュールや `libraries` stanza で
宣言された外部ライブラリを読み込んだ状態で `utop` を立ち上げることができます。
```
$ dune utop
...
utop # Yourfavname.Hello.hello ();;
- : string = "Hello, World!"
utop # Sha256.("foo" |> string |> to_hex);;
- : string = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
```