Skip to content

Instantly share code, notes, and snippets.

@jmikkola
Created February 4, 2017 21:12
Show Gist options
  • Save jmikkola/9889a7fe45240a03c550b10e95498cb2 to your computer and use it in GitHub Desktop.
Save jmikkola/9889a7fe45240a03c550b10e95498cb2 to your computer and use it in GitHub Desktop.

Erlang Cheat Sheet

(this is a work in progress)

Running Erlang

Getting the interpreter in ubuntu: sudo apt-get install erlang. To get native compliation capability, also install erlang-base-hipe.

Starting the interpreter: erl. To exit: Ctrl-g then q enter.

File extension: .erl.

Compiling a module from the shell (assuming the module is in the current directory): c(module_name). If hipe is installed, native compliation can be done with c(module_name, [native]).

Working with Erlang

Add .beam to the project's .gitignore.

Emacs

  • Start a shell: C-c C-z
  • Compile file: C-c C-k

Syntax

Statements end in ..

Variables start with an upper case letter, atoms start with a lowercase one.

Math and Logic

  • Mod operator: 5 rem 2
  • Integer division: 5 div 2
  • Equality testing: x =:= 2
  • Pattern patching: {foo, X} = {foo, 123}. (X becomes 123)

Functions

  • Functions with the same name but a different number of arguments are considered different functions.
    • e.g. add/2 vs add/3 for referring to the 2- and 3-argument variants

Example:

add(A,B) ->
    A + B.

Data structures

Tuples

Point = {123,456}. {X,Y} = Point. {X,_} = Point.

Lists

Lists can be mixed-type.

  • List of numbers: [1, 2, 3]
  • Prepend to a list [0 | numbers]
  • Get head and tail: [H, T] = Numbers.
  • Comprehensions: [2*N || N <- [1,2,3,4]].
  • Range: lists:seq(1, 4).

Code structure

Modules

  • Declare a module called foo: -module(foo).
  • Export a function: -export([add/2]).
  • Import a module and some functions: -import(foo, [add/2]).
  • Calling a function from a module: foo:add(1,2).

Types

  • Strongly typed (no implicit type conversions)
  • Dynamically typed

Conversion

  • erlang:list_to_integer("54") (strings are basically lists of numbers in erlang)
  • erlang:integer_to_list(54)
  • erlang:atom_to_list(true)

Interesting types

  • Atoms (e.g. foo, true)
  • Bit strings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment