randomcoder
randomcoder

Reputation: 15

elixir recursion block not returning proper value

I want the following block of code to return value not equal to 0 or n. But sometimes it returns values equal to 0.

def get_random(n, num) do   
   random = returns some number
   IO.puts random
   if random == n or random == 0 do
      get_random(n, num)
   end
   random
end

Upvotes: 1

Views: 68

Answers (1)

denis.peplin
denis.peplin

Reputation: 9841

You didn't set random variable second time.

Fixed code:

defmodule GetRandom do
  def get_random(n, num) do
    random = Enum.random(0..num)
    IO.puts random
    random = if random == n or random == 0 do
      get_random(n, num)
    else
      random
    end
    random
  end
end

This code can be simplified. First, if Enum.random is used, you don't need to exclude 0 after call. Just exclude it from range.

Also, use implicit value return. You don't need to set random variable second time if it is in the end of the function.

defmodule GetRandom do
  def get_random(n, num) do
    random = Enum.random(1..num)
    IO.puts random
    if random == n do
      get_random(n, num)
    else
      random
    end
  end
end

Upvotes: 1

Related Questions