Question

I am working with big_int type. I looked in the OCaml's library Pervasives.

For example: in Int32

let t = 5l
Printf.printf "%ld" t

How can I define t and which %?d if I want to declare it is an big_int?

Was it helpful?

Solution

Below is a toplevel session. The #load directive would become a command-line link option if you used the compiler:

# #load "nums.cma" ;;
# let t = Big_int.big_int_of_int 5 ;;
val t : Big_int.big_int = <abstr>
# Printf.printf "%s" (Big_int.string_of_big_int t) ;;
5- : unit = ()

For numbers that do not fit in a native int, use Big_int.big_int_of_string. Example: Big_int.big_int_of_string "99999999999999999999999".

The complete list of functions is here.

Finally, the Big_int module is quite old and clumsy. The interface dates back to caml-light, in which the module system was rudimentary. This is the reason why each function name redundantly repeats "big_int...". If you are choosing a big integer library now, I would recommend Zarith, which is modern and efficient. The drawback of Zarith is that it is a separate download (for now).

OTHER TIPS

There are several modern "big numbers" libraries for OCaml, all interfaces about GNU MP:

  1. My own, mlgmp, which ships with many Linux distributions as libgmp-ocaml.
  2. mlgmpidl from Bertrand Jeannet (BEWARE: both mlgmp and mlgmpidl declare themselves to ocamlfind as the Gmp package, thus weird conflicts).
  3. ZArith

ZArith is better for two reasons:

  1. It tries as much as possible to perform computations on machine integers before allocating GNU MP objects.
  2. It allocates GNU MP objects inside the OCaml heap, as opposed to the normal allocation scheme through malloc(), which is not very suited to functional programming.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top