Files
reference/source/_posts/ocaml.md
T
2024-08-08 21:10:46 -06:00

2.8 KiB

title, date, background, tags, categories, intro, plugins
title date background tags categories intro plugins
Ocaml 2024-08-06 00:00:00 bg-[#ec670f]
scientific
functional
Programming
The [Ocaml](https://www.ocaml.org/) cheat sheet is a one-page reference sheet for the Ocaml programming language.
copyCode

Getting Started

hello.ml

# let () =
    let message = "Hello, World!" in
    Printf.printf "%s\n" message

Compile and Run

$ ocamlc -o hello.byte hello.ml
$ ./hello.byte

Build and Run with Dune

$ dune build hello.exe
$ _build/default/hello.exe

Imports

Global Open

# open Hex 

Local Open

# Hex.of_string "hex string" 

# let open Hex in 
   of_string "to hex"

Comments

(* A single line comment *)

(* A multi-line comment
* where we want to explain 
* something complex *)

Documentation Comments

val sum : int -> int -> int
(** [sum x y] returns the sum
 of two integers [x] and [y] *)

Data Types

Predefined Types

Unit

# ()
- : unit = ()

The unit is eqivalent to void

# 5 (* int *)

# 3.14 (* float *)

# true (* bool *)
# false

# 'a' (* char *)

# "a string" (* string *)

# String.to_bytes "hello" (* bytes *)
- : bytes = Bytes.of_string "hello"

Arrays & Lists

Arrays

# [|0; 1; 2; 3|] 

# [|'u'; 's'; 'c'|].(1) (* array access *)
- char = 's'

Arrays are mutable

# let scores = [|97; 85; 99|]
# scores.(2) <- 89 (* update an element *)
- unit = ()

# scores
- : int array = [|97; 85; 89|]

Lists

# [1; 2; 3]
- : int list = [1; 2; 3;]

# ["a"; "str"; "lst"]
- : string list = ["a"; "str"; "lst"]

Lists are immutable

Functions

# let sum x y =
    let result = x + y in
    result
    
# sum 2 3
-: int = 5

Recursive Functions

# let rec factorial n = 
    if n < 1 then 1 else n * factorial (n - 1)

Pipeline

(* find log((x + y)!) *)
# sum 2 3 
  |> factorial
  |> float_of_int
  |> log
- : float = 4.787...

Control Flow and Operators

If Statement

# let is_pos x = 
    if x > 0 then "positive" else "negative"

Pattern Matching

let is_pos x = 
  match x > 0 with 
  | true  -> "positive"
  | false -> "negative"

Operators

=         (* equal to *)
<> or !=  (*not eqaul *)
>         (* greater than *)
<         (* less than *)
>=        (* greater than or eq to *)
<=        (* less than or eq to *)

List Operations

(* an int list*)
# let lst = [1;2;3]

(* map a function to each elem *)
# List.map (fun x -> x + x) lst
- : int list = [2; 4; 6]

# List.mem 4 lst
- : bool = false

# List.find (fun x -> x = 4) lst
Exception: Not_found

Associaton Lists

# let scores = 
    [("math", 91); ("phil", 89); ("stats", 94)]

# List.assoc "stats" scores;;
- : int = 94