-
-
Save breunigs/da728183bc843877856155eb678aad84 to your computer and use it in GitHub Desktop.
Vortrags"folien" zu Pattern Matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assignment | |
x = 2 | |
[x, y] = [3, 4] | |
# perl -e '($one, $two) = (1, 2); print $two;' | |
# ruby -e "one, two = 1, 2; puts two" | |
# Assignment++ | |
[x, [y, z]] = [5, [6, 7]] | |
%{hashes: yay} = %{hashes: "yay"} | |
%{omg: %{what: [are, you]}, doing: %{please: stahp}} = %{omg: %{what: ["are", "you"]}, doing: %{please: "wtf"}} | |
# Auch für Strings (Character Listen) | |
"/" <> path = "/nnev/is/awesome" | |
# Wozu? | |
## 1. Assert / Guard | |
true = false | |
some_fun = fn -> false end | |
true = some_fun.() | |
## 2. Offensichtlich: Variablen rausziehen | |
{status_code, body, headers} = some_http_call() | |
## 3. Mit Error Handling: | |
case some_http_call() do | |
{:ok, some_response} -> IO.puts "yay!" | |
{:error, some_error} -> IO.puts "oh no!" | |
_anything_else -> IO.puts ":(" | |
end | |
## 4. Funktionen (statt if) | |
defmodule Demo do | |
def user_data(user, requester ) | |
def user_data(%{id: id}, %{id: id} ), do: "alles über #{id}" | |
def user_data(%{id: id}, %{permission: :admin}), do: "auch alles über #{id}" | |
def user_data(%{id: id}, %{id: other_id} ), do: "wenig über #{id}, weil #{other_id} doof ist" | |
def user_data(_user, _requester ), do: "nein.jpg" | |
end | |
# Demo.user_data(%{id: 1}, %{id: 1}) | |
# Demo.user_data(%{id: 1}, %{id: 2}) | |
# Demo.user_data(%{id: 1}, %{id: 2, permission: :admin}) | |
## 4. Funktionen (defaults) | |
defmodule Demo2 do | |
def absolutify(url_or_path) | |
def absolutify("http://" <> _path = url), do: url | |
def absolutify("/" <> path ), do: "http://nnev.de/#{path}" | |
end | |
# Unter der Haube | |
* Primitive Operationen | |
* If / Else (bzw. switch) | |
# Mehr? | |
https://stackoverflow.com/questions/586362/pattern-matching-implementation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment