Skip to content

Latest commit

 

History

History
537 lines (384 loc) · 9.86 KB

File metadata and controls

537 lines (384 loc) · 9.86 KB

Module 1: Introduction to Elixir

🎯 Module Objectives

  • Understand what Elixir is and its ecosystem
  • Learn why Elixir is valuable
  • Install Elixir and Erlang
  • Use the Interactive Elixir shell (IEx)
  • Write your first Elixir code

What is Elixir?

Elixir is a dynamic, functional programming language built on top of the Erlang VM (BEAM). It was created by José Valim in 2011 and is designed for building scalable, maintainable, and fault-tolerant applications.

Main Features

  1. Functional Programming: Immutable data and first-class functions
  2. Concurrent: Built for massive concurrency with lightweight processes
  3. Fault-Tolerant: "Let it crash" philosophy with supervision trees
  4. Scalable: Distributed computing support out of the box
  5. Productive: Modern syntax with excellent tooling
  6. Compatible: Runs on the battle-tested Erlang VM

Why Elixir?

1. The Erlang Foundation

Elixir runs on the Erlang VM, which powers systems requiring:

  • High availability (99.9999999% uptime - "nine nines")
  • Massive concurrency (millions of processes)
  • Real-time systems
  • Distributed computing

Examples: WhatsApp handles 900 million users on Erlang, Discord uses Elixir for real-time messaging.

2. Modern and Productive

Unlike Erlang's syntax, Elixir provides:

  • Ruby-inspired, readable syntax
  • Powerful macro system for metaprogramming
  • Excellent documentation tools
  • Great tooling with Mix build tool

3. Concurrency Model

# Spawn a million processes? No problem!
for i <- 1..1_000_000 do
  spawn(fn -> :ok end)
end

Each process is lightweight (only ~2KB of memory).

4. Real-World Success

Companies using Elixir:

  • Discord: 5+ million concurrent users
  • Pinterest: Reduced servers from 200 to 15
  • Moz: 20 billion records processed daily
  • Bleacher Report: Real-time sports updates

🆚 Elixir vs Other Languages

Feature Elixir Node.js Python Ruby
Concurrency Built-in, lightweight processes Single-threaded, async GIL limitations GIL limitations
Fault Tolerance Supervision trees Manual error handling Manual error handling Manual error handling
Immutability By default Optional Optional Optional
Pattern Matching Core feature Limited Limited Limited
Scalability Horizontal & Vertical Horizontal (clustering) Horizontal (multiprocessing) Horizontal (multiprocessing)
Real-time Excellent Good Fair Fair

🔧 Installing Elixir

Elixir requires Erlang/OTP to be installed first.

💡 Recommended: Use asdf version manager to easily manage Erlang and Elixir versions. This is especially useful when working with multiple projects that may require different versions. See the Using asdf section below.

On Ubuntu/Debian

# Add Erlang Solutions repository
wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb
sudo dpkg -i erlang-solutions_2.0_all.deb
sudo apt-get update

# Install Erlang and Elixir
sudo apt-get install -y esl-erlang elixir

# Verify installation
elixir --version

On macOS

# Using Homebrew
brew install elixir

# Verify installation
elixir --version

On Windows

# Using Chocolatey
choco install elixir

# Or download installer from:
# https://elixir-lang.org/install.html#windows

# Verify installation
elixir --version

Using asdf (Version Manager - ⭐ Recommended)

asdf is a universal version manager that allows you to manage multiple versions of Erlang and Elixir on the same system. This is the recommended method for installing Elixir, especially for developers working on multiple projects.

Advantages of asdf:

  • Manage multiple versions of Erlang and Elixir
  • Switch between versions per project
  • Simple version upgrades
  • Works on Linux, macOS, and Windows (WSL)
  • Same tool for multiple languages

Installation:

# Install asdf
git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.13.1

# Add to shell (bash example)
echo '. "$HOME/.asdf/asdf.sh"' >> ~/.bashrc
echo '. "$HOME/.asdf/completions/asdf.bash"' >> ~/.bashrc
source ~/.bashrc

# For zsh, use:
# echo '. "$HOME/.asdf/asdf.sh"' >> ~/.zshrc
# source ~/.zshrc

# Add Erlang and Elixir plugins
asdf plugin add erlang
asdf plugin add elixir

# List available versions (optional)
asdf list all erlang
asdf list all elixir

# Install Erlang and Elixir
asdf install erlang 26.1.2
asdf install elixir 1.15.7-otp-26

# Set global versions (used by default)
asdf global erlang 26.1.2
asdf global elixir 1.15.7-otp-26

# Or set local version for current directory
# asdf local erlang 26.1.2
# asdf local elixir 1.15.7-otp-26

# Verify
elixir --version

Quick Reference:

# List installed versions
asdf list erlang
asdf list elixir

# Install new version
asdf install elixir 1.16.0-otp-26

# Switch version for current project
asdf local elixir 1.16.0-otp-26

# Update plugins
asdf plugin update --all

✅ Installation Verification

Run these commands to verify everything works:

# View Elixir version
elixir --version

# You should see something like:
# Erlang/OTP 26 [erts-14.1.1] [source] [64-bit]
# Elixir 1.15.7 (compiled with Erlang/OTP 26)

# Start Interactive Elixir
iex

🎮 Interactive Elixir (IEx)

IEx is your best friend when learning Elixir. It's a REPL (Read-Eval-Print Loop) where you can test code instantly.

Starting IEx

# Start IEx
iex

# You'll see:
# Erlang/OTP 26 [erts-14.1.1]
# 
# Interactive Elixir (1.15.7) - press Ctrl+C to exit
# iex(1)>

Basic IEx Usage

# Simple arithmetic
iex> 1 + 1
2

iex> 10 * 5
50

# Strings
iex> "Hello, " <> "Elixir!"
"Hello, Elixir!"

# Lists
iex> [1, 2, 3] ++ [4, 5]
[1, 2, 3, 4, 5]

# Tuples
iex> {:ok, "result"}
{:ok, "result"}

# Check variable type
iex> i(42)
# Shows detailed information about the value

Useful IEx Commands

# Help
h()                    # General help
h(String)             # Module help
h(String.upcase)      # Function help

# Last value
v()                   # Get last value
v(2)                  # Get value from line 2

# Clear screen
clear()

# Compile and load file
c("path/to/file.ex")

# Exit IEx
# Press Ctrl+C twice, or type:
System.halt()

🎨 Basic Elixir Syntax

Hello World

# In IEx
iex> IO.puts("Hello, World!")
Hello, World!
:ok

Create a file hello.exs:

# hello.exs
IO.puts("Hello, World!")

Run it:

elixir hello.exs
# Output: Hello, World!

Variables

# Variables are immutable by default
iex> name = "Elixir"
"Elixir"

iex> age = 12
12

# "Reassignment" creates a new binding
iex> age = age + 1
13

Data Types

# Integer
42

# Float
3.14

# Atom (constant whose name is its value)
:ok
:error
:atom

# Boolean (atoms under the hood)
true
false

# String (UTF-8 encoded binaries)
"hello"

# List (linked list)
[1, 2, 3]

# Tuple (contiguous memory)
{:ok, "result"}

# Map (key-value store)
%{name: "John", age: 30}

Basic Operations

# Arithmetic
iex> 10 + 5
15

iex> 10 - 3
7

iex> 10 * 2
20

iex> 10 / 2
5.0

iex> div(10, 3)    # Integer division
3

iex> rem(10, 3)    # Remainder
1

# String concatenation
iex> "Hello, " <> "World!"
"Hello, World!"

# String interpolation
iex> name = "Elixir"
iex> "Hello, #{name}!"
"Hello, Elixir!"

# Boolean operations
iex> true and false
false

iex> true or false
true

iex> not true
false

# Comparison
iex> 1 == 1
true

iex> 1 === 1.0    # Strict equality
false

iex> 1 < 2
true

🔍 Help System

Elixir has excellent built-in documentation:

# General help
iex> h()

# Module documentation
iex> h(String)

# Function documentation
iex> h(String.upcase)

# Show information about a value
iex> i("hello")
Term
  "hello"
Data type
  BitString
Byte size
  5
Description
  This is a string: a UTF-8 encoded binary...

📝 First Program: Temperature Converter

Create temperature.exs:

# temperature.exs

# Convert Celsius to Fahrenheit
celsius = 25
fahrenheit = celsius * 9 / 5 + 32

IO.puts("#{celsius}°C is #{fahrenheit}°F")

# Convert Fahrenheit to Celsius
fahrenheit = 77
celsius = (fahrenheit - 32) * 5 / 9

IO.puts("#{fahrenheit}°F is #{celsius}°C")

Run it:

elixir temperature.exs
# Output:
# 25°C is 77.0°F
# 77°F is 25.0°C

🎓 Module Summary

You have learned:

  • ✅ What Elixir is and its main features
  • ✅ Why Elixir is valuable for modern applications
  • ✅ How to install Elixir and Erlang
  • ✅ How to use IEx (Interactive Elixir)
  • ✅ Basic syntax and data types
  • ✅ How to write and run your first Elixir program

➡️ Next Step

Module 2: Elixir Fundamentals


💡 Practice Exercises

Try these in IEx:

  1. Calculate the area of a circle with radius 5 (π * r²)

    radius = 5
    area = 3.14159 * radius * radius
  2. Create a greeting message with your name

    name = "Your Name"
    IO.puts("Hello, #{name}! Welcome to Elixir!")
  3. Experiment with different data types

    integer = 42
    float = 3.14
    atom = :ok
    string = "hello"
    list = [1, 2, 3]
    tuple = {:ok, "success"}
    map = %{name: "John"}
    
    # Use i() to inspect each one
    i(integer)
    i(float)
    # ... and so on
  4. Try the help system

    h(Enum)
    h(Enum.map)
    h(String.upcase)

💡 Self-Assessment Questions

  1. What VM does Elixir run on?
  2. Name three companies that use Elixir in production
  3. What command do you use to start Interactive Elixir?
  4. What's the difference between == and ===?
  5. How do you concatenate two strings?

(Answers are in the module content)


Great job! You're now ready to dive deeper into Elixir. 🚀