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