Counting Up and Down — Basic Recursion in Elixir.

Messing around with Elixir 1.2.0.

Try these yourself over at http://elixirplayground.com/

If you’re using IEX, just copy the code and press enter, it should run.


Count up to 100

defmodule Recursion do
def loops(x) when x == 100 do
IO.puts x
end

def loops(x) do
IO.puts x
loops(x + 1)
end
end
Recursion.loops(0) #Type this after you copy the function in if using IEX.

Counting up to 100 then down to 0 with 2 guard clauses

defmodule Recursion do
def loops(x) when x == 100 do
IO.puts x
down(x — 1)
end

def loops(x) do
IO.puts x
loops(x + 1)
end

def down(x) when x == 0 do
IO.puts x
end

def down(x) do
IO.puts x
down(x — 1)
end
end
Recursion.loops(0) # Count up to 100 then down to 0.

Using Enum

http://elixir-lang.org/docs/v1.2/elixir/Enum.html

defmodule Looping do
def loops do 
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ,17 ,18 ,19 ,20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
#Count up from 1 - 100, puts out each number within the array.  
Enum.each(list, fn(s) -> IO.puts(s) end)
#Copies our list, reverses it, names it reversedList. 
reversedList = Enum.reverse(list)
#Prints out our copied list. Counts up the list from 100 to 1.
Enum.each(reversedList, fn(s) -> IO.puts(s) end)
end
end

Again with Enum

defmodule Looping do 
def loops do
1..100 |> Enum.each(&IO.puts/1)
100..1 |> Enum.each(&IO.puts/1)
end
end
Without the shorthand:
defmodule Looping do 
def loops do
1..100 |> Enum.each( fn(s) -> IO.puts(s) end)
100..1 |> Enum.each( fn(s) -> IO.puts(s) end)
end
end

The same thing in Python, or at least one way to do it.

for i in reversed(xrange(101)):
print i
for i in (xrange(101)):
print i
#Count down from 101 or (100) then count up to 101 (100). Python 2.7

Thanks to all the people that helped me on Stackoverflow and the Elixir Slack channel. I learnt more about the basics on slack than anywhere else. Check it out by joining https://elixir-lang.slack.com