How to end recursion

I want user to keep having the possibility to enter input again as long as it produces a result.
I use recursion here to make it happen, however, I want to exit recursion when user input does not lead to a valid result.

In my code I tried to bind keyword list search result to variable x and then check if it is :ok or not, if :ok continue recursion if not exit.

Problem is x is always :ok no matter what user input is. Im not sure here how can I get out of recursion here.

defmodule Home4 do

    def taskOne() do
        colors = [{:black, "#000000"}, {:aqua, "#00FFFF"}, {:brown, "#A52A2A"}, {:green, "#008000"}, {:navy, "#000080"}, {:olive, "#808000"}, {:pink, "#FFC0CB"}, {:purple, "#800080"}, {:red, "#FF0000"}, {:yellow, "#FFFF00"}]
        Home4.test(colors)
    end


    def test(keywordlist) do
        input = IO.gets("Enter color name or code: ") |> String.trim()
        if String.starts_with?(input, "#") do
            x = keywordlist 
            |> Enum.find( fn {key, val} -> val == input end)
            |> elem(0) |> IO.puts()
            #If something end recursion else continue
            if x == :ok do
                Home4.test(keywordlist)                          
            end
        else
            x = keywordlist         
            |> Keyword.get(String.to_atom(input)) 
            |> IO.puts()
            #If something end recursion
            if x == :ok do
                Home4.test(keywordlist)                          
            end          
        end      
    end

end
Home4.taskOne()

The ok is the result of the last operation… IO.puts()

1 Like

If you will separate the side effects (IO calls) in a different function than the one that performs the pure business logic, I think you’ll find the code much easier to work with. You should also look into the optional default parameter that both Enum.find and Keyword.get offer (or my List.keyfind suggestion on the other thread). Those can return a :not_found atom that can be a signal to stop recursion.

3 Likes

Thank you! I got an idea now how to solve it :slight_smile: