【问题标题】:Using drop_while in Elixir?在 Elixir 中使用 drop_while?
【发布时间】:2016-08-04 02:22:08
【问题描述】:

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

【问题讨论】:

    标签: elixir


    【解决方案1】:

    您正在寻找Enum.reject/2,而不是Enum.drop_while/2。正如文档所说,Enum.drop_while开始 下降,直到 fun 返回一个真实值。在您的示例中,fun1 返回true,因此您将获得从1 开始的原始列表的所有元素。

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

    【讨论】:

    • 所以,until a truthy value 是理解它的关键。
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2017-09-11
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多