在Elixir中使用drop_while?

时间:2016-08-03 18:17:35

标签: elixir

<\ n> Elixir的文档说明

drop_while(enumerable, fun)
   Drops items at the beginning of the enumerable while fun returns a truthy value

但我对以下输出感到困惑。这是否意味着一旦获得!truthy,其他一切都被视为假?

iex> Enum.drop_while([0,1,2,3,4,5], fn(x) -> rem(x,2) == 0 end)
[1,2,3,4,5]

我期望输出[1,3,5],因为

 iex> Enum.map([0,1,2,3,4,5], fn(x) -> rem(x,2) == 0 end)
[true,false,true,false,true,false]

我试图理解它是如何工作的,而不是试图获得我想要的输出(有Enum.filter来实现结果)

1 个答案:

答案 0 :(得分:4)

您正在寻找Enum.reject/2,而不是Enum.drop_while/2。与文档说的一样,Enum.drop_while开始开始,直到fun返回真值。在您的示例中,fun会为true返回1,因此您可以从1开始获取原始列表的所有元素。

iex(1)> Enum.reject([0, 1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)
[1, 3, 5]