Skip to content

Commit 1d657d1

Browse files
Adding a few elixir scripts
1. CalculatePi.ex --> Approximate a value of pi 2. FactorialIterative.ex --> Returns a factorial for a given n, in an iterative manner. 3. FactorialRecursive.ex --> Returns a factorial for a given n, in an recursive manner. 4. FibonacciIterative.ex --> Returns a Fibonacci value for a given n, in an iterative manner. 5. FibonacciRecursive.ex --> Returns a Fibonacci value for a given n, in a recursive manner. 6. MaxRecursive.ex --> Find largest value in a list. 7. README.md -> Basic overview document
1 parent ba92e76 commit 1d657d1

File tree

7 files changed

+249
-0
lines changed

7 files changed

+249
-0
lines changed

src/elixir/CalculatePi.ex

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Module to calculate an approximation of Pi
2+
defmodule PiApproximation do
3+
4+
# Function to calculate pi given number of terms
5+
def calculate_pi(terms) do
6+
7+
# Initialize pi accumulator
8+
pi = 0.0
9+
10+
# Reduce over 1..terms range
11+
# Accumulator is a tuple with pi, denominator, and operation
12+
Enum.reduce(1..terms, {pi, 1.0, 1.0}, fn _, {acc_pi, acc_denom, acc_op} ->
13+
14+
# Calculate new pi value
15+
new_pi = acc_pi + acc_op * (4.0 / acc_denom)
16+
17+
# Return tuple with updated values
18+
{new_pi, acc_denom + 2.0, -acc_op}
19+
end) |> elem(0)
20+
end
21+
22+
end
23+
24+
# Number of terms to approximate
25+
terms = 100_000
26+
27+
# Call approximation function
28+
result = PiApproximation.calculate_pi(terms)
29+
30+
# Print result
31+
IO.puts(result)

src/elixir/FactorialIterative.ex

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
defmodule Factorial do
2+
# Define a module called Factorial.
3+
4+
def factorial(n) when n >= 0 do
5+
# Calculate the factorial using Enum.reduce.
6+
Enum.reduce(1..n, 1, &(&1 * &2))
7+
end
8+
9+
defp format_factorial(i, result) do
10+
# Format the output string.
11+
"#{i}! = #{result}"
12+
end
13+
14+
def main do
15+
# Entry point of the program.
16+
nums = [0, 1, 2, 3, 4, 5]
17+
18+
Enum.each(nums, fn i ->
19+
# Iterate through the list of numbers.
20+
result = factorial(i)
21+
IO.puts(format_factorial(i, result))
22+
end)
23+
end
24+
end
25+
26+
Factorial.main() # Execute the program.

src/elixir/FactorialRecursive.ex

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Define Math module for math utilities
2+
defmodule Math do
3+
4+
# Recursive factorial function
5+
def factorial(0), do: 1 # Base case
6+
7+
def factorial(n) when n > 0 do
8+
# Recursive case
9+
n * factorial(n-1)
10+
end
11+
12+
end
13+
14+
# Array of numbers to get factorials for
15+
nums = [0, 1, 2, 3, 4, 5]
16+
17+
# Loop through the nums array
18+
for i <- nums do
19+
20+
# Calculate and print factorial
21+
IO.puts "#{i}! = #{Math.factorial(i)}"
22+
23+
end

src/elixir/FibonacciIterative.ex

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Define a Fibonacci module
2+
defmodule Fib do
3+
4+
# Function to calculate nth Fibonacci number
5+
def fibonacci(n) when n >= 0 do
6+
7+
# Initialize starting values
8+
last = 0
9+
curr = 1
10+
11+
# Use Enum.reduce as a loop from 0 to n-1
12+
Enum.reduce(0..(n-1), {last, curr}, fn _, {last, curr} ->
13+
14+
# Update last and curr, returning as a tuple
15+
{curr, curr + last}
16+
end)
17+
18+
# Return the last value after reducing
19+
|> elem(0)
20+
end
21+
end
22+
23+
# Print 10th Fibonacci number
24+
IO.puts(Fib.fibonacci(10))

src/elixir/FibonacciRecursive.ex

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Define a Fibonacci module
2+
defmodule Fibonacci do
3+
# Base case: If n is 0 or 1, return n.
4+
def fibonacci(n) when n <= 1, do: n
5+
6+
# Recursive case: Calculate the Fibonacci number by summing the results
7+
# of the previous two Fibonacci numbers.
8+
def fibonacci(n) do
9+
fibonacci(n - 1) + fibonacci(n - 2)
10+
end
11+
end
12+
13+
# Print the Fibonacci number for n = 10.
14+
IO.puts("Fibonacci(n): #{Fibonacci.fibonacci(10)}")

src/elixir/MaxRecursive.ex

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
defmodule MaxRecursive do
2+
# Base case: When n is 1, return the first element of the list (head).
3+
def max_recursive(nums, 1), do: hd(nums)
4+
5+
# Recursive case: Calculate the maximum recursively.
6+
def max_recursive(nums, n) do
7+
aux = max_recursive(nums, n - 1)
8+
if aux > Enum.at(nums, n - 1) do
9+
aux
10+
else
11+
Enum.at(nums, n - 1)
12+
end
13+
end
14+
end
15+
16+
# Example usage
17+
nums = [1, 2, 3, 4, 32, 6, 7, 8, 9, 10]
18+
IO.inspect "nums = #{inspect(nums)}"
19+
IO.inspect "Max = #{MaxRecursive.max_recursive(nums, length(nums))}"

src/elixir/README.md

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
## Elixir Language Basic Syntax Review
2+
Elixir is a general purpose programming language built on top of Erlang or Ericsson language. It is very efficient for building distributed, fault tolerant appications. It's been used by many companies like Pinterest, PagerDuty, FarmBot, E-Metro Tel etc.
3+
4+
Key features:
5+
6+
- Built especially for scalable and maintanable applications.
7+
- Everything is an expression
8+
- Compiles to bytecode
9+
- Built-in tooling for compilation, testing, debugging, formatting code etc.
10+
- Erlang functions can be called directly as it get compiled to Erlang bytecode.
11+
12+
#### 1. Variables
13+
14+
````elixir
15+
variable-name = value
16+
````
17+
18+
#### 2. Data types
19+
20+
|Data type | Usage | Description |
21+
| ------------ | ------------ | ------------ |
22+
| Numeric |x = 21|Elixir supports not only integer and float values but also a number can be defined in octal, hexadecimal and binary bases. |
23+
| Atom | :true|Atoms are constant values whose name is same as their value |
24+
| Boolean | : false, :true| Either true or false, usually declared as atoms |
25+
| Strings | "Hello" | Strings are enclosed in double quotes(" ") and multi line strings are enclosed in triple double quotes(""" """) |
26+
|Lists | ['a', 10, :true] | Lists are used to store different types of values and are represented in square brackets [] |
27+
|Tuples | {'apple', 100, :false} | Similar to Lists and are represented in curly brackets {}. Tuples are good for accessing the values and lists are good for insertion and deletion of values |
28+
29+
30+
#### 3. Loops and Conditionals
31+
32+
##### If-Else and If-Else:
33+
34+
When ever you want to perform a set of operations based on a condition If is used.
35+
36+
```elixir
37+
if condition do
38+
#Code
39+
end
40+
```
41+
42+
When there is requirement to add code for false condition to IF block.
43+
44+
```elixir
45+
if condition do
46+
#Code
47+
else
48+
#code
49+
end
50+
```
51+
52+
##### Unless and Unless-Else:
53+
54+
Unless is similar to If but the code get executed only if the condition fails.
55+
56+
````elixir
57+
unless condition do
58+
#Code
59+
end
60+
````
61+
62+
Unless-Else is similar to If-Else but the code get executed only if the condition fails.
63+
64+
````elixir
65+
unless condition do
66+
#Code if condition fails
67+
else
68+
#Code if condition satisfies
69+
end
70+
````
71+
72+
##### Cond:
73+
Cond is used when you want to execute a piece of code based on multiple conditions.
74+
75+
````elixir
76+
cond do
77+
condition-1 -> #code if condition is true
78+
condition-2 -> #code if condition is true
79+
...
80+
true -> #code if none of the above are true
81+
end
82+
````
83+
84+
##### Case:
85+
86+
Case is similar to switch in C/C++ language.
87+
88+
````elixir
89+
case value do
90+
value-1 -> #code if value matches value-1
91+
value-2 -> #code if value matches value-2
92+
value-3 -> #code if value matches value-3
93+
...
94+
_ -> #code if value does not match any of the above and is similar to default in switch
95+
end
96+
````
97+
98+
#### 4. Functions
99+
Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity.
100+
101+
Two types of functions are present in Elixir
102+
103+
1. Anonymous Functions: Anonymous functions are functions with no name and they use `fn..end` constructs.
104+
2. Named functions: Assign names to functions so that they can be called easily. Always named functions are defined in modules.
105+
106+
```elixir
107+
defmodule modulename do
108+
def function_name(parameter1, parameter2) do
109+
#code
110+
end
111+
end
112+
```

0 commit comments

Comments
 (0)