Skip to content

Instantly share code, notes, and snippets.

@drewkerrigan
Last active February 6, 2018 13:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drewkerrigan/4ec6865cf96ad10495b072c23fb3a038 to your computer and use it in GitHub Desktop.
Save drewkerrigan/4ec6865cf96ad10495b072c23fb3a038 to your computer and use it in GitHub Desktop.
Erlang / Elixir in 5 Minutes or Less

Learning Erlang / Elixir Basics

Primitives

Erlang only has a few primitives that you need to worry about. Here they are below with corresponding Elixir examples.

  1. integer: Erlang: 123, Elixir: 123
  2. float: Erlang: 123.5, Elixir: 123.5
  3. atom: Erlang: hello, Elixir: :hello
  4. binary: Erlang: <<"hello">> or <<10,20>>, Elixir: "hello" or <<10,20>>
  5. fun: Erlang: fun (X) -> X+1 end., Elixir: fn (x) -> x+1 end
  6. pid: Erlang: <0.57.0>, Elixir: #PID<0.80.0>

Lists, Etc

  1. list: Erlang: "hello" or [1, 2, 3], Elixir: 'hello' or [1, 2, 3]
  2. tuple: Erlang: {hello, <<"world">>, 123} or {ok, true}, Elixir: {:hello, "world", 123} or {:ok, true}

Modules

Erlang

-module(hello_world).

say_hello(Contents) when is_binary(Contents) ->
  Str = "hello " ++ binary_to_list(Contents),
  list_to_binary(Str).

Elixir

defmodule HelloWorld do
  def say_hello(contents) when is_string(Contents) do
    "hello" <> contents
  end
end

Control Flow, Pattern Matching, Looping

Erlang

say_hello({value, _}) -> "Called `say_hello/1` with a tuple!".
  
say_hello(_) -> "Called `say_hello/1` with something other than a tuple!".
  
match_with_case(V) ->
  case V of
    {ok, _} -> "V had the format `{ok, term)`";
    {error, _} -> "V had the format `{error, term}`"
  end.
  
%% Iterate a list like iterate([1, 2, 3], []), the result should be [2, 3, 4]
iterate([], Accumlator) -> lists:reverse(Accumulator).
iterate([Head | Rest], Accumlator) -> iterate(Rest, [Head + 1 | Accumulator).

Elixir

def say_hello({:value, _}), do: "Called `say_hello/1` with a tuple!"
def say_hello(_), do: "Called `say_hello/1` with something other than a tuple!"
  
def match_with_case(v) do
  case v do
    {:ok, _} -> "v had the format `{:ok, :term)`"
    {:error, _} -> "v had the format `{:error, :term}`"
  end
end

## Iterate a list like iterate([1, 2, 3], []), the result should be [2, 3, 4]
def iterate([], accumlator), do: Enum.reverse(accumulator)
def iterate([head | rest], accumlator), do: iterate(rest, [head + 1 | accumulator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment