发布时间:2023-07-19 13:00
第一次学习Elixir,作为一个笔记记录一下学习过程,内容中均为自己的理解,存在理解有误的地方,请指出,谢谢!
#A list generator:
iex> for n <- [1, 2, 3, 4], do: n * 2
[2, 4, 6, 8]
# for Bitstring
iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>
iex> for <<r::8, g::8, b::8 <- pixels>>, do: {r, g, b}
iex> [{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}]
# A comprehension with two generators
for x <- [1, 2], y <- [2, 3], do: x * y
[2, 3, 4, 6]
n <- [1, 2, 3, 4]
, [1, 2]
, [2, 3]
都是generator, do后面是执行方法,即对可枚举元素的操作# A comprehension with a generator and 筛选出对2求余为0的元素
iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n
[2, 4, 6]
# 筛选出type不等于guest的值
iex> users = [user: "john", admin: "meg", guest: "barbara"]
iex> for {type, name} when type != :guest <- users do
...> String.upcase(name)
...> end
["JOHN", "MEG"]