Here’s a Elixir cheat sheet, a functional and concurrent programming language designed for building scalable and maintainable applications:
Basics
Comments:
# Single-line comment
"""
Multi-line
comment
"""
Variables:
x = 42
Atoms:
:ok
:error
Strings:
"Hello, Elixir!"
Data Types
Numbers:
42
3.14
Booleans:
true
false
Lists:
[1, 2, 3]
Tuples:
{1, "hello"}
Maps:
%{:name => "John", :age => 30}
%{"name" => "John", "age" => 30}
Pattern Matching
Match Operator:
x = 42
42 = x # Matches successfully
Case Statement:
case result do
:ok -> "Operation successful"
:error -> "An error occurred"
end
Functions
Defining a Function:
def add(a, b) do
a + b
end
Anonymous Functions:
add = fn a, b -> a + b end
result = add.(1, 2)
Modules and Functions
Module Definition:
defmodule MyModule do
def my_function do
"Hello from MyModule!"
end
end
Module Alias:
alias MyModule, as: M
M.my_function()
Processes and Concurrency
Spawn a Process:
pid = spawn(fn -> IO.puts("Hello from process #{inspect self()}") end)
Sending and Receiving Messages:
send(pid, {:message, "Hello"})
receive do
{:message, msg} -> IO.puts("Received: #{msg}")
end
Enum and Stream
Enum Functions:
list = [1, 2, 3]
Enum.map(list, &(&1 * 2))
Streams:
stream = Stream.map([1, 2, 3], &(&1 * 2))
Enum.to_list(stream)
Error Handling
Raise an Exception:
raise "An error occurred"
Try and Rescue:
result =
try do
perform_operation()
rescue
RuntimeError -> "An error occurred"
end
File I/O
Reading a File:
{:ok, content} = File.read("filename.txt")
IO.puts(content)
Writing to a File:
File.write("output.txt", "Hello, Elixir!")
Mix (Build Tool)
Create a New Elixir Project:
mix new my_project
Run Tests:
mix test
This Elixir cheat sheet covers some of the essential features of the language. For more in-depth information, refer to the official Elixir documentation.