Add Elixir examples for recursion
This commit is contained in:
committed by
Aditya Bhargava
parent
fa35ae875d
commit
687d3fece6
12
03_recursion/elixir/01_countdown.exs
Normal file
12
03_recursion/elixir/01_countdown.exs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
defmodule Countdown do
|
||||||
|
defguardp non_positive?(x) when x <= 0
|
||||||
|
|
||||||
|
def from(i) when non_positive?(i), do: nil
|
||||||
|
|
||||||
|
def from(i) do
|
||||||
|
IO.puts(i)
|
||||||
|
from(i - 1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
Countdown.from(5)
|
||||||
18
03_recursion/elixir/02_greet.exs
Normal file
18
03_recursion/elixir/02_greet.exs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
defmodule Greeting do
|
||||||
|
def greet2(name) do
|
||||||
|
IO.puts("how are you, #{name}?")
|
||||||
|
end
|
||||||
|
|
||||||
|
def bye do
|
||||||
|
IO.puts("ok bye!")
|
||||||
|
end
|
||||||
|
|
||||||
|
def greet(name) do
|
||||||
|
IO.puts("hello, #{name}!")
|
||||||
|
greet2(name)
|
||||||
|
IO.puts("getting ready to say bye...")
|
||||||
|
bye()
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
Greeting.greet("adit")
|
||||||
6
03_recursion/elixir/03_factorial.exs
Normal file
6
03_recursion/elixir/03_factorial.exs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
defmodule Factorial do
|
||||||
|
def of(1), do: 1
|
||||||
|
def of(n), do: n * of(n - 1)
|
||||||
|
end
|
||||||
|
|
||||||
|
IO.puts(Factorial.of(5))
|
||||||
Reference in New Issue
Block a user