Source

ocaml-guide / src / types.org

Full commit
#+TITLE: OCaml Guide: Types
#+AUTHOR: Taylor Venable
#+OPTIONS: H:6 toc:2

* The Types of Things

In OCaml,

* Numbers
** Integers

Integers in OCaml are signed and have a magnitude of 30 bits. It's possible to experience overflow.

#+BEGIN_EXAMPLE
# let fib n =
    let rec fib2 a b c =
      match c with
          0 -> b
        | c -> fib2 b (a + b) (c - 1)
    in fib2 0 1 n;;
          val fib : int -> int = <fun>
# fib 1000;;
- : int = -143806971314347795
#+END_EXAMPLE

This is clearly not correct.

Another way to use big numbers is to use the version in Batteries: ~BatBig_int~. Here's an example:

#+BEGIN_EXAMPLE
# #require "batteries" ;;
...
# open BatBig_int ;;
# let fib n =
    let rec fib2 a b c =
      if c = zero then b
      else fib2 b (a + b) (c - one)
    in fib2 zero one (of_int n);;
        val fib : int -> BatBig_int.t = <fun>
# fib 1000 ;;
- : BatBig_int.t =
<big_int 70330367711422815821835254877183549770181269836358732742604905087154537
11819693357974224949456261173348775044924176599108818636326545022364710601205337
4121273867339111198139373125598767690091902245245323403501>
#+END_EXAMPLE