From cdae58c1f3d249f3813512e35be19c5eac01c60e Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Sat, 25 Apr 2020 14:34:10 +0200 Subject: [PATCH] Cheatsheet --- sandbox.exs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 sandbox.exs diff --git a/sandbox.exs b/sandbox.exs new file mode 100644 index 0000000..58ff0da --- /dev/null +++ b/sandbox.exs @@ -0,0 +1,59 @@ +IO.inspect [1, 2, true, "abc"] ++ [3, 2, "abc"] # Concatenate two lists. +IO.inspect [1, 2, true, "abc"] -- [3, 2, "abc"] # List subtraction. +IO.inspect(hd [1, 2, 3]) # Head of a list. +IO.inspect(tl [1, 2, 3]) # Tail of a list. + +tuple = {:ok, "hello"} +IO.inspect(elem tuple, 1) # Get the second element of a tuple. + +IO.inspect "ABC" <> "XYZ" # String concatenation. + +l = [1, 2, 3] +[h | t] = l +IO.inspect {h, t} +IO.inspect [0 | l] +a = 2 +{^a, b} = {2, 42} # Pin operator. +IO.inspect b, label: "b" +{x, x} = {10, 10} # 'x' must be bind to the same value. +IO.inspect x, label: "x" + +str = "hëllö" <> <<0>> # Append a zero to the string (binary). +IO.inspect str, binaries: :as_binaries + +IO.inspect(<<3::4>> === <<0::1, 0::1, 1::1, 1::1>>) # Same binaries: 3 encoded on 4 bits. +IO.inspect(is_binary <<0xFF, 0x5A>>) # true. +IO.inspect(is_binary <<0xFF, 0xF::4>>) # false: binaries must be on a multiple of 8 bits. +IO.inspect(is_bitstring <<0xFF, 0xF::4>>) # true. + +# Pattern matching on binaries. +<> = "über" +IO.inspect(x === ?ü) # true. + +# 'charlist': the string in Erlang. +IO.inspect('hëllò', charlists: :as_lists) +IO.inspect(to_string('hëllò') == "hëllò") # true. +IO.inspect('hëllò' == to_charlist("hëllò")) # true. + +# keyword list. +IO.inspect([{:a, 1}, {:b, 2}] === [a: 1, b: 2]) # true. +IO.inspect(a: 1, b: 2, c: 3) # Brackets omitted. + +# Maps. +map = %{:a => 1, 2 => :b} +IO.inspect map[:a] # Print 1. +IO.inspect map.a # Special syntax with atom key, print 1. +IO.inspect map[2] # Print ':b'. +IO.inspect map[3] # Print 'nil'. +%{:a => a} = map +IO.inspect a # Print 1. +IO.inspect %{map | 2 => "two"} # Updating 'map'. + +# Module. +defmodule Math do + def sum(a, b) do + a + b + end +end + +IO.inspect Math.sum(1, 2) \ No newline at end of file -- 2.43.0