Getting started

theindigamer edited this page Jun 26, 2017 · 23 revisions

A trivial project using batteries 2.0:

(* euler001.ml *)
open Batteries

let main () =
  (1--999) (* the enum that counts from 1 to 999 *)
  |> Enum.filter (fun i -> i mod 3 = 0 || i mod 5 = 0)
  |> Enum.reduce (+) (* add all remaining values together *)
  |> Int.print stdout

let () = main ()

To compile this program, run ocamlfind ocamlc -package batteries -linkpkg euler001.ml -o euler001.

If you have a larger project, ocamlbuild and OMake both work well with batteries.

Warning about 'open' in Batteries 1.x

Batteries 1.x has two main modules: Batteries_uni for compiling without threads and Batteries for compiling with threads. Since compiling without threads is the default, you may get the error

Unknown module 'Batteries'

There are two fixes for this. One is to turn on threads, the other is to open Batteries_uni instead of Batteries.

Batteries 2.x changes this model so that all modules that require threads are in BatteriesThreads, so that open Batteries is valid no matter how you compile.

Ocamlbuild

OCaml 3.12 or newer

Ocamlbuild comes with support for findlib since 3.12.0. There may be bugs in its handling of threads in 3.12.0, so we recommend 3.12.1 if you are going to follow these instructions. The 3.10-3.11 instructions will work under 3.12.0 as well.

  1. Tell ocamlbuild to use batteries through a _tags file: <*>: package(batteries)
  2. Use open Batteries in your source files to allow referring to BatFoo as just Foo. This also integrates BatList and all other stdlib-extensions into the standard module names.
  3. Compile with ocamlbuild -use-ocamlfind foo.byte where foo.ml is the name of your main module file. (or foo.native for native compilation)

OMake

If you're already using OMake, add the following to your OMakefile:

OCAMLPACKS[] += batteries
OCAMLFLAGS += -thread

Toplevel

To load batteries included in your toplevel, copy the ocamlinit file from the batteries source tree to ~/.ocamlinit and it will auto-load ocamlfind and the syntax extensions. You should see a graphical banner indicating that batteries is loaded.

ocamlscript

To use Batteries with ocamlscript, you only need to include the appropriate findlib package(s).

#!/usr/bin/env ocamlscript

(* Compile and link with Batteries *)
Ocaml.packs := ["batteries"];;
--
open Batteries

let () = print_endline "Hello world!"