Elixir
Elixir
Compiling and Running Elixir Code
elixircis used to compile elixir files.
Some Important Points about Elixir
Everything is an expression which returns a value, this includes control structures like if, unless, case, etc.
Variables are mutable but memory used by them is immutable.
fn_name?is used to indicate that function is going to return a boolean value.=fnname! = is used to indicate that function is going to raise an exception.
defanddefmoduleare macros.Last statement in a function is the return value.
Parenthesis are optional in function calls.
Function artiy is the number of arguments it takes. So everywhere on the internet or docs you will see
fn_name/arity.Default values can be provided using
\\operator. Exampledef greet(name, greeting \\\\ "Hello") do ... end. This is equivalent to writing a function with less arity and then calling it from the function with more arity. This actually creates multiple functions with different arities. It is not possible for a single function to have multiple arities.defpis used to define private functions. Private functions can only be called from the module they are defined in.importinside adefmoduleblock imports the functions from the module into the current module. This is different fromimportoutside adefmoduleblock which imports the functions into the current namespace.aliasis used to alias a module. Examplealias MyApp.User, as: User.alias abc.defis equivalent toalias abc.Def, as: Def.@abcis a module attribute. It is used to store metadata about the module. It is used to store compile time constants. It is also used to store documentation.@moduledocis used to store documentation for the module.@docis used to store documentation for a function.@specis used to store the function signature(type).
Type System in Elixir
Elixir is dynamically typed. Static typing is in development.
There are numbers,
floatsandintegers.:atomis a constant whose name is its value. They are used to reference modules, functions, etc. They are also used as keys in maps.There is another way to write atoms,
:"atom". This is useful when atom name contains special characters.Can also write with simple capital letter and in that case we dont require colon. Example
:Elixir.Atomis same asAtombecauseElixiris the default namespace.
:trueand:falseare atoms.nilis also an atom.
Constructors, Reducers and Converters
Constructor are functions that create a new data structure. Example
Map.new/0,Map.new/1,Map.new/2, etc.Reducers are functions that reduce a data structure to a single value. Example
Enum.reduce/2,Enum.reduce/3, etc.Converters are functions that convert a data structure to another data structure. Example
Enum.to_list/1,Enum.to_map/1, etc.