Elixir Introduction

Installation

Go to Elixir to get the download introducton.

Install Elixir on Ubuntu

run commands:

1
2
3
4
wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
sudo apt-get update
sudo apt-get install esl-erlang
sudo apt-get install elixir

Verify installation

  1. into interactive command line by iex command:
1
2
3
4
5
$ iex
Erlang/OTP 19 [erts-8.1] [source-e7be63d] [64-bit] [smp:2:2] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
  1. quit by double ctrl - c
    1
    2
    3
    4
    5
    Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
    iex(1)>
    BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
    (v)ersion (k)ill (D)b-tables (d)istribution
    ^C%

The first program

There’re 2 type of suffix of elixir source file

  1. *.ex: will be compiled
  2. *.exs: used to as test file
  1. source file hello.exs, content like below

    1
    IO.puts 'Hello, world!'
  2. run command elixir hello.exs and get the output

    1
    2
    $ elixir hello.exs
    Hello, world!

模式匹配

赋值

Elixir可以找到一种方式让等号的左边等于右边,则执行成功

所以赋值语句并不是其他语言的赋值那样,例子如下:

1
2
3
4
5
6
iex(1)> a = 1
1
iex(2)> 1 = a
1
iex(3)> 2 = a
** (MatchError) no match of right hand side value: 1

用_(下划线)忽略匹配值
下划线是特殊通配符,声称“我可以接受任何值”

  • 在匹配过程中,变量一旦被绑定为某一个值,该值在匹配其余部分的时候就会保持不变
  • 强制让变量的已有值参与匹配,可使用^(脱字节)前缀
0%