Ocaml Cheatsheet

974




sample program

print_string "Hello world!"
  • print_string : is used to print the given string

  • (* Single line comments *)

  • (* Multi

    * line

    * comment.

    *)

Data types

ClassificationData-types
Basic data typesint, float, bool, char, string, unit.
Sophisticated data typestuples, arrays, lists, sets, hash tables, queues, stacks, data streams.

Variables

let varible-names = value

Example

let a = 100;

Conditional Statements

1. If

if boolean-condition then (* code if condition is true *)

2. If-else

if boolean-condition then (* code if condition is true*) else (* code if condition is false*)

Loops

1. While

while boolean-condition do
  (* code *)
done

2. For

for var = start-value to end-value do
  (* code *)
done
  
for var = start-value downto end-value do
  (* code *)
done

Lists

let listName= [item1;item2;item3]

Tuple

let tupleName  : datatype * datatype * ... = (value, value, ...);;

Functions

How to define a function

let funcName (arguments) =
    (* code *)

Call a function

funcName arguments

Example

(* Defining the function*)
let sum a b =
 (a+b)

(* calling a function)
sum 3 7