Understanding Enum.take_while

Hi,

Why does Enum.take_while supports < sign but not > sign. I have a list named sort

Sort list

sort = [2, 3, 5, 22, 23, 23, 34, 34, 56, 62, 68, 68, 347, 757]

when I try to run

Enum.take_while(sort, fn x -> x < 40 end)

Runs perfectly and gives an output

[2, 3, 5, 22, 23, 23, 34, 34]

When I try to execute

Enum.take_while(sort, fn x -> x > 40 end)

It shows an empty list like []. Is there something am doing wrong. Need assistance.

Thanks

Enum.take_while stops as soon as it encounters an element that the given function returns false for. Using > returns false for the first element…

Are you thinking of Enum.filter instead?

3 Likes

Enum.take_while takes elements from the given enumerable for as long as the function returns true.

As soon as a single false is encountered it stops and returns the resulting list.

What you’re probably looking for is Enum.filter.

3 Likes