【ELIXIR】for语句的N种用法

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

处理bitstring的时候,双箭头放在最外边

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

:into

凡是支持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

使用Ecto query

搭配for语句能够实现强大的数据库查询功能,下篇文章将讲讲Ecto。stream

就到这里吧。

Hackerrank没动力刷了,好难TAT

相关文章
相关标签/搜索