Elixir - DailyTrip [001.2] Basic Elixir Syntax and Concepts

Basic Syntax

Atoms

iex(1)> :this_is_a_constant
:this_is_a_constant
iex(2)> SoIsThis
SoIsThis

Booleans

iex(3)> :true == true
true
iex(4)> :false == false
true

Numbers

iex(5)> 1 + 2
3
iex(6)> 2.0 + 3
5.0

iex(7)> 2 - 1
1
iex(8)> 3 - 2.0
1.0

iex(9)> 2 * 3
6
iex(10)> 3.0 * 2
6.0

iex(11)> 4 / 3
1.3333333333333333
iex(12)> 4 / 2
2.0

iex(13)> div(4, 2)
2

iex(14)> rem(5, 2)
1

Strings

iex(15)> "Hello " <> "world"
"Hello world"

iex(16)> who = "josh"
"josh"
iex(17)> "Hello #{who}"
"Hello josh"

iex(18)> String.upcase("José")
"JOSÉ"

Pattern Matching

iex(1)> foo = "bar"
"bar"

iex(2)> "bar" = "bar"
"bar"
iex(3)> "baz" = "bar"
** (MatchError) no match of right hand side value: "bar"

Tuples

iex(18)> {:like, "this"}
{:like, "this"}

iex(19)> person = {"Josh", "Adams", 33}
{"Josh", "Adams", 33}
iex(20)> first = elem(person, 0)
"Josh"
iex(21)> last = elem(person, 1)
"Adams"
iex(22)> age = elem(person, 2)
33

iex(23)> put_elem(person, 2, 34)
{"Josh", "Adams", 34}

iex(24)> person
{"Josh", "Adams", 33}

Very frequently, tuples are used alongside pattern matching. Oftentimes functions will return one of either:

iex(25)> {:ok, "some value"}
{:ok, "some value"}
iex(26)> {:error, "something went wrong"}
{:error, "something went wrong"}

Collections

List

iex(25)> [1, 2, 3]
[1, 2, 3]

iex(26)> [1 | [2, 3]]
[1, 2, 3]

iex(27)> [1 | []] == [1]
true
iex(28)> hd([1, 2, 3])
1
iex(29)> tl([1, 2, 3])
[2, 3]

iex(32)> 'abc'
'abc'

iex(33)> [97, 98, 99]
'abc'
iex(34)> [97, 98, 99] == 'abc'
true

Keyword Lists

When specifying a small set of options, it's common to use Keyword Lists. These are lists of 2-tuples where the first element is an atom.

iex(35)> [{:foo, "bar"}, {:baz, "whee"}]
[foo: "bar", baz: "whee"]
iex(36)> [foo: "bar", baz: "whee"]
[foo: "bar", baz: "whee"]

You can fetch particular elements out with the following syntax:

iex(37)> [foo: "bar", baz: "whee"][:foo]
"bar"```
### Maps
```elixir
iex(38)> %{foo: "bar", baz: "whee"}
%{baz: "whee", foo: "bar"}

iex(39)> %{foo: "bar", baz: "whee"}.baz
"whee"
iex(40)> %{foo: "bar", baz: "whee"}[:foo]
"bar"

Regular Expressions

iex(42)> ~r/foo/
~r/foo/
iex(43)> Regex.match?(~r/foo/, "This contains foo")
true
iex(44)> Regex.match?(~r/foo/, "This does not")
false

Anonymous functions

iex(45)> add_two = fn x -> x + 2 end
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(46)> add_two.(3)
5

Scripting

Making a script

vim foo.exs
add_two = fn x ->
  x + 2
end

# Here we'll use `IO.puts`, which just outputs to the console
IO.puts add_two.(3)
elixir foo.exs
# => 5

Summary

We covered most of the basic syntax of Elixir.

Resources

  • Basic Types
  • Linked Lists

你可能感兴趣的:(Elixir - DailyTrip [001.2] Basic Elixir Syntax and Concepts)