Ocaml Cheat Sheet



Ocaml Programming language cheatsheet gives you a quick reference to code syntax with examples makes it handy while coding. Paper Name Page Views Download Count Added Date; cs3110 ocaml cheat sheet: 335: 119: 19 Apr, 2012: ocaml emacs mode cheat sheet: 304: 52: 19 Apr, 2012: ocaml standard library cheat sheet.

  1. Ocaml Cheat Sheet 2020
  2. Ocaml Cheat Sheet Pdf
  3. Ocaml Cheat Sheet 2019
  4. Ocaml Cheat Sheet
  5. Ocaml Cheat Sheet Printable

NOTE: this manual is a work in progress. Please let us know if you thinksomething is missing by filing anissue, or join our Discord server.

Here is a comparison between common Erlang and Elixir syntaxes and the OCamland Reason syntaxes that are supported by Caramel.

Types

Variants and Unions

Erlang:

Elixir

OCaml

Records

Erlang:

Elixir

OCaml

Expressions and Values

Atoms

ErlangElixirOCamlReasonDescription
ok:ok`ok`okAtoms in Caramel are treated as polymorphic variants.
'ok':'ok'------Quoted atoms are unsupported in Caramel.
ErlangElixirOCamlReason
% comment# comment(* comment *)// comment

Variables

ErlangElixirOCamlReason
A = 1a = 1let a = 1let a = 1
A2 = A + 1a = 1let a' = a + 1let a' = a + 1

Binary Strings, and Charlists

ErlangElixirOCamlReason
<<'binary'>>'binary''binary''binary'
'string''binary'['b'; 'i'; 'n'; 'a'; 'r'; 'y']['b', 'i', 'n', 'a', 'r', 'y']

Function Calls

Ocaml Cheat Sheet 2020

ErlangElixirOCamlReason
Lambda()lambda.()lambda ()lambda()
local()local()local ()local()
mod:fn()Mod.fn()Mod.fn ()Mod.fn()
A:F()apply(A, F, [])------

Dynamically dispatched calles are not supported in Caramel, because we can'tknow the type of the arguments they will have, or the type of the value theywould return.

If expressions

Erlang:

Elixir

OCaml

Reason

Match / Case / Switch expression

Cheat

Erlang:

Elixir

OCaml

Reason

Ocaml Cheat Sheet Pdf

The 'Unknown:'s below indicate that an entry is incomplete.

Cheat

Ocaml Cheat Sheet 2019

  • either the entry exist in the language, and please tell.
  • either the entry doesn't exist in the language, and please tell so.The entry will be marked as such and won't appear as missing anymore.

Ocaml Cheat Sheet

  • Category: Object Oriented, Functional, Statically typed
  • Various

    nothing neededbreaking lines (useful when end-of-line and/or indentation has a special meaning)
    (* ... *)commenting (nestable)
    < > <= >=comparison
    min / maxcomparison (min / max (binary or more))
    comparecomparison (returns 3 values (i.e. inferior, equal or superior))
    (** ... *)documentation comment
    = <>equality / inequality (deep)
    !=equality / inequality (shallow)
    Gc.full_major()force garbage collection
    ( ... )grouping expressions
    begin ... endgrouping expressions
    case-sensitivetokens (case-sensitivity (keywords, variable identifiers...))
    [_A-Z][_a-zA-Z0-9']*tokens (constant regexp (if different from variable identifier regexp))
    [_a-z][_a-zA-Z0-9']*tokens (type regexp (if different from variable identifier regexp))
    [_a-z][_a-zA-Z0-9']*tokens (variable identifier regexp)
    underscores for functions / types, unclear for modules / constructorstokens (what is the standard way for scrunching together multiple words)
    <-variable assignment or declaration (assignment)
    let v = e invariable assignment or declaration (declaration)

  • Functions

    (>) apartial application (in the examples below, a normal call is 'f(a,b)') (give the first argument to operator '>')
    f apartial application (in the examples below, a normal call is 'f(a,b)') (give the first argument)
    fun a b -> ...anonymous function
    f a b ...function call
    f()function call (with no parameter)
    let f para1 para2 = ...function definition
    no syntax needed(1)function return value (function body is the result)

  • Control Flow

    try a with exn -> ...exception (catching)
    raiseexception (throwing)
    if c then ...if_then
    if c then b1 else b2if_then_else
    for i = 10 downto 1 do ... doneloop (for each value in a numeric range, 1 decrement)
    for i = 1 to 10 do ... doneloop (for each value in a numeric range, 1 increment (see also the entries about ranges))
    while c do ... doneloop (while condition do something)
    multiple selection (switch)
    ;sequence

  • Types

    :annotation (or variable declaration)
    e :> tcast (upcast)
    type n = tdeclaration
    constness is the defaultmutability, constness (type of a constant value)
    T refmutability, constness (type of a mutable value)

  • Object Oriented & Reflexivity

    classclass declaration
    inheritinheritance
    object#method paramethod invocation
    object#methodmethod invocation (with no parameter)
    {< >} or Oo.copy oobject cloning
    new class_name ...object creation

  • Package, Module

    module P = struct ... enddeclare
    automatically done based on the file namedeclare
    declare (selective export)
    open pimport (everything into current namespace)
    automatically done(2)import (package (ie. load the package))
    .package scope

  • Strings

    s.[n]accessing n-th character
    chrascii to character
    'z'character 'z'
    codecharacter to ascii
    charcharacter type name
    subextract a substring
    rindexlocate a substring (starting at the end)
    all strings allow multi-line stringsmulti-line
    Marshal.to_stringserialize (marshalling)
    print_stringsimple print (on strings)
    print_endline(3)simple print (on strings)
    printfsimple print (printf-like)
    sprintfsprintf-like
    ^string concatenation
    = <>string equality & inequality
    lengthstring size
    'n'strings (end-of-line (without writing the real CR or LF character))
    '...'strings (with no interpolation of variables)
    stringtype name
    Marshal.from_stringunserialize (un-marshalling)
    uppercase / lowercaseupper / lower case character
    uppercase/lowercaseuppercase / lowercase / capitalized string

    Unknown:

    strings (with interpolation of variables)
  • Booleans

    falsefalse value
    not(4)logical not
    || / &&logical or / and (short circuit)
    truetrue value
    booltype name

  • Bags and Lists

    split2 lists from a list of couples
    ::adding an element at the beginning (list cons) (return the new list (no side-effect))
    tlall but the first element
    fold_leftf(... f(f(init, e1), e2) ..., en)
    fold_rightf(e1, f(e2, ... f(en, init) ...))
    findfind an element
    hdfirst element
    iterfor each element do something
    memis an element in the list
    existsis the predicate true for an element
    for_allis the predicate true for every element
    iteriiterate with index
    concatjoin a list of strings in a string using a glue string
    find_allkeep elements (matching)
    filterkeep elements (matching)
    @list concatenation
    [ a ; b ; c ]list constructor
    flattenlist flattening (one level depth)
    combinelist of couples from 2 lists
    lengthlist size
    a.(i)list/array indexing
    nthlist/array indexing
    assoclookup an element in a association list
    partitionpartition a list: elements matching, elements non matching
    revreverse
    sort(5)sort
    maptransform a list (or bag) in another one
    map2transform two lists in parallel
    a listtype name

    Unknown:

    split a list
  • Various Data Types

    finddictionary (access: read)
    add, replacedictionary (access: write)
    memdictionary (has the key ?)
    removedictionary (remove by key)
    Hashtbl.tdictionary (type name)
    type typ = N1 | N2 | ...enumerated type declaration
    Noneoptional value (null value)
    optionoptional value (type name)
    Some voptional value (value)
    .record (selector)
    type typ = { n1 : typ1; n2 : typ2 }record (type declaration)
    :=reference (pointer) (assigning (when dereferencing doesn't give a lvalue))
    refreference (pointer) (creation)
    !(6)reference (pointer) (dereference)
    a, b, ctuple constructor
    typ1 * ... * typntuple type
    type typ = N1 of typ1 | N2 of typ2 | ...union type declaration

    Unknown:

    optional value (null coalescing)
  • Mathematics

    + +. / - -. / * *. / / /.(7)addition / subtraction / multiplication / division
    land / lor / lxorbitwise operators (and / or / xor)
    lnotbitwise operators (bitwise inversion)
    lsl / lsr or asrbitwise operators (left shift / right shift / unsigned right shift)
    **exponentiation (power)
    log10logarithm (base 10)
    loglogarithm (base e)
    modmodulo (modulo of -3 / 2 is -1)
    - -.negation
    1000., 1E3numbers syntax (floating point)
    1_000, 10_00, 100_0numbers syntax (integer thousand-separator)
    0b1, 0o7, 0xfnumbers syntax (integers in base 2, octal and hexadecimal)
    1000numbers syntax (integers)
    negation firstoperator priorities and associativities (exponentiation vs negation (is -3^2 equal to 9 or -9))
    Random.intrandom (random number)
    Random.init, Random.self_initrandom (seed the pseudo random generator)
    sqrt / exp / abssquare root / e-exponential / absolute value
    sin / cos / tantrigonometry (basic)
    asin / acos / atan(8)trigonometry (inverse)
    int_of_float / / floor / ceiltruncate / round / floor / ceil
    floattype name (floating point)
    inttype name (integers)

Remarks

  • (1) in Matlab, only for anonymous function
  • (2) using a correspondance from the package name to the file name
  • (3) adding an end-of-line
  • (4) Smalltalk: postfix operator
  • (5) in Scheme, not standard, but nearly standard
  • (6) prefix
  • (7) with mathematical priorities
  • (8) Ruby >= 1.7

Ocaml Cheat Sheet Printable

Pixel
This work is licensed under a Creative Commons Attribution-ShareAlike 2.0 Generic License.
Generated from syntax-across-languages.html.pl
$Id: syntax-across-languages.html.pl 408 2008-08-29 08:32:23Z pixel $