Elixir tuple, struct and map



Elixir Tuple

To declare a tuple, you simply declare

d = {1, "b", :c"}

And to retrieve it use elem function.

 elem(d, 0) // return 1
 elem(d, 1) // return "b"

You can use Tuple function to help out with tuple manipulation.

Elixir Map

Sometimes it can be confusing because we are declaring  map using the same operator {}.

Map are key value pair.

To declare, simple type

a = %{  a  => 1, b => 2 } // you can't do this

 a = %{"a" => 1, "b" => 2} // ok

if you're using ATOM, you can declare as follows (notice the change of parameter from => (arrow key) to ":" below) :-

 l = %{a: 1, b: 2 }

Accessing map (Non-Atom Map), you can simply, 

 a["a"] // output 1 
 a["b"] // output 2 

Or you can use 

Map.get(a, "a") // output 1 
Map.get(a, "b") // output 2

Accessing Atom map 
If your map is declare this way :  
 l = %{a: 1, b: 2 } 

l[:a] //output 1 
Map.get(l, :a) // output 1 

Elixir struct 

struct is used to define a custom data structure. It is really extension of Elixir's Map.
defstruct is used to do this.


defmodule Test do
  defstruct name: "Angelina", age: 27
end

And to instantiate the structure, you write (with the module name in front) like so;

 %Test{}  # Outputs %Test{age: 27, name: "Angelina"}
%Test{name: "Vincent"} # Outputs : %Test{age: 27, name: "Vincent"}

When you're dealing with Ecto, you will use this alot. 

Just thought i outline the ABC of working with tuple, maps and struct which could look pretty similar. 






Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm