Basics
Object-oriented programming uses Classes that define the mold for objects which are instances of that Class. Each object thus has the methods of that class. Data is then passed to those objects and manipulated according to the Class methods.
Functional programming uses Module Functions with sub functions instead of methods. Data is passed through the functions as immutable data.
Elixir Compiler Steps:
- Read file
- Tokenize
- Parse (builds Abstract Syntax Tree [has precedence])
- Expand Macros
- Apply Rewrite Rules
- Lower Elixir AST to Erlang AST
Erlang Compiler 7. Compile Erlang AST to Core AST 8. Core Optimizations & True Inlining 9. Compile Pattern Matching
Kernel Erlang 10. Run Kernel Optimizations 11. Generate and Optimize Assembly 12. Generate bytecode 13. Write .beam file
Aliases
`` adds the prefix
alias Enum, as: E
E.each(["one", "two", "three"], &(IO.puts(&1))
Syntax
_anonymous_variable
is used to tell that that variable is unused. For example: {:ok, _contents}
arguments -> expression
Module.__info__(:functions)
exposes the functions of the Module
method!
returns error if there is an error
Elixir Expressions
{function, metadata, arguments}
Keywords
[atom: data, "string atom": data]
is the same as [{:atom, data}, {"string atom": data}]
Reuse Directives: alias, require, import, use
alias
saves you from writing the ancestors
alias VeryLongAppName.{Module1, Module2}
Module1.method
# instead of VeryLongAppName.Module1.method
use Module
allows the used Module to inject stuff
import Module
imports the methods used by that Module so that it can be used in the current Module without referencing it all the time.
require Module
this lets you use the methods in the Module but you have to add that Module’s name
use Module first requires module and then calls the using macro on Module.
Consider the following:
defmodule ModA do defmacro using(_opts) do IO.puts “You are USING ModA” end
def moda() do IO.puts “Inside ModA” end end
defmodule ModB do use ModA
def modb() do IO.puts “Inside ModB” moda() # <- ModA was not imported, this function doesn’t exist end end
This will not compile as ModA.moda() has not been imported into ModB.
The following will compile though:
defmodule ModA do defmacro using(_opts) do IO.puts “You are USING ModA” quote do # <– import ModA # <– end # <– end
def moda() do IO.puts “Inside ModA” end end
defmodule ModB do use ModA
def modb() do IO.puts “Inside ModB” moda() # <– all good now end end As when you used ModA it generated an import statement that was inserted into ModB.
Share