elixir-tips
Search…
Part- 1

1. Multiple [ OR ]

This is just the other way of writing Multiple OR conditions. This is not the recommended approach because in regular approach when the condition evaluates to true , it stops executing the remaining conditions which saves time of evaluation unlike this approach which evaluates all conditions first in list. This is just bad but good for discoveries.
1
# Regular Approach
2
find = fn(x) when x>10 or x<5 or x==7 -> x end
3
4
# Our Hack
5
hell = fn(x) when true in [x>10,x<5,x==7] -> x end
Copied!

2. i( term) Elixir Term Type and Meta Data

Prints information about the data type of any given term. Try that in iex and see the magic.
1
iex> i(1..5)
Copied!

3. iex Custom Configuration - iex Decoration

Copy the content into a file and save the file as .iex.exs in your ~ home directory and see the magic. You can also download the file HERE
1
# IEx.configure colors: [enabled: true]
2
# IEx.configure colors: [ eval_result: [ :cyan, :bright ] ]
3
IO.puts IO.ANSI.red_background() <> IO.ANSI.white() <> " ❄❄❄ Good Luck with Elixir ❄❄❄ " <> IO.ANSI.reset
4
Application.put_env(:elixir, :ansi_enabled, true)
5
IEx.configure(
6
colors: [
7
eval_result: [:green, :bright] ,
8
eval_error: [[:red,:bright,"Bug Bug ..!!"]],
9
eval_info: [:yellow, :bright ],
10
],
11
default_prompt: [
12
"\e[G", # ANSI CHA, move cursor to column 1
13
:white,
14
"I",
15
:red,
16
"❤" , # plain string
17
:green,
18
"%prefix",:white,"|",
19
:blue,
20
"%counter",
21
:white,
22
"|",
23
:red,
24
"▶" , # plain string
25
:white,
26
"▶▶" , # plain string
27
# ❤ ❤-»" , # plain string
28
:reset
29
] |> IO.ANSI.format |> IO.chardata_to_string
30
31
)
Copied!
img

4. Creating Custom Sigils and Documenting

Each x sigil call respective sigil_x definition
Defining Custom Sigils
1
defmodule MySigils do
2
#returns the downcasing string if option l is given then returns the list of downcase letters
3
def sigil_l(string,[]), do: String.downcase(string)
4
def sigil_l(string,[?l]), do: String.downcase(string) |> String.graphemes
5
6
#returns the upcasing string if option l is given then returns the list of downcase letters
7
def sigil_u(string,[]), do: String.upcase(string)
8
def sigil_u(string,[?l]), do: String.upcase(string) |> String.graphemes
9
end
Copied!

usage

Load the module into iex
1
iex> import MySigils
2
iex> ~l/HELLO/
3
"hello"
4
iex> ~l/HELLO/l
5
["h", "e", "l", "l", "o"]
6
iex> ~u/hello/
7
"HELLO"
8
iex> ~u/hello/l
9
["H", "E", "L", "L", "O"]
Copied!

5. Custom Error Definitions

Define Custom Error

1
defmodule BugError do
2
defexception message: "BUG BUG .." # message is the default
3
end
Copied!
Usage
1
$ iex bug_error.ex
2
iex> raise BugError
3
** (BugError) BUG BUG ..
4
iex> raise BugError, message: "I am Bug.." #here passing the message dynamic
5
** (BugError) I am Bug..
Copied!

6. Get a Value from Nested Maps Easily

The get_in function can be used to retrieve a nested value in nested maps using a list of keys.
1
nested_map = %{ name: %{ first_name: "blackode"} } # Example of Nested Map
2
first_name = get_in(nested_map, [:name, :first_name]) # Retrieving the Key
3
4
# Returns nil for missing value
5
nil = get_in(nested_map, [:name, :last_name]) # returns nil when key is not present
Copied!
Read docs: Kernel.get_in/2

7. With Statement Benefits

The special form with is used to chain a sequence of matches in order and finally return the result of do: if all the clauses match. However, if one of the clauses does not match, its result of the miss matched expression is immediately returned.
1
iex> with 1 <- 1+0,
2
2 <- 1+1,
3
do: IO.puts "all matched"
4
"all matched"
Copied!
1
iex> with 1 <- 1+0,
2
2 <- 3+1,
3
do: IO.puts "all matched"
4
4
5
## since 2 <- 3+1 is not matched so the result of 3+1 is returned
Copied!

8. Writing Protocols

Define a Protocol

A Protocol is a way to dispatch to a particular implementation of a function based on the type of the parameter. The macros defprotocol and defimpl are used to define Protocols and Protocol implementations respectively for different types in the following example.
1
defprotocol Triple do
2
def triple(input)
3
end
4
5
defimpl Triple, for: Integer do
6
def triple(int) do
7
int * 3
8
end
9
end
10
11
defimpl Triple, for: List do
12
def triple(list) do
13
list ++ list ++ list
14
end
15
end
Copied!

Usage

Load the code into iex and execute
1
iex> Triple.triple(3)
2
9
3
Triple.triple([1, 2])
4
[1, 2, 1, 2, 1, 2]
Copied!

9. Ternary Operator

There is no ternary operator like true ? "yes" : "no" . So, the following is suggested.
1
"no" = if 1 == 0, do: "yes", else: "no"
Copied!

10. Advantage of Kernel.||

When using pipelines, sometimes we break the pipeline for or operation. For example:
1
result = :input
2
|> do_something
3
|> do_another_thing
Copied!
1
# Bad
2
result = (result || :default_output)
3
|> do_something_else
Copied!
Indeed, || is only a shortcut for Kernel.|| . We can use Kernel.|| in the pipeline instead to avoid breaking the pipeline.
The code above will be:
1
result = :input
2
|> do_something
3
|> do_another_thing
4
|> Kernel.||(:default_output) #<-- This line
5
|> do_something_else
Copied!
This above tip is from qhwa
Next