Data Types
Elixir uses dynamic types based on Erlang where the type is determined by the data entered in the variable.
Tuples for fixed number of elements
{"string", integer, f.loat, :atom}
elem(variable, position_in_index)
to extract values in the tuple
a = {"Lam", 143}
elem(a, 1)`
# 123
List for non-fixed number of elements
a = [1, 2, 3]
length(a)
# 3
b = [4, 5]
b ++ a
Enum
, in
, [head | tails]
works with lists
Enum.at(a, 2)
# 3
3 in a
# true
head
is the first element in the list
tail
is made up of the non-head elements
Map for key-values %
Unstructured map
%{a => a, b => b}
z = %{a => a, b => b}
z[a] # gets a
a
Structured map
%{a: "A", b: "B"}
Character List
Binary «1, 2, 3»
AST is a data structure composed of the following elements:
Quote Literals
- :atom
- 1nteger
- f.loat
- “string”
- [“l”, “i”, “s”, “t”]
- {“2-element”, :tuple}
3-Element Tuples
- variables
{name, meta, context}
- calls
{function, context/meta, arguments}
“Calls” such as sum(1, 2, 3)
create ASTs such as {:sum, meta, [1, 2, 3]}
.
%{map}
is_integer() is_float()
Atom
An atom’s name is the same as its value
Atom
:atom_name
:Atom_name
:"Atom name"
convert string to float
String.split
- converts string into a list with each word put in quotes, separated by a comma
"asdfasd" |> String.split
String.to_integer
and String.to_float
- converts a string-integer and string-float into an integer and float
"123" |> String.to_integer
"123.123" |> String.to_float
Integer.parse, Float.parse
123 |> Integer.parse
Convert string to integer or float
# returns tuple e.g. {123.45, ""}
Integer.parse(n)
Float.parse(n)
# returns integer
String.to_integer(n)
String.to_float(n)
Decimal.new(n) |> Decimal.to_integer
Decimal.new(n) |> Decimal.to_float
Example
"1.0 1 3 10 100" |> String.split |> Enum.map(fn n -> Float.parse(n) |> elem(0) end)
[1.0, 1.0, 3.0, 10.0, 100.0]
Convert float to string
n |> to_string([decimals: 2, compact: true])
Convert float to charlist
n |> to_charlist()