Elixir中的for語句有許多用法:數據庫
for n <- [1,2,3,4], do: n * 2
[2, 4, 6, 8]code
for x <- [1,2], y <- [3,4], do: x * y
[3,4,6,8]rem
for x <- [1,2,3,4], rem(x, 2) == 0, do: x
[2, 4]字符串
users = [user: "jhon", admin: "tom", guest: "lulu"] for {type, name} when type != :guest <- users, do: String.upcase(name) end
["JHON", "TOM"]string
pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>> for <<r::8, g::8, b::8 <- pixels >>, do: {r, g, b}
[{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}]it
凡是支持collectable協議的結構體,例如"" , IO.stream(:stdio, :line)等,均可以使用 :into 選項,來將for語句執行的結構插入到結構體中io
for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>
使用 into: ""
將代碼點helloworld插入到了""中,變爲字符串 "helloworld"table
for line <- IO.stream(:stdio, :line), into: IO.stream(:stdio, :line) do String.upcase(line) end
這就是一個簡單的回聲服務class
搭配for語句能夠實現強大的數據庫查詢功能,下篇文章將講講Ecto。stream
就到這裏吧。
Hackerrank沒動力刷了,好難TAT