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.
integer
: Erlang:123
, Elixir:123
float
: Erlang:123.5
, Elixir:123.5
atom
: Erlang:hello
, Elixir::hello
binary
: Erlang:<<"hello">>
or<<10,20>>
, Elixir:"hello"
or<<10,20>>
fun
: Erlang:fun (X) -> X+1 end.
, Elixir:fn (x) -> x+1 end
pid
: Erlang:<0.57.0>
, Elixir:#PID<0.80.0>
Lists, Etc
list
: Erlang:"hello"
or[1, 2, 3]
, Elixir:'hello'
or[1, 2, 3]
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)