defmodule Looper do
def loop(p, i) do
case i in p do
true -> loop(p, i + 0.01)
false -> i
end
end
end
p = [1.01, 1.02, 1.04]
i = 1.01
Looper.loop(p, i)
There’s likely other ways to do it. Recursion generally solves most scenarios where you’d use a while loop.
The obvious ‘other way’ to do it would be using streams:
defmodule Looper do
def loop(p, i) do
i
|> Stream.iterate(fn x -> x + 0.01 end)
|> Stream.take_while(&Kernel.in(&1, p))
|> Enum.to_list
|> List.last
end
end
but in this simple case it would generate a lot more overhead than the plain recursive version, thus being slower.
I think in this case it is definitely better to follow the KISS principle and go for the straightforward recursive loop which is way simpler than the other alternatives.
I think it’s interesting that that can even work, I’m curious what the macro is doing. Definitely not a recommended solution though. Functional code is a lot more idiomatic and clear.
EDIT:
Ah in looking at the examples I see that if you want i to carry on with the value it has to be rebound, that makes more sense: