加载中...

elixir


其中 Y=elixir

源代码下载: learnelixir-cn.ex

Elixir 是一门构建在Erlang VM 之上的函数式编程语言。Elixir 完全兼容 Erlang, 另外还提供了更标准的语法,特性。

  1. # 这是单行注释, 注释以井号开头
  2. # 没有多行注释
  3. # 但你可以堆叠多个注释。
  4. # elixir shell 使用命令 `iex` 进入。
  5. # 编译模块使用 `elixirc` 命令。
  6. # 如果安装正确,这些命令都会在环境变量里
  7. ## ---------------------------
  8. ## -- 基本类型
  9. ## ---------------------------
  10. # 数字
  11. 3 # 整型
  12. 0x1F # 整型
  13. 3.0 # 浮点类型
  14. # 原子(Atoms),以 `:`开头
  15. :hello # atom
  16. # 元组(Tuple) 在内存中的存储是连续的
  17. {1,2,3} # tuple
  18. # 使用`elem`函数访问元组(tuple)里的元素:
  19. elem({1, 2, 3}, 0) #=> 1
  20. # 列表(list)
  21. [1,2,3] # list
  22. # 可以用下面的方法访问列表的头尾元素:
  23. [head | tail] = [1,2,3]
  24. head #=> 1
  25. tail #=> [2,3]
  26. # 在elixir,就像在Erlang, `=` 表示模式匹配 (pattern matching)
  27. # 不是赋值。
  28. #
  29. # 这表示会用左边的模式(pattern)匹配右侧
  30. #
  31. # 上面的例子中访问列表的头部和尾部就是这样工作的。
  32. # 当左右两边不匹配时,会返回error, 在这个
  33. # 例子中,元组大小不一样。
  34. # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
  35. # 还有二进制类型 (binaries)
  36. <<1,2,3>> # binary
  37. # 字符串(Strings) 和 字符列表(char lists)
  38. "hello" # string
  39. 'hello' # char list
  40. # 多行字符串
  41. """
  42. I'm a multi-line
  43. string.
  44. """
  45. #=> "I'm a multi-line\nstring.\n"
  46. # 所有的字符串(Strings)以UTF-8编码:
  47. "héllò" #=> "héllò"
  48. # 字符串(Strings)本质就是二进制类型(binaries), 字符列表(char lists)本质是列表(lists)
  49. <<?a, ?b, ?c>> #=> "abc"
  50. [?a, ?b, ?c] #=> 'abc'
  51. # 在 elixir中,`?a`返回 `a` 的 ASCII 整型值
  52. ?a #=> 97
  53. # 合并列表使用 `++`, 对于二进制类型则使用 `<>`
  54. [1,2,3] ++ [4,5] #=> [1,2,3,4,5]
  55. 'hello ' ++ 'world' #=> 'hello world'
  56. <<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
  57. "hello " <> "world" #=> "hello world"
  58. ## ---------------------------
  59. ## -- 操作符(Operators)
  60. ## ---------------------------
  61. # 一些数学运算
  62. 1 + 1 #=> 2
  63. 10 - 5 #=> 5
  64. 5 * 2 #=> 10
  65. 10 / 2 #=> 5.0
  66. # 在 elixir 中,操作符 `/` 返回值总是浮点数。
  67. # 做整数除法使用 `div`
  68. div(10, 2) #=> 5
  69. # 为了得到余数使用 `rem`
  70. rem(10, 3) #=> 1
  71. # 还有 boolean 操作符: `or`, `and` and `not`.
  72. # 第一个参数必须是boolean 类型
  73. true and true #=> true
  74. false or true #=> true
  75. # 1 and true #=> ** (ArgumentError) argument error
  76. # Elixir 也提供了 `||`, `&&` 和 `!` 可以接受任意的类型
  77. # 除了`false` 和 `nil` 其它都会被当作true.
  78. 1 || true #=> 1
  79. false && 1 #=> false
  80. nil && 20 #=> nil
  81. !true #=> false
  82. # 比较有: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` 和 `>`
  83. 1 == 1 #=> true
  84. 1 != 1 #=> false
  85. 1 < 2 #=> true
  86. # `===` 和 `!==` 在比较整型和浮点类型时更为严格:
  87. 1 == 1.0 #=> true
  88. 1 === 1.0 #=> false
  89. # 我们也可以比较两种不同的类型:
  90. 1 < :hello #=> true
  91. # 总的排序顺序定义如下:
  92. # number < atom < reference < functions < port < pid < tuple < list < bit string
  93. # 引用Joe Armstrong :“实际的顺序并不重要,
  94. # 但是,一个整体排序是否经明确界定是非常重要的。”
  95. ## ---------------------------
  96. ## -- 控制结构(Control Flow)
  97. ## ---------------------------
  98. # `if` 表达式
  99. if false do
  100. "This will never be seen"
  101. else
  102. "This will"
  103. end
  104. # 还有 `unless`
  105. unless true do
  106. "This will never be seen"
  107. else
  108. "This will"
  109. end
  110. # 在Elixir中,很多控制结构都依赖于模式匹配
  111. # `case` 允许我们把一个值与多种模式进行比较:
  112. case {:one, :two} do
  113. {:four, :five} ->
  114. "This won't match"
  115. {:one, x} ->
  116. "This will match and assign `x` to `:two`"
  117. _ ->
  118. "This will match any value"
  119. end
  120. # 模式匹配时,如果不需要某个值,通用的做法是把值 匹配到 `_`
  121. # 例如,我们只需要要列表的头元素:
  122. [head | _] = [1,2,3]
  123. head #=> 1
  124. # 下面的方式效果一样,但可读性更好
  125. [head | _tail] = [:a, :b, :c]
  126. head #=> :a
  127. # `cond` 可以检测多种不同的分支
  128. # 使用 `cond` 代替多个`if` 表达式嵌套
  129. cond do
  130. 1 + 1 == 3 ->
  131. "I will never be seen"
  132. 2 * 5 == 12 ->
  133. "Me neither"
  134. 1 + 2 == 3 ->
  135. "But I will"
  136. end
  137. # 经常可以看到最后一个条件等于'true',这将总是匹配。
  138. cond do
  139. 1 + 1 == 3 ->
  140. "I will never be seen"
  141. 2 * 5 == 12 ->
  142. "Me neither"
  143. true ->
  144. "But I will (this is essentially an else)"
  145. end
  146. # `try/catch` 用于捕获被抛出的值, 它也支持 `after` 子句,
  147. # 无论是否值被捕获,after 子句都会被调用
  148. # `try/catch`
  149. try do
  150. throw(:hello)
  151. catch
  152. message -> "Got #{message}."
  153. after
  154. IO.puts("I'm the after clause.")
  155. end
  156. #=> I'm the after clause
  157. # "Got :hello"
  158. ## ---------------------------
  159. ## -- 模块和函数(Modules and Functions)
  160. ## ---------------------------
  161. # 匿名函数 (注意点)
  162. square = fn(x) -> x * x end
  163. square.(5) #=> 25
  164. # 也支持接收多个子句和卫士(guards).
  165. # Guards 可以进行模式匹配
  166. # Guards 使用 `when` 关键字指明:
  167. f = fn
  168. x, y when x > 0 -> x + y
  169. x, y -> x * y
  170. end
  171. f.(1, 3) #=> 4
  172. f.(-1, 3) #=> -3
  173. # Elixir 提供了很多内建函数
  174. # 在默认作用域都是可用的
  175. is_number(10) #=> true
  176. is_list("hello") #=> false
  177. elem({1,2,3}, 0) #=> 1
  178. # 你可以在一个模块里定义多个函数,定义函数使用 `def`
  179. defmodule Math do
  180. def sum(a, b) do
  181. a + b
  182. end
  183. def square(x) do
  184. x * x
  185. end
  186. end
  187. Math.sum(1, 2) #=> 3
  188. Math.square(3) #=> 9
  189. # 保存到 `math.ex`,使用 `elixirc` 编译你的 Math 模块
  190. # 在终端里: elixirc math.ex
  191. # 在模块中可以使用`def`定义函数,使用 `defp` 定义私有函数
  192. # 使用`def` 定义的函数可以被其它模块调用
  193. # 私有函数只能在本模块内调用
  194. defmodule PrivateMath do
  195. def sum(a, b) do
  196. do_sum(a, b)
  197. end
  198. defp do_sum(a, b) do
  199. a + b
  200. end
  201. end
  202. PrivateMath.sum(1, 2) #=> 3
  203. # PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
  204. # 函数定义同样支持 guards 和 多重子句:
  205. defmodule Geometry do
  206. def area({:rectangle, w, h}) do
  207. w * h
  208. end
  209. def area({:circle, r}) when is_number(r) do
  210. 3.14 * r * r
  211. end
  212. end
  213. Geometry.area({:rectangle, 2, 3}) #=> 6
  214. Geometry.area({:circle, 3}) #=> 28.25999999999999801048
  215. # Geometry.area({:circle, "not_a_number"})
  216. #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
  217. #由于不变性,递归是Elixir的重要组成部分
  218. defmodule Recursion do
  219. def sum_list([head | tail], acc) do
  220. sum_list(tail, acc + head)
  221. end
  222. def sum_list([], acc) do
  223. acc
  224. end
  225. end
  226. Recursion.sum_list([1,2,3], 0) #=> 6
  227. # Elixir 模块支持属性,模块内建了一些属性,你也可以自定义属性
  228. defmodule MyMod do
  229. @moduledoc """
  230. 内置的属性,模块文档
  231. """
  232. @my_data 100 # 自定义属性
  233. IO.inspect(@my_data) #=> 100
  234. end
  235. ## ---------------------------
  236. ## -- 记录和异常(Records and Exceptions)
  237. ## ---------------------------
  238. # 记录就是把特定值关联到某个名字的结构体
  239. defrecord Person, name: nil, age: 0, height: 0
  240. joe_info = Person.new(name: "Joe", age: 30, height: 180)
  241. #=> Person[name: "Joe", age: 30, height: 180]
  242. # 访问name的值
  243. joe_info.name #=> "Joe"
  244. # 更新age的值
  245. joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180]
  246. # 使用 `try` `rescue` 进行异常处理
  247. try do
  248. raise "some error"
  249. rescue
  250. RuntimeError -> "rescued a runtime error"
  251. _error -> "this will rescue any error"
  252. end
  253. # 所有的异常都有一个message
  254. try do
  255. raise "some error"
  256. rescue
  257. x in [RuntimeError] ->
  258. x.message
  259. end
  260. ## ---------------------------
  261. ## -- 并发(Concurrency)
  262. ## ---------------------------
  263. # Elixir 依赖于 actor并发模型。在Elixir编写并发程序的三要素:
  264. # 创建进程,发送消息,接收消息
  265. # 启动一个新的进程使用`spawn`函数,接收一个函数作为参数
  266. f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
  267. spawn(f) #=> #PID<0.40.0>
  268. # `spawn` 函数返回一个pid(进程标识符),你可以使用pid向进程发送消息。
  269. # 使用 `<-` 操作符发送消息。
  270. # 我们需要在进程内接收消息,要用到 `receive` 机制。
  271. defmodule Geometry do
  272. def area_loop do
  273. receive do
  274. {:rectangle, w, h} ->
  275. IO.puts("Area = #{w * h}")
  276. area_loop()
  277. {:circle, r} ->
  278. IO.puts("Area = #{3.14 * r * r}")
  279. area_loop()
  280. end
  281. end
  282. end
  283. # 编译这个模块,在shell中创建一个进程,并执行 `area_looop` 函数。
  284. pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
  285. # 发送一个消息给 `pid`, 会在receive语句进行模式匹配
  286. pid <- {:rectangle, 2, 3}
  287. #=> Area = 6
  288. # {:rectangle,2,3}
  289. pid <- {:circle, 2}
  290. #=> Area = 12.56000000000000049738
  291. # {:circle,2}
  292. # shell也是一个进程(process), 你可以使用`self`获取当前 pid
  293. self() #=> #PID<0.27.0>

参考文献


还没有评论.