Elixir - comprehensions

Elixir - comprehensions

第一次学习Elixir,作为一个笔记记录一下学习过程,内容中均为自己的理解,存在理解有误的地方,请指出,谢谢!

comprehension基础使用

  • 功能:允许我们快速构建一个可枚举的或是位串的数据结构。
  • 返回值:默认返回List,通过配置参数可以返回其他类型,后面会介绍
  • 基本的使用方法
    #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"]
    

options

Comprehension共有3个配置参数

  • :into: 修改comprehension的返回值类型, example: into: %{} 修改返回类型为map

  • :uniq: 保证返回数据中元素的唯一性, example: uniq: true

    # into 、 uniq的使用
    iex> for <<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>>
    "ABC"
    
  • reduce: 与Enum.reduce/3的使用方法和功能相同

    #reduce的使用
    iex> for <<x <- "AbCabCABc">>, x in ?a..?z, reduce: %{} do
    ...> 	acc -> Map.update(acc, <<x>>, 1, & &1 + 1)
    ...> end
    %{"a" => 1, "b" => 2, "c" => 1}
    

    reduce:%{}, %{}是Map.update函数累加器accumulator的初始值
    for <<x <- "AbCabCABc">>, x in ?a..?z,筛选后的结果是reduce函数要操纵的List

官网学习地址:
Elixir学习地址- hexdoc
elixir-lang
感谢,有问题大家交流!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值