Introduction to Programming in Elixir
Elixir is a dynamic, functional programming language built on the Erlang VM (BEAM). It is designed for building scalable and maintainable applications, particularly for distributed and concurrent systems. Elixir combines the productivity of modern languages with the robustness of Erlang, making it a great choice for web development, real-time systems, and more.
This guide will introduce you to the fundamentals of Elixir programming, helping you write clean, efficient, and concurrent code.
Table of Contents
- What is Elixir?
- Setting Up Your Environment
- Basic Syntax and Data Types
- Pattern Matching
- Functions
- Modules and Structs
- Collections
- Concurrency with Processes
- Error Handling
- Metaprogramming with Macros
What is Elixir?
Elixir is a functional programming language that runs on the Erlang VM. It is known for its scalability, fault tolerance, and concurrency model.
1# Example: Your first Elixir program
2IO.puts("Hello, Elixir Programming!")
Setting Up Your Environment
To write and run Elixir programs, you need to install Elixir on your system. Follow the instructions on the official Elixir website.
1# Example: Running an Elixir script
2elixir main.exs
Basic Syntax and Data Types
Elixir is a dynamically typed language with a clean and expressive syntax. Common data types include integers, floats, atoms, strings, and lists.
1# Example: Declaring variables
2age = 25
3height = 5.9
4name = "Alice"
5is_student = true
6
7IO.puts("Name: #{name}, Age: #{age}, Height: #{height}")
Pattern Matching
Pattern matching is a core feature of Elixir, allowing you to destructure data and bind variables in a concise way.
1# Example: Pattern matching
2{a, b} = {1, 2}
3IO.puts("a: #{a}, b: #{b}") # a: 1, b: 2
Functions
Functions in Elixir are first-class citizens and can be defined using the def
keyword. Elixir also supports anonymous functions.
1# Example: Function
2defmodule Math do
3 def add(a, b) do
4 a + b
5 end
6end
7
8result = Math.add(5, 10)
9IO.puts("Result: #{result}") # 15
Modules and Structs
Modules are used to organize functions, and structs are used to define custom data types.
1# Example: Module and Struct
2defmodule Person do
3 defstruct name: "", age: 0
4
5 def display(%Person{name: name, age: age}) do
6 IO.puts("Name: #{name}, Age: #{age}")
7 end
8end
9
10person = %Person{name: "Alice", age: 25}
11Person.display(person)
Collections
Elixir provides powerful collection types like lists, tuples, and maps for storing and manipulating data.
1# Example: List
2fruits = ["Apple", "Banana", "Orange"]
3Enum.each(fruits, fn fruit -> IO.puts(fruit) end)
Concurrency with Processes
Elixir's concurrency model is based on lightweight processes, which are isolated and communicate via message passing.
1# Example: Spawning a process
2pid = spawn(fn ->
3 receive do
4 {:greet, name} -> IO.puts("Hello, #{name}!")
5 end
6end)
7
8send(pid, {:greet, "Alice"})
Error Handling
Elixir uses the try
, catch
, and rescue
constructs for error handling, but it encourages a "let it crash" philosophy for fault-tolerant systems.
1# Example: Error handling
2try do
3 raise "Something went wrong"
4rescue
5 e in RuntimeError -> IO.puts("Error: #{e.message}")
6end
Metaprogramming with Macros
Elixir supports metaprogramming through macros, allowing you to generate code at compile time.
1# Example: Macro
2defmodule MyMacro do
3 defmacro say_hello do
4 quote do
5 IO.puts("Hello from a macro!")
6 end
7 end
8end
9
10defmodule Main do
11 require MyMacro
12 MyMacro.say_hello()
13end