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
来实现结果)
答案 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]