Enum.split_with 但只使用结果元组的一侧

hnh*_*nhl 0 elixir

之后如何访问第一个列表Enum.split_with()

m = Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
// m = {[4, 2, 0], [5, 3, 1]}
Run Code Online (Sandbox Code Playgroud)

我只想访问列表[4,2,0]并通过另一个Enum.filter()函数

就像是

m = 
  Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
  |> Enum.filter(fn -> ) //Filter only first list after split
Run Code Online (Sandbox Code Playgroud)

Ada*_*hip 5

重点Enum.split_with/2是获得过滤拒绝的项目。如果你只需要或者过滤的或不合格的项目,然后Enum.filter/2Enum.reject/2有更好的选择:

iex(1)> Enum.filter([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[4, 2, 0]
iex(2)> Enum.reject([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[5, 3, 1]
Run Code Online (Sandbox Code Playgroud)

也就是说,有两种标准方法可以访问元组的元素:

  1. 通过=运算符使用模式匹配:
iex(3)> {first, _} = {:a, :b}
{:a, :b}
iex(4)> first
:a
Run Code Online (Sandbox Code Playgroud)
  1. 如果是管道的一部分,请使用elem/2帮助程序:
iex(5)> {:a, :b} |> elem(0)
:a
Run Code Online (Sandbox Code Playgroud)

  • 在`v1.12`中引入了[`Kernel.then/2`](https://hexdocs.pm/elixir/master/Kernel.html#then/2):`Enum.split_with([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0) |> then(fn {first, _} -> 第一个结束) #⇒ [4, 2, 0]` (2认同)
  • 我应该补充一点,作为 1.12 发布时使用模式匹配的替代方法。不过,在这种特定情况下,我可能会坚持使用“elem/2”。 (2认同)