Hi, I created this simple function in utop:
let get_random_hanzi () =
let buf = Buffer.create 1 in
let chr = Random.int_incl 0x4e00 0x9fff |> Uchar.of_int in
Buffer.add_utf_8_uchar buf chr;
Buffer.contents buf
It works fine, so I saved it inside a file and then created this jbuild file to compile it:
(jbuild_version 1)
(executable
((name hello)
(libraries (core))))
When I run jbuilder build hello.exe
, I get this error:
Error: Unbound value Uchar.of_int
I don’t quite understand why it works fine in utop but doesn’t work at all when I try to compile…
The core library redefines the Uchar
module. In particular, its version of Uchar.of_int
is Uchar.of_scalar_exn
.
1 Like
Thanks so much! That worked, but I had to make one more change before my program would compile. I had to change Buffer.add_utf_8_uchar buf chr
to Caml.Buffer.add_utf_8_uchar buf chr
. The full program looks like this:
open Base
open Stdio
let get_random_hanzi () =
let buf = Buffer.create 1 in
let chr = Random.int_incl 0x4e00 0x9fff |> Uchar.of_scalar_exn in
Caml.Buffer.add_utf_8_uchar buf chr;
Buffer.contents buf
let () =
print_endline "你好世界!";
Random.self_init();
print_endline ("Random hanzi: " ^ get_random_hanzi())
Is there a better way to write that, or does it look more or less OK?
This seems quite good to me: It seems that the base
library version was not updated with the new unicode specific function in Buffer
. In this case, using Caml.Buffer
is the right thing to do.
Alternatively, you could use the Format
or Printf
module for the printing:
let ( ) = Random.self_init ()
let ( ) = Format.printf "你好世界!@.Random hanzi:%s@." (get_random_hanzi ())
1 Like