OCaml体验

安装:http://ocaml.org/docs/install.html
文档:http://caml.inria.fr/pub/docs/manual-ocaml/

OPAM安装方式:

  1. wget https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin,需要管理员权限。
  2. 直接下载二进制文件,然后sudo cp /usr/local/bin

卸载:simply remove /usr/local/bin/opam and ~/.opam

opam用法

# ** Get started **
opam init            # Initialize ~/.opam using an already installed OCaml
opam init --comp 4.02.3
                     # Initialize with a freshly compiled OCaml 4.02.3

# ** Lookup **
opam list -a         # List all available packages
opam search QUERY    # List packages with QUERY in their name or description
opam show PACKAGE    # Display information about PACKAGE

# ** Install **
opam install PACKAGE # Download, build and install the latest version of PACKAGE
                     # and all its dependencies

# ** Upgrade **
opam update          # Update the packages database
opam upgrade         # Bring everything to the latest version possible

# ** More **
opam CMD --help      # Command-specific manpage

体验

Under the interactive system, the user types OCaml phrases terminated by ;; in response to the # prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or let definitions of identifiers (either values or functions).

# 1+2*3;;
- : int = 7

# let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265358979312

# let square x = x *. x;;
val square : float -> float = 

# square (sin pi) +. square (cos pi);;
- : float = 1.

The OCaml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: + and * operate on integers, but +. and *. operate on floats.

# 1.0 * 2;;
Error: This expression has type float but an expression was expected of type
         int

Recursive functions are defined with the let rec binding:

# let rec fib n =
    if n < 2 then n else fib (n-1) + fib (n-2);;
val fib : int -> int = 

# fib 10;;
- : int = 55

你可能感兴趣的:(OCaml体验)