This document describes the coding conventions and patterns used in the ExAlgo project to help maintain consistency across the codebase.
- Follow the pattern:
ExAlgo.<Category>.<ModuleName>(e.g.,ExAlgo.Heap.LeftistHeap) - Categories: Heap, List, Queue, Stack, Sort, Search, Tree, Set, Number, Counting, Dynamic Programming
- One primary module per file
- Protocol implementations in
impls/subdirectories
defmodule ExAlgo.Category.ModuleName do
@moduledoc """
Brief description of what the module implements.
Optional: Additional context, algorithm complexity, links to Wikipedia, etc.
"""
# Aliases at the top
alias __MODULE__
# Nested modules for internal data structures
defmodule Node do
defstruct [:field1, :field2, field3: default_value]
end
# Main struct definition
defstruct field1: [], field2: []
# Type definitions
@type t :: %__MODULE__{...}
@type value_type :: any()
# Public functions with @doc and @spec
# Private functions
end- Always include
@moduledocwith clear, concise description - Add algorithm complexity analysis when relevant
- Include links to external resources (Wikipedia, papers) for context
- Document performance characteristics and caveats
- Every public function must have
@doc - Always include
## Examplessection with IEx-style doctests - Document edge cases
- Use special sections when needed:
## Performance Note- complexity warnings## Note on Complexity- detailed analysis
Example:
@doc """
Inserts an item into the queue.
## Examples
iex> Queue.new() |> Queue.enqueue(1)
%Queue{left: [1], right: []}
"""- All public functions must have
@spec - Define custom types at module level with
@type - Common type patterns:
@type t :: %__MODULE__{...} @type value_type :: any() @type empty_error :: {:error, :empty_list} @type neg_index_error :: {:error, :negative_index}
- Use descriptive type names (
value_type(),item(), etc.) - Explicitly type error returns as union types
- Use
snake_casefor all functions - Prefix private helpers with
do_(e.g.,do_merge,do_find) - Common function names:
new/0,new/1- constructorsfrom/1- create from enumerableinsert/2,delete/2- modificationsfind/2,find_min/1,find_max/1- queriesto_list/1,to_text/1,to_mermaid/1- conversions
- Use multiple function clauses for different cases
- Pattern match on struct fields in function heads
- Use guard clauses for validation:
def find_min(%Empty{}), do: {:error, :empty}
def find_min(%Node{value: v}), do: {:ok, v}
def at(_, index) when index < 0, do: {:error, :negative_index}- Return tuples:
{:ok, value}or{:error, reason} - Use atoms for error reasons (
:empty,:underflow,:negative_index) - Use
withstatements for chaining operations that may fail
- Always return updated structures, never mutate
- Use struct update syntax:
def enqueue(%__MODULE__{left: left} = queue, item),
do: %{queue | left: [item | left]}- Prefer tail-call optimization with accumulators
- Base cases first, recursive cases after
- Comment tail calls:
defp do_merge(xs, ys, acc) do
do_merge(xs, ys, [y | acc]) # Tail call!
end- Use
|>extensively for data transformation - Combine with
then/2for intermediate steps:
list
|> Enum.split(half)
|> then(fn {left, right} ->
{merge_sort(left), merge_sort(right)}
end)
|> then(fn {left, right} -> do_merge(left, right, []) end)- Protocol implementations in separate files under
impls/subdirectories - Multiple related implementations can share a file
- Always alias the module at the top
Implement these protocols when appropriate:
Inspect- custom inspect outputEnumerable- for collection-like structuresCollectable- for structures that can collect values
Example:
defimpl Inspect, for: Queue do
import Inspect.Algebra
def inspect(queue, opts) do
concat(["#ExAlgo.Queue<", to_doc(Queue.to_list(queue), opts), ">"])
end
enddefmodule ExAlgo.Module.NameTest do
use ExUnit.Case
use ExUnitProperties # When using property-based tests
@moduletag :category_name
alias ExAlgo.Module.Name
doctest ExAlgo.Module.Name
setup do
{:ok, %{
empty_struct: Name.new(),
populated: Name.from(1..5)
}}
end
describe "function_name/arity" do
test "description", fixtures do
# test implementation
end
property "property description" do
check all data <- generator() do
assert condition
end
end
end
end- Always run doctests:
doctest ModuleName - Use
@moduletagfor categorization - Group tests by function in
describeblocks - Use
setupfor test fixtures - Property-based testing with StreamData for algorithms
- Test edge cases explicitly (empty, single element, negative values)
- Place helper functions at bottom of test file
- Use 2-space indentation
- Use
do:for short single-line functions - Multi-line for complex logic
- Comments use
#with space after - Format with
mix format
Use nested modules for internal data structures:
defmodule ExAlgo.Heap.LeftistHeap do
alias __MODULE__
defmodule Node do
defstruct [:dist, :value, :left, :right]
end
defmodule Empty do
defstruct []
end
end- Include complexity notes in module docs
- Explain trade-offs in function documentation
- Comment optimizations (tail calls, etc.)
- Educational Focus: Code emphasizes clarity and learning over micro-optimizations
- Comprehensive Documentation: Every function has examples and doctests
- Strong Typing: All public APIs are fully type-specified
- Functional Patterns: Immutability, recursion, pattern matching throughout
- Test Coverage: Both example-based and property-based tests
- Consistent Error Handling: Tagged tuples for all error cases