for 的使用
# 基本形式
for some_condition?, do: #output value
# elixir 中,除了简单的 for 写法,如下
for i <- 1..10 do
end
# iex> for i <- [:a, :b, :c], j <- [1, 2], do: {i, j}
# output: [a: 1, a: 2, b: 1, b: 2, c: 1, c: 2]
# i 和 j 定义出来的,用在 block 和 some_condition?
# func(i, j) 这种直接返回值的,如果返回的是 false 或者 nil 就过滤掉这个了
# some_condition? 中 也可以写成: path = Path.join(dir, file) 这种形式
for i <- 1..10, j <- [2, 3], func(i, j) do
# block
end
# Example:
dirs = ['/home/mikey', '/home/james']
for dir <- dirs,
file <- File.ls!(dir),
path = Path.join(dir, file),
File.regular?(path) do
File.stat!(path).size
end
# Comprehensions discard all elements for which the filter expression returns false or nil; all other values are selected.
# into:
iex> for {key, val} <- %{"a" => 1, "b" => 2}, into: %{}, do: {key, val * val}
# output: %{"a" => 1, "b" => 4}