Reputation: 173
I have a simple Go for loop and i want to learn how to do this with Recursion in Elixir. I don't really know how the recursion loop works at this time but i am working on that part! I also don't know if this is even the right way to do recursive functions.
package main
import "fmt"
func main() {
for i := 0; i < 10000000; i++ {
fmt.Println(i)
}
}
defmodule Looping do
def loops(i, e) when e <= 0 do
IO.puts i + e
end
def loops(i, e) do
IO.puts i + e
loops(i, e + 1)
end
end
Looping.loops(1, 1)
Produces 1 + 1 + 1 on going in Elixir.
Martin over at the beginners slack channel suggested the following.
1..1_000_000 |> Enum.each(&IO.puts/1)
Upvotes: 1
Views: 1382
Reputation: 31
In your case using a range & a simple comprehension would work very well, but if you wanted to use recursion specifically you could do something like
defmodule SomeName do
def addr(range), do: addr(Enum.to_list(range), 0)
def addr([first|rest], sum), do: addr(rest, sum + first)
def addr([], sum), do: sum
end
if you wanted to print each line you could throw an IO.inspect/1 in addr/2 to print out the sum like
def addr([first|rest], sum) do
IO.inspect(sum)
addr(rest, sum + first)
end
Upvotes: 0
Reputation: 3069
Well ignoring the main stuff and running your elixir code in Iex I get an infinite ascending series that begins
1
2
3
4
which suggests you may have intended to stop when you arrive at 10000000 not at zero - thus tidying up your code we have:
defmodule Looping do
def loops(e) when e == 10000000 do
IO.puts e
end
def loops(e) do
IO.puts e
loops(e + 1)
end
end
Looping.loops(0)
Upvotes: 3
Reputation: 2313
I'm not exactly sure what you're looking for, but simulating a for loop with recursion in Elixir would look something like this:
def my_func(param1, 5), do: param1
def my_func(param1, count) do
my_func param1 * 2, count + 1
end
and you would call the function like this to run the loop from 1 to 5:
my_func(input_for_param1, 1)
I think your problem is that you still don't understand what recursion is and how Elixir (and Functional Programming languages) work. Try to first grasp these concepts (including pattern matching) and everything will come easier to you.
Another way to do a for loop would be by creating a construct for it through metaprogramming.
Upvotes: 2
Reputation: 914
There are a lot of simple recursion examples found here: http://elixir-lang.org/getting-started/recursion.html That also explain recursion and going through lists. What are you specifically after? Take a look at those and let me know if you are having a hard time figuring it out.
Upvotes: 0