1

I want to encode this algorithm In Elixir:

var name = generate_name();
while (check_if_exists(name)) {
  name = generate_name();
}

I can't encode that the same way in Elixir because there must more idiomatic and functional way. How can I do that then?

1

2 Answers 2

8

Elixir is an Immutable programming language. That means you cannot modify the value of variable, only re-bind it. Hence, the classic doesn't exist in Elixir.

But, you can implement this using recursion:

def get_name do
  name = generate_name()

  case check_if_exists(name) do
    true  -> get_name()
    false -> name
  end
end
Sign up to request clarification or add additional context in comments.

5 Comments

Guidelines suggest using case for 3+ clauses only: if check_if_exists(name), do: get_name(), else: name.
I can very well change a value of a variable in Elixir
no, you cannot change the value of a variable - you can only rebind it to a different value.
If/else is just a macro for the case statement with true/false code above.
I chose case instead of if-else because I like it more, even though it's a macro on top of case just like @FredtheMagicWonderDog said
6

Another possibility is to create an infinite stream of names, then find the first name that is available:

Stream.repeatedly(&generate_name/0)
|> Enum.find(&check_if_exists/1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.