開始 Elixr! [上]

2015-07-24, Friday
elixir erlang

從半年前開始就開始關注Elixir這個語言。
它提供了不少方便的功能還有高效能容錯分散式的好處,
因為發明者是Ruby on Rails的core Developer所以許多語法和Ruby很相似,
Rubyist的話可以更容易的進入它的世界,它也是一個Funtional Language(函數式語言)。

Alt text

###如何安裝

1
2
3
4
5
#Mac OS X
brew update
brew install elixir
#Macports
sudo port install elixir

其他平台安裝可以參考:http://elixir-lang.org/install.html

###基本型態

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Strings
"hello" # string
'hello' # char list

# Multi-line strings
"""
I'm a multi-line
string.
"""
# Strings are all encoded in UTF-8:
"héllò" #=> "héllò"

#String相加
'hello ' ++ 'world'  #'hello world'
"a" <> "b" #ab

# Strings are really just binaries, and char lists are just lists.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c]   #=> 'abc'

# `?a` in elixir returns the ASCII integer for the letter `a`
?a #=> 97

# 數字
3    # integer
0x1F # integer
3.0  # float

# Atoms, `:`開頭 , 變數名稱就是變數本身
:hello
:"變數"

<<1,2,3>> # binary

# Tuples that are stored contiguously in memory.
{1,2,3} # tuple
# Lists that are implemented as linked lists.
[1,2,3] # list

[1,2,3] ++ [4,5]     #=> [1,2,3,4,5]
1..3 # range -> [1,2,3]

###Pattern Match
Pattern Match是函數式語言的一個核心精神,
它可以透過match的方式對建構函式執行相對應的運算

1
2
3
4
5
6
7
8
9
#這是最經典的一個Pattern Match範例
[h|e] = [1,2,3,4]
#h 將會取得1
#e 將會取的[2,3,4]
#已以上的例子, 我們可以實現遞迴的想法
# [h|e] = e ....

[a,b,c] = ["a","b","c"]
{a,b,c} = ["a","b","c"]

控制程序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if false do
  "我是假的"
else
  "我不是假的"
end

unless true do
  "我是真的"
else
  "我不是真的"
end

test = {:one, :two}
case test do
  {:four, :five} ->
    "This won't match"
  {:one, x} ->
    "This will match and bind `x` to `:two`"
  _ ->
    "This will match any value"
end

try do
  throw(:hello)
catch
  message ->
    "Got #{message}."
  _ ->
    "catch all"
after
  IO.puts("I'm the after clause.")
end

其他

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#透過h查詢某一個function的document info
h IO.puts

#Hello World in Elixir
IO.puts("Hello World!")

#在Pattern Match時如果有部分的資料,你不在意想要丟掉的部分你可以透過"_"去忽略它

[head | _ ] = [1,2,3]
[head | _tail ] = [:a, :b, :c]

# Anonymous functions
square = fn(x) -> x * x end
square.(5) #=> 25

更多基礎介紹可以參考官網,我覺得它寫得非常完整!

可能有興趣的文章: