pythonwhile-loopelixir

Elixir equivalent to while true


I want to rewrite this method (written here in Python) in Elixir

def something()
    while True:
        x = function()
        y = function()
        if x != y:
            return x
    

function() generates a random value, so the execution would end sooner or later.

My problem is to translate the while True in the most "functional way" possible.

I came up with this solution, but I think is not very readable.


def something() do
    internal(function(), function())
end

defp internal(a, a) do
    internal(function(), function())
end

defp internal(a, _) do
    a
end

Is there a better way to do it?

PS: function() must be always called twice at every cycle and it cannot be rewritten.

Thanks


Solution

  • Elixir has variables and if expressions too, so all you really need to do is replace while True with a recursive call:

      def something() do
        x = function()
        y = function()
    
        if x != y do
          x
        else
          something()
        end
      end