Elixir ↔ Roc Conversion
Bidirectional conversion between Elixir and Roc. This skill extends meta-convert-dev with Elixir↔Roc specific type mappings, idiom translations, and architectural patterns for moving from dynamic, actor-based concurrency to static, pure functional programming with platform-provided effects.
This Skill Extends
meta-convert-dev - Foundational conversion patterns (APTV workflow, testing strategies)
For general concepts like the Analyze → Plan → Transform → Validate workflow, testing strategies, and common pitfalls, see the meta-skill first.
This Skill Adds
- Type mappings: Elixir dynamic types → Roc static types
- Paradigm translation: GenServer/OTP patterns → Pure state machines + platform Tasks
- Idiom translations: Elixir functional patterns → Roc functional patterns
- Error handling: Elixir error tuples + exceptions → Result types
- Concurrency: Processes/GenServer → Roc platform Tasks
- Module system: Elixir modules → Roc platform/application architecture
- Metaprogramming: Elixir macros → Roc abilities and external codegen
This Skill Does NOT Cover
- General conversion methodology - see
meta-convert-dev
- Elixir language fundamentals - see
lang-elixir-dev
- Roc language fundamentals - see
lang-roc-dev
Quick Reference
| Elixir |
Roc |
Notes |
:atom |
[Tag] |
Atoms become tags in tag unions |
integer() |
I64 / U64 |
Specify signedness explicitly |
float() |
F64 |
64-bit float |
String.t() |
Str |
UTF-8 strings |
binary() |
List U8 |
Byte sequences |
list() |
List a |
Homogeneous lists |
tuple() |
(a, b, c) |
Fixed-size tuples |
map() |
Dict k v |
Key-value maps (requires Hash+Eq keys) |
keyword() |
List (Str, a) |
List of tuples (no duplicate keys guaranteed) |
{:ok, value} |
Ok(value) |
Success result |
{:error, reason} |
Err(reason) |
Error result |
nil |
None in tag union |
Optional values |
pid() |
- |
No direct equivalent (platform handles processes) |
fn(x) -> x end |
\x -> x |
Lambda syntax |
%{__struct__: Name} |
Opaque type Name := ... |
Structs become opaque types |
When Converting Code
- Analyze OTP patterns before writing Roc - GenServers become pure state machines
- Identify process boundaries - these become platform Task interactions
- Map dynamic patterns to static types - use tag unions for variants
- Redesign supervision trees - Roc platforms handle failure differently
- Extract pure logic - separate computation from effects (Task, IO)
- Handle hot code loading - not a language feature in Roc
- Test equivalence - verify behavior matches despite different architecture
Type System Mapping
Primitive Types
| Elixir |
Roc |
Notes |
:atom |
[Tag] |
Atoms as tags in tag unions |
integer() |
I64 |
Default signed 64-bit |
integer() |
U64 |
Unsigned variant |
integer() (small) |
I32 / U32 |
For smaller values |
integer() (arbitrary) |
- |
Roc has fixed-size integers |
float() |
F64 |
64-bit floating point |
boolean() |
Bool |
Direct mapping |
String.t() |
Str |
UTF-8 strings |
binary() |
List U8 |
Byte sequences |
bitstring() |
List U8 |
Byte-aligned only in Roc |
nil |
None |
In tag union [Some a, None] |
pid() |
- |
Processes don't exist in Roc |
port() |
- |
Platform handles I/O |
reference() |
- |
No direct equivalent |
function() |
Function types |
See function mappings below |
Collection Types
| Elixir |
Roc |
Notes |
list() |
List a |
Homogeneous lists (all same type) |
[T] |
List T |
Type-safe, uniform elements |
tuple() |
(A, B, C) |
Fixed-size tuples |
{A, B, C} |
(A, B, C) |
Direct structural mapping |
map() |
Dict k v |
Key-value dictionary (requires Hash+Eq for keys) |
%{K => V} |
Dict K V |
Keys must implement Hash and Eq abilities |
MapSet.t() |
Set a |
Unique values (requires Hash+Eq) |
keyword() |
List (Str, a) |
List of tuples, no uniqueness guarantee |
[{:key, value}] |
List (Str, a) |
Keyword lists as tuple lists |
Range.t() |
- |
Use List.range to generate lists |
Stream.t() |
- |
Roc has lazy iterators but no Stream type |
Composite Types
| Elixir |
Roc |
Notes |
defstruct |
{ field : Type } |
Structs become records |
%Name{field: value} |
{ field: value } |
Record literals |
Tagged tuple {:tag, value} |
Tag(value) |
Tags with payloads |
@type name :: spec |
Name : Type |
Type alias |
@opaque name :: spec |
Opaque type Name := Type |
Hidden implementation |
@spec annotations |
Type signatures |
Enforced in Roc |
Function Types
| Elixir |
Roc |
Notes |
(-> R) |
({} -> R) |
Zero-argument function |
(A -> R) |
(A -> R) |
Single argument |
(A, B -> R) |
(A, B -> R) |
Multiple arguments (curried) |
| Variable arity |
- |
Roc doesn't support varargs |
| Default arguments |
- |
Use separate function signatures |
Error Types
| Elixir |
Roc |
Notes |
{:ok, value} |
Ok(value) |
Success case |
{:error, reason} |
Err(reason) |
Error case |
:ok atom |
Ok({}) |
Success with no value |
{:ok, V} | {:error, R} |
Result V R |
Result type |
| Exception raising |
Err variant |
No exceptions, use Result |
rescue clause |
Pattern match on Result |
Explicit error handling |
Idiom Translation
Pattern 1: Simple Module Conversion
Elixir:
defmodule MathUtils do
@doc "Add two numbers"
def add(a, b), do: a + b
@doc "Square a number"
def square(n), do: n * n
# Private function
defp internal_helper(x), do: x * 2
end
Roc:
interface MathUtils
exposes [add, square]
imports []
## Add two numbers
add : I64, I64 -> I64
add = \a, b -> a + b
## Square a number
square : I64 -> I64
square = \n -> n * n
# Private helper (not exposed)
internalHelper : I64 -> I64
internalHelper = \x -> x * 2
Why this translation:
- Elixir modules become Roc interfaces
- Public functions go in
exposes
- Private functions are simply not exposed
- Doctests become inline
expect tests in Roc
- Type signatures are explicit (not optional like typespecs)
Pattern 2: Pattern Matching on Tagged Tuples
Elixir:
def process_result({:ok, data}) do
{:success, data}
end
def process_result({:error, reason}) do
{:failure, reason}
end
def process_result(_unknown) do
{:failure, :unknown_result}
end
Roc:
processResult : [Ok Data, Err Reason, Unknown] -> [Success Data, Failure Reason]
processResult = \result ->
when result is
Ok(data) -> Success(data)
Err(reason) -> Failure(reason)
Unknown -> Failure(UnknownResult)
Why this translation:
- Elixir tagged tuples map to Roc tags
- Pattern matching syntax is similar (
when vs pattern match in function head)
- Tag unions make all cases explicit in type signature
- Type system ensures exhaustiveness (can't forget cases)
Pattern 3: Pipe Operator
Elixir:
def process_data(data) do
data
|> String.trim()
|> String.downcase()
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == ""))
end
Roc:
processData : Str -> List Str
processData = \data ->
data
|> Str.trim
|> Str.toLowercase
|> Str.split(",")
|> List.map(Str.trim)
|> List.keepIf(\s -> s != "")
Why this translation:
- Both languages have pipe operators with similar semantics
- Roc uses
keepIf instead of reject with negated predicate
- Capture operator
& in Elixir becomes explicit lambdas in Roc
- Type inference works similarly in both
Pattern 4: Enum Operations
Elixir:
def sum(list), do: Enum.reduce(list, 0, &+/2)
def squares(list), do: Enum.map(list, fn x -> x * x end)
def evens(list), do: Enum.filter(list, fn x -> rem(x, 2) == 0 end)
def find_first_large(list) do
Enum.find(list, fn x -> x > 100 end)
end
Roc:
sum : List I64 -> I64
sum = \list ->
List.walk(list, 0, Num.add)
squares : List I64 -> List I64
squares = \list ->
List.map(list, \x -> x * x)
evens : List I64 -> List I64
evens = \list ->
List.keepIf(list, \x -> x % 2 == 0)
findFirstLarge : List I64 -> [Some I64, None]
findFirstLarge = \list ->
list
|> List.findFirst(\x -> x > 100)
|> Result.map(Some)
|> Result.withDefault(None)
Why this translation:
Enum.reduce becomes List.walk (fold)
Enum.filter becomes List.keepIf
Enum.find returns Result, needs conversion to option type
- Function captures (
&+/2) become explicit function references (Num.add)
- Roc requires explicit handling of "not found" cases
Pattern 5: Struct to Record
Elixir:
defmodule User do
defstruct [:name, :email, age: 0]
def new(name, email) do
%User{name: name, email: email}
end
def update_age(user, new_age) do
%{user | age: new_age}
end
def greet(%User{name: name}), do: "Hello, #{name}!"
end
Roc:
interface User
exposes [User, new, updateAge, greet]
imports []
User : {
name : Str,
email : Str,
age : U32,
}
new : Str, Str -> User
new = \name, email ->
{ name, email, age: 0 }
updateAge : User, U32 -> User
updateAge = \user, newAge ->
{ user & age: newAge }
greet : User -> Str
greet = \{ name } ->
"Hello, \(name)!"
Why this translation:
- Elixir structs map directly to Roc records
- Record update syntax is similar (
%{user | age:} vs { user & age:})
- Pattern matching on records works similarly
- Roc records are structural (no
__struct__ metadata)
- Default values in struct definition become default in constructor
Pattern 6: GenServer → Pure State Machine
Elixir:
defmodule Counter do
use GenServer
# Client API
def start_link(initial_value) do
GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
end
def increment do
GenServer.cast(__MODULE__, :increment)
end
def get do
GenServer.call(__MODULE__, :get)
end
# Server Callbacks
@impl true
def init(initial_value) do
{:ok, initial_value}
end
@impl true
def handle_call(:get, _from, state) do
{:reply, state, state}
end
@impl true
def handle_cast(:increment, state) do
{:noreply, state + 1}
end
end
Roc:
# Pure state machine - no processes
interface Counter
exposes [State, init, increment, get]
imports []
State : I64
init : State
init = 0
increment : State -> State
increment = \count ->
count + 1
get : State -> I64
get = \count ->
count
# If you need effects, use platform Tasks
# The platform would provide state management and concurrency
# Application code remains pure
Why this translation:
- GenServer becomes pure state functions
- No process lifecycle - just data transformation
- State is explicit parameter and return value
call operations become synchronous functions that return new state
cast operations become functions that just transform state
- Effects and concurrency are platform responsibilities, not shown here
- Platform provides state management if needed
Pattern 7: With Statement Error Handling
Elixir:
def create_user(params) do
with {:ok, validated} <- validate_params(params),
{:ok, user} <- insert_user(validated),
{:ok, _email} <- send_welcome_email(user) do
{:ok, user}
else
{:error, reason} -> {:error, reason}
end
end
Roc:
createUser : Params -> Result User [ValidationErr, InsertErr, EmailErr]
createUser = \params ->
validated = validateParams!(params)
user = insertUser!(validated)
_email = sendWelcomeEmail!(user)
Ok(user)
Why this translation:
- Elixir
with becomes Roc ! operator (try/propagate)
! suffix propagates errors automatically
- Error types are unified in tag union
- Early return on error is implicit with
!
- More concise than explicit pattern matching
Pattern 8: Optional Values
Elixir:
def find_user(id, users) do
Enum.find(users, fn user -> user.id == id end)
end
def get_email(nil), do: "no email"
def get_email(user), do: user.email
# Using in pipeline
def display_email(id, users) do
users
|> find_user(id)
|> case do
nil -> "User not found"
user -> user.email
end
end
Roc:
findUser : U64, List User -> [Some User, None]
findUser = \id, users ->
users
|> List.findFirst(\user -> user.id == id)
|> Result.map(Some)
|> Result.withDefault(None)
getEmail : [Some User, None] -> Str
getEmail = \maybeUser ->
when maybeUser is
Some({ email }) -> email
None -> "no email"
displayEmail : U64, List User -> Str
displayEmail = \id, users ->
when findUser(id, users) is
Some(user) -> user.email
None -> "User not found"
Why this translation:
- Elixir
nil maps to None in tag union
Enum.find returns nil or value; Roc findFirst returns Result
- Explicit pattern matching on option types
- Type system prevents forgetting to handle
None case
- Must convert
Result to option type with Some/None
Pattern 9: List Comprehensions
Elixir:
def squares(list) do
for x <- list, do: x * x
end
def evens(list) do
for x <- list, rem(x, 2) == 0, do: x
end
def cartesian_product(list1, list2) do
for x <- list1, y <- list2, do: {x, y}
end
def filtered_map(list) do
for x <- list, x > 0, into: %{}, do: {x, x * x}
end
Roc:
squares : List I64 -> List I64
squares = \list ->
List.map(list, \x -> x * x)
evens : List I64 -> List I64
evens = \list ->
List.keepIf(list, \x -> x % 2 == 0)
cartesianProduct : List a, List b -> List (a, b)
cartesianProduct = \list1, list2 ->
List.joinMap(list1, \x ->
List.map(list2, \y -> (x, y))
)
filteredMap : List I64 -> Dict I64 I64
filteredMap = \list ->
list
|> List.keepIf(\x -> x > 0)
|> List.map(\x -> (x, x * x))
|> Dict.fromList
Why this translation:
- Comprehensions become
map/keepIf operations
- Nested comprehensions use
joinMap (flatMap/concatMap)
- Filters become
keepIf
into: %{} becomes Dict.fromList
- More verbose but explicit
- Type signatures make intent clear
Pattern 10: Protocol Implementation
Elixir:
defprotocol Serializable do
@doc "Serialize to JSON"
def to_json(data)
end
defimpl Serializable, for: Map do
def to_json(map) do
Jason.encode!(map)
end
end
defimpl Serializable, for: List do
def to_json(list) do
Jason.encode!(list)
end
end
# Usage
Serializable.to_json(%{name: "Alice"})
Roc:
# Roc uses abilities (similar to typeclasses)
# Built-in Encode ability is auto-derived for most types
# For custom encoding:
toJson : a -> Str where a implements Encode
toJson = \value ->
value
|> Encode.toBytes(Json.utf8)
|> Str.fromUtf8
# Automatic for records and tags
user = { name: "Alice", age: 30 }
json = toJson(user) # Works automatically
# For custom types with specific behavior:
User := { name : Str, age : U32 }
toJsonUser : User -> Str
toJsonUser = \@User({ name, age }) ->
"""
{\"name\": \"\(name)\", \"age\": \(Num.toStr(age))}
"""
Why this translation:
- Elixir protocols map to Roc abilities
- Many abilities are auto-derived (Encode, Decode, Eq, Hash, Inspect)
- For custom behavior, write explicit functions
- No dynamic dispatch in Roc - abilities are compile-time
- Roc's approach is more restrictive but type-safe
Concurrency Patterns
Elixir Process Model vs Roc Task Model
Elixir's concurrency is built on lightweight BEAM processes with message passing. Roc has no built-in concurrency - it's all platform-provided through Tasks.
Mental Model Shift:
| Elixir Concept |
Roc Approach |
Key Insight |
| Process with state |
Pure state machine + platform Task |
Data and behavior separated |
| Message passing |
Function parameters and results |
Explicit data flow, no mailboxes |
spawn |
Platform Task creation |
Effects are platform capability |
| GenServer |
Pure functions + Task orchestration |
Business logic pure, I/O delegated |
| Supervisor |
Platform-level concern |
Fault tolerance in host |
| Hot code reload |
Not available |
Platform restart required |
Pattern: Spawned Task
Elixir:
defmodule Worker do
def start do
spawn(fn -> loop() end)
end
defp loop do
receive do
{:work, from, data} ->
result = process(data)
send(from, {:result, result})
loop()
:stop ->
:ok
end
end
defp process(data), do: String.upcase(data)
end
# Usage
pid = Worker.start()
send(pid, {:work, self(), "hello"})
receive do
{:result, result} -> IO.puts(result)
end
Roc:
# Pure processing function
process : Str -> Str
process = \data ->
Str.toUppercase(data)
# If concurrency is needed, platform provides it
import pf.Task exposing [Task]
processAsync : Str -> Task Str []
processAsync = \data ->
# Platform handles concurrent execution
Task.await(Task.fromThunk(\{} -> process(data)))
# Usage (in Task context)
main : Task {} []
main =
result = processAsync!("hello")
Stdout.line!(result)
Why this translation:
- No process spawning in Roc - platform handles concurrency
- Pure function for business logic (
process)
- Platform Task for effects
- No message passing - direct function composition
- Platform decides execution strategy (sync/async/parallel)
Pattern: GenServer State
Elixir:
defmodule Cache do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
def get(key) do
GenServer.call(__MODULE__, {:get, key})
end
def put(key, value) do
GenServer.cast(__MODULE__, {:put, key, value})
end
@impl true
def init(_), do: {:ok, %{}}
@impl true
def handle_call({:get, key}, _from, state) do
{:reply, Map.get(state, key), state}
end
@impl true
def handle_cast({:put, key, value}, state) do
{:noreply, Map.put(state, key, value)}
end
end
Roc:
# Pure state functions
State : Dict Str Str
init : State
init = Dict.empty({})
get : State, Str -> [Some Str, None]
get = \state, key ->
Dict.get(state, key)
|> Result.map(Some)
|> Result.withDefault(None)
put : State, Str, Str -> State
put = \state, key, value ->
Dict.insert(state, key, value)
# Platform would provide state management
# For example, a hypothetical Agent-like platform API:
#
# import pf.Agent exposing [Agent, start, getState, updateState]
#
# cacheAgent : Agent State
# cacheAgent = start(init)
#
# getValue : Str -> Task [Some Str, None] []
# getValue = \key ->
# Agent.getState(cacheAgent, \state -> get(state, key))
#
# putValue : Str, Str -> Task {} []
# putValue = \key, value ->
# Agent.updateState(cacheAgent, \state -> put(state, key, value))
Why this translation:
- GenServer becomes pure state transformations
- State management delegated to platform (Agent, Store, etc.)
- No process registered names - platform handles references
- No
call vs cast distinction - just sync vs async Task
- Fault tolerance handled by platform, not supervision tree
Pattern: Task.async
Elixir:
def fetch_multiple(urls) do
tasks = Enum.map(urls, fn url ->
Task.async(fn -> fetch_url(url) end)
end)
Task.await_many(tasks, 5000)
end
defp fetch_url(url) do
case HTTPoison.get(url) do
{:ok, %{body: body}} -> {:ok, body}
{:error, reason} -> {:error, reason}
end
end
Roc:
import pf.Http
import pf.Task exposing [Task]
fetchMultiple : List Str -> Task (List Str) [HttpErr]
fetchMultiple = \urls ->
urls
|> List.map(\url -> Http.get(url))
|> Task.sequence # Platform may execute concurrently
|> Task.map(\responses -> List.map(responses, \r -> r.body))
# Platform-specific concurrent execution
# Some platforms may provide parallel primitives:
# fetchMultipleParallel : List Str -> Task (List Str) [HttpErr]
# fetchMultipleParallel = \urls ->
# Task.parallel(List.map(urls, Http.get))
Why this translation:
Task.async maps to platform Task creation
- Platform decides concurrency strategy
Task.sequence combines multiple Tasks
- Timeout is platform-specific (may be in Task API)
- No separate "await" - composition with
! or Task.map
Pattern: Agent State
Elixir:
defmodule Counter do
use Agent
def start_link(_opts) do
Agent.start_link(fn -> 0 end, name: __MODULE__)
end
def increment do
Agent.update(__MODULE__, &(&1 + 1))
end
def get do
Agent.get(__MODULE__, & &1)
end
end
Roc:
# Pure state functions
State : I64
init : State
init = 0
increment : State -> State
increment = \count -> count + 1
get : State -> I64
get = \count -> count
# Hypothetical platform API for stateful agents
# (actual API depends on platform)
#
# import pf.Agent exposing [Agent]
#
# counterAgent : Agent State
# counterAgent = Agent.start(init)
#
# incrementCounter : Task {} []
# incrementCounter =
# Agent.update(counterAgent, increment)
#
# getCounter : Task I64 []
# getCounter =
# Agent.get(counterAgent, get)
Why this translation:
- Agent pattern becomes pure state + platform state management
- No global registered names - agent references are explicit
- Updates are explicit functions, not anonymous lambdas
- Platform provides concurrency-safe state updates
- Business logic (increment, get) remains pure and testable
Error Handling
Elixir Error Model → Roc Result Type
| Elixir Pattern |
Roc Pattern |
Translation Strategy |
{:ok, value} |
Ok(value) |
Direct mapping |
{:error, reason} |
Err(reason) |
Direct mapping |
raise/1 |
Err variant |
No exceptions in Roc |
rescue clause |
Pattern match on Result |
Explicit error handling |
try/rescue |
Result combinators |
Compose with Result.try, Result.map |
| Multiple error tuples |
Tag union error type |
[Err1, Err2, Err3] |
! (bang) functions |
Regular functions returning Result |
All errors explicit |
Pattern: Error Propagation
Elixir:
def calculate(a, b, c) do
with {:ok, x} <- divide(a, b),
{:ok, y} <- divide(x, c) do
{:ok, y}
else
{:error, reason} -> {:error, reason}
end
end
# Or using the ! convention:
def calculate!(a, b, c) do
x = divide!(a, b)
y = divide!(x, c)
y
end
Roc:
calculate : I64, I64, I64 -> Result I64 [DivByZero]
calculate = \a, b, c ->
x = divide!(a, b) # Propagates error automatically
y = divide!(x, c)
Ok(y)
# Or explicitly:
calculateExplicit : I64, I64, I64 -> Result I64 [DivByZero]
calculateExplicit = \a, b, c ->
divide(a, b)
|> Result.try(\x ->
divide(x, c)
)
Why this translation:
- Elixir
with becomes Roc ! operator
! in Roc is try/propagate (not unwrap/crash like Elixir!)
- Both patterns allow early return on error
- Roc's approach is more concise
- Type system ensures all errors are handled
Pattern: Multiple Error Types
Elixir:
defmodule Parser do
def parse_and_save(input) do
with {:ok, data} <- parse(input),
{:ok, validated} <- validate(data),
:ok <- save(validated) do
{:ok, validated}
else
{:error, :invalid_format} -> {:error, "Invalid format"}
{:error, :validation_failed, msg} -> {:error, "Validation: #{msg}"}
{:error, :save_failed} -> {:error, "Could not save"}
end
end
end
Roc:
parseAndSave : Str -> Result Data [InvalidFormat, ValidationFailed Str, SaveFailed]
parseAndSave = \input ->
data = parse!(input) # Returns Result Data [InvalidFormat]
validated = validate!(data) # Returns Result Data [ValidationFailed Str]
save!(validated) # Returns Result {} [SaveFailed]
Ok(validated)
# Error handling with descriptive messages
parseAndSaveWithMsg : Str -> Result Data Str
parseAndSaveWithMsg = \input ->
parseAndSave(input)
|> Result.mapErr(\err ->
when err is
InvalidFormat -> "Invalid format"
ValidationFailed(msg) -> "Validation: \(msg)"
SaveFailed -> "Could not save"
)
Why this translation:
- Elixir error atoms map to Roc tag variants
- Error payloads become tag parameters
! operator unifies error types automatically
Result.mapErr converts to user-friendly messages
- Type signature documents all possible errors
Pattern: Raise and Rescue
Elixir:
def process_file(path) do
content = File.read!(path) # Raises on error
parse(content)
rescue
e in File.Error -> {:error, "File error: #{e.message}"}
e in ArgumentError -> {:error, "Invalid arguments"}
end
# Safer alternative
def process_file_safe(path) do
case File.read(path) do
{:ok, content} -> parse(content)
{:error, reason} -> {:error, "File error: #{inspect(reason)}"}
end
end
Roc:
# Roc has no exceptions - all errors are Result types
import pf.File
processFile : Str -> Result Data [FileErr Str, ParseErr]
processFile = \path ->
content = File.readUtf8!(path) # ! propagates error
parse!(content)
# Explicit error handling
processFileExplicit : Str -> Result Data Str
processFileExplicit = \path ->
when File.readUtf8(path) is
Ok(content) ->
when parse(content) is
Ok(data) -> Ok(data)
Err(ParseErr) -> Err("Parse error")
Err(err) -> Err("File error: \(File.errorToStr(err))")
Why this translation:
- No
raise/rescue in Roc - all errors are values
- File I/O returns
Result, never throws
- Bang functions in Roc propagate errors (not panic like Elixir)
- Error handling is always explicit
- Can't forget to handle errors (type system enforces)
Metaprogramming
Elixir Macros → Roc Alternatives
Roc has no macro system. Elixir's metaprogramming capabilities must be replaced with alternative patterns.
| Elixir Feature |
Roc Alternative |
Notes |
defmacro |
External codegen |
Build-time code generation |
use Module |
Interface composition |
Import and compose interfaces |
quote / unquote |
- |
Not available |
| Protocols |
Abilities |
Auto-derivation, compile-time |
@derive |
Automatic |
Most abilities auto-derived |
| Compile-time code gen |
Build scripts |
External tools generate Roc |
| AST manipulation |
- |
Not supported |
Pattern: Use Directive
Elixir:
defmodule MyGenServer do
use GenServer # Injects callbacks and helpers
@impl true
def init(state), do: {:ok, state}
@impl true
def handle_call(:get, _from, state) do
{:reply, state, state}
end
end
Roc:
# No macro injection - explicit structure
interface MyServer
exposes [State, init, handleGet]
imports []
State : I64
init : I64 -> State
init = \initialValue -> initialValue
handleGet : State -> (I64, State)
handleGet = \state ->
(state, state)
# Platform would provide GenServer-like behavior
# but without macro magic - explicit function signatures
Why this translation:
- No compile-time code injection in Roc
- All functions are explicit
- Behavior is defined by interface contract, not macros
- Platform provides runtime, application provides logic
- More verbose but clearer
Pattern: Protocol Derivation
Elixir:
defmodule User do
@derive {Jason.Encoder, only: [:name, :email]}
@derive Jason.Decoder
defstruct [:name, :email, :age]
end
# Automatic implementation
Jason.encode!(%User{name: "Alice", email: "alice@example.com", age: 30})
Roc:
# Abilities are auto-derived for most types
User : {
name : Str,
email : Str,
age : U32,
}
# Encode/Decode automatically available
user = { name: "Alice", email: "alice@example.com", age: 30 }
encoded = Encode.toBytes(user, Json.utf8)
# For custom encoding (rare):
encodeUser : User -> List U8
encodeUser = \{ name, email, age } ->
# Manual JSON construction if needed
jsonStr = """
{"name":"\(name)","email":"\(email)","age":\(Num.toStr(age))}
"""
Str.toUtf8(jsonStr)
Why this translation:
- Most abilities (Eq, Hash, Inspect, Encode, Decode) auto-derived
- No need for
@derive - happens automatically
- Custom encoding requires explicit functions
- More restrictive but simpler
- No runtime overhead (compile-time derivation)
Pattern: Compile-Time Configuration
Elixir:
defmodule MyApp do
@api_url Application.compile_env(:my_app, :api_url, "https://default.com")
def fetch_data do
HTTPoison.get(@api_url <> "/data")
end
end
Roc:
# No compile-time config in language
# Use build scripts or environment-specific modules
# Option 1: Separate config modules (build-time switch)
# config/prod.roc
apiUrl : Str
apiUrl = "https://prod.com"
# config/dev.roc
apiUrl : Str
apiUrl = "https://dev.com"
# Option 2: Platform environment variables
import pf.Env
fetchData : Task Response [HttpErr, EnvErr]
fetchData =
apiUrl = Env.var!("API_URL") # Runtime config
Http.get("\(apiUrl)/data")
# Option 3: External codegen
# Build script generates config.roc from environment
Why this translation:
- No compile-time metaprogramming in Roc
- Config is either build-time (separate modules) or runtime (Env vars)
- External tools can generate Roc modules
- Simpler language, more predictable builds
- Clear separation of build vs runtime config
Pattern: Macros for DSLs
Elixir:
defmodule Router do
import MyWeb.Router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
end
scope "/", MyWeb do
pipe_through :browser
get "/", PageController, :index
get "/users/:id", UserController, :show
end
end
Roc:
# No DSL macros - use plain data structures
Route : {
method : [Get, Post, Put, Delete],
path : Str,
handler : Request -> Task Response [],
}
Pipeline : List (Request -> Task Request [])
browserPipeline : Pipeline
browserPipeline = [
acceptsHtml,
fetchSession,
]
routes : List Route
routes = [
{ method: Get, path: "/", handler: pageIndex },
{ method: Get, path: "/users/:id", handler: userShow },
]
# Platform provides routing engine that interprets data
# No macros needed - just data and functions
Why this translation:
- DSLs become data structures
- Macros become data transformation functions
- Platform interprets routing data
- More verbose but explicit
- Easier to reason about (no compile-time magic)
Module System Translation
Elixir Modules → Roc Interfaces
| Elixir |
Roc |
Notes |
defmodule |
interface |
Module declaration |
@moduledoc |
Doc comments ## |
Module documentation |
@doc |
Doc comments ## |
Function documentation |
def (public) |
In exposes list |
Public functions |
defp (private) |
Not in exposes |
Private functions |
import |
import |
Import modules |
alias |
- |
Roc uses full names |
use |
- |
No macro injection |
Pattern: Module Organization
Elixir:
# lib/my_app/accounts/user.ex
defmodule MyApp.Accounts.User do
@moduledoc """
User account management.
"""
defstruct [:name, :email, :age]
@doc "Create a new user"
def new(name, email) do
%__MODULE__{name: name, email: email, age: 0}
end
@doc "Update user age"
def update_age(user, age) do
%{user | age: age}
end
defp validate(user), do: # ...
end
# lib/my_app/accounts.ex
defmodule MyApp.Accounts do
alias MyApp.Accounts.User
def create_user(name, email) do
User.new(name, email)
end
end
Roc:
# MyApp/Accounts/User.roc
## User account management
interface User
exposes [User, new, updateAge]
imports []
User : {
name : Str,
email : Str,
age : U32,
}
## Create a new user
new : Str, Str -> User
new = \name, email ->
{ name, email, age: 0 }
## Update user age
updateAge : User, U32 -> User
updateAge = \user, age ->
{ user & age }
# Private function (not exposed)
validate : User -> Bool
validate = \user -> # ...
# MyApp/Accounts.roc
interface Accounts
exposes [createUser]
imports [User]
createUser : Str, Str -> User.User
createUser = \name, email ->
User.new(name, email)
Why this translation:
- File structure mirrors namespace
- Interfaces replace modules
exposes replaces public def
- Documentation uses
## comments
- Imports are explicit (no
alias shorthand)
- Nested namespaces use directory structure
Pattern: Behaviours and Callbacks
Elixir:
defmodule MyBehaviour do
@callback handle(term()) :: {:ok, term()} | {:error, term()}
@callback init(term()) :: {:ok, term()}
end
defmodule MyImplementation do
@behaviour MyBehaviour
@impl true
def init(config), do: {:ok, config}
@impl true
def handle(data), do: {:ok, process(data)}
defp process(data), do: data
end
Roc:
# Behaviours become ability constraints or explicit interfaces
# Option 1: Ability (for polymorphism)
Handler implements
handle : a, Request -> Result Response Err where a implements Handler
init : Config -> Result a Err where a implements Handler
# Option 2: Interface contract (simpler, common case)
interface MyHandler
exposes [State, init, handle]
imports []
State : { config : Config }
init : Config -> Result State Err
init = \config -> Ok({ config })
handle : State, Request -> Result Response Err
handle = \state, request ->
Ok(process(request))
# Private
process : Request -> Response
process = \request -> # ...
Why this translation:
- Behaviours map to abilities (for polymorphism) or interfaces (simpler)
- No
@impl annotations needed (type system checks)
- Callbacks become function signatures in interface
- Type system ensures implementation matches contract
- More restrictive but type-safe
Testing Strategy
Elixir ExUnit → Roc Expect
| Elixir |
Roc |
Notes |
ExUnit.Case |
expect statements |
Inline tests |
test "..." |
expect ... |
No test names |
assert |
expect x == y |
Boolean expressions |
refute |
expect !(x == y) |
Negation |
setup |
- |
No test lifecycle hooks |
describe |
Comments # |
Organizational comments |
| Doctest |
expect in docs |
Inline in documentation |
assert_receive |
- |
No message-based testing |
Pattern: Basic Testing
Elixir:
defmodule MathUtilsTest do
use ExUnit.Case
describe "add/2" do
test "adds two positive numbers" do
assert MathUtils.add(2, 3) == 5
end
test "adds negative numbers" do
assert MathUtils.add(-1, 1) == 0
end
end
describe "divide/2" do
test "divides successfully" do
assert MathUtils.divide(10, 2) == {:ok, 5.0}
end
test "returns error on division by zero" do
assert MathUtils.divide(10, 0) == {:error, :division_by_zero}
end
end
end
Roc:
interface MathUtils
exposes [add, divide]
imports []
add : I64, I64 -> I64
add = \a, b -> a + b
# Tests for add
expect add(2, 3) == 5
expect add(-1, 1) == 0
expect add(0, 0) == 0
divide : F64, F64 -> Result F64 [DivisionByZero]
divide = \a, b ->
if b == 0 then
Err(DivisionByZero)
else
Ok(a / b)
# Tests for divide
expect divide(10, 2) == Ok(5.0)
expect divide(10, 0) == Err(DivisionByZero)
expect
when divide(20, 4) is
Ok(result) -> result == 5.0
Err(_) -> Bool.false
Why this translation:
- No test framework setup needed
expect statements run with roc test
- No test names - expectations speak for themselves
- Inline with code (closer to doctest philosophy)
- Can use pattern matching in expects
Pattern: Doctests
Elixir:
defmodule Calculator do
@doc """
Adds two numbers.
## Examples
iex> Calculator.add(2, 3)
5
iex> Calculator.add(-1, 1)
0
"""
def add(a, b), do: a + b
end
Roc:
interface Calculator
exposes [add]
imports []
## Adds two numbers.
##
## Examples:
##
## ```
## expect add(2, 3) == 5
## expect add(-1, 1) == 0
## ```
add : I64, I64 -> I64
add = \a, b -> a + b
# Actual test expectations (run with roc test)
expect add(2, 3) == 5
expect add(-1, 1) == 0
Why this translation:
- Documentation includes example
expect statements
- Actual tests are separate
expect statements
- No special doctest syntax
- Examples in docs can be copy-pasted as tests
- Simpler mental model
Pattern: Setup and Teardown
Elixir:
defmodule DatabaseTest do
use ExUnit.Case
setup do
{:ok, conn} = Database.connect()
on_exit(fn -> Database.disconnect(conn) end)
{:ok, conn: conn}
end
test "inserts user", %{conn: conn} do
assert {:ok, user} = Database.insert(conn, %User{name: "Alice"})
assert user.name == "Alice"
end
end
Roc:
# No setup/teardown in Roc tests
# Tests are pure - create test data inline
interface Database
exposes [connect, disconnect, insert, User]
imports []
User : { name : Str }
# Tests create their own state
expect
conn = testConnection # Helper for test connections
user = insert(conn, { name: "Alice" })
when user is
Ok(u) -> u.name == "Alice"
Err(_) -> Bool.false
# Helper for test data
testConnection : Connection
testConnection = # Create test connection
Why this translation:
- No setup/teardown hooks
- Tests are pure functions
- Create test data inline or with helper functions
- No shared mutable state between tests
- Simpler but requires more explicit test data creation
Pattern: Property-Based Testing
Elixir:
defmodule StringPropertiesTest do
use ExUnit.Case
use ExUnitProperties
property "reversing twice returns original" do
check all string <- string(:printable) do
assert string |> String.reverse() |> String.reverse() == string
end
end
property "length is preserved when reversing" do
check all string <- string(:alphanumeric) do
assert String.length(string) == String.length(String.reverse(string))
end
end
end
Roc:
# Roc doesn't have built-in property-based testing yet
# Write tests for specific cases or use external tools
# Specific test cases
expect
str = "hello"
str == (str |> Str.reverse |> Str.reverse)
expect
str = "Roc Lang"
str == (str |> Str.reverse |> Str.reverse)
expect
str = ""
str == (str |> Str.reverse |> Str.reverse)
# Length preservation
expect
str = "testing"
Str.countUtf8Bytes(str) == Str.countUtf8Bytes(Str.reverse(str))
Why this translation:
- No built-in property-based testing library yet
- Write representative test cases manually
- Consider external codegen for test generation
- Simpler but less comprehensive
- May evolve as ecosystem matures
Build System and Dependencies
Mix → Roc Platform System
| Elixir (Mix) |
Roc |
Notes |
mix.exs |
app / package header |
Project definition |
deps |
Platform URL |
Dependencies via platforms |
mix deps.get |
Automatic |
Platforms fetched automatically |
mix compile |
roc build |
Build command |
mix test |
roc test |
Test runner |
mix format |
roc format |
Code formatter |
mix run |
roc run |
Run application |
Pattern: Project Confi
…(truncated)
1---2name: convert-elixir-roc3description: Bidirectional conversion between Elixir and Roc. Use when migrating projects between these languages in either direction. Extends meta-convert-dev with Elixir↔Roc specific patterns. Use when migrating Elixir projects to Roc, translating BEAM/OTP patterns to platform-based architecture, or refactoring Elixir codebases. Extends meta-convert-dev with Elixir-to-Roc specific patterns.4metadata:5 source: https://skillmd.com/skills/arustydev/convert-elixir-roc6---78# Elixir ↔ Roc Conversion910Bidirectional conversion between Elixir and Roc. This skill extends `meta-convert-dev` with Elixir↔Roc specific type mappings, idiom translations, and architectural patterns for moving from dynamic, actor-based concurrency to static, pure functional programming with platform-provided effects.1112## This Skill Extends1314- `meta-convert-dev` - Foundational conversion patterns (APTV workflow, testing strategies)1516For general concepts like the Analyze → Plan → Transform → Validate workflow, testing strategies, and common pitfalls, see the meta-skill first.1718## This Skill Adds1920- **Type mappings**: Elixir dynamic types → Roc static types21- **Paradigm translation**: GenServer/OTP patterns → Pure state machines + platform Tasks22- **Idiom translations**: Elixir functional patterns → Roc functional patterns23- **Error handling**: Elixir error tuples + exceptions → Result types24- **Concurrency**: Processes/GenServer → Roc platform Tasks25- **Module system**: Elixir modules → Roc platform/application architecture26- **Metaprogramming**: Elixir macros → Roc abilities and external codegen2728## This Skill Does NOT Cover2930- General conversion methodology - see `meta-convert-dev`31- Elixir language fundamentals - see `lang-elixir-dev`32- Roc language fundamentals - see `lang-roc-dev`3334---3536## Quick Reference3738| Elixir | Roc | Notes |39|--------|-----|-------|40| `:atom` | `[Tag]` | Atoms become tags in tag unions |41| `integer()` | `I64` / `U64` | Specify signedness explicitly |42| `float()` | `F64` | 64-bit float |43| `String.t()` | `Str` | UTF-8 strings |44| `binary()` | `List U8` | Byte sequences |45| `list()` | `List a` | Homogeneous lists |46| `tuple()` | `(a, b, c)` | Fixed-size tuples |47| `map()` | `Dict k v` | Key-value maps (requires Hash+Eq keys) |48| `keyword()` | `List (Str, a)` | List of tuples (no duplicate keys guaranteed) |49| `{:ok, value}` | `Ok(value)` | Success result |50| `{:error, reason}` | `Err(reason)` | Error result |51| `nil` | `None` in tag union | Optional values |52| `pid()` | - | No direct equivalent (platform handles processes) |53| `fn(x) -> x end` | `\x -> x` | Lambda syntax |54| `%{__struct__: Name}` | Opaque type `Name := ...` | Structs become opaque types |5556## When Converting Code57581. **Analyze OTP patterns** before writing Roc - GenServers become pure state machines592. **Identify process boundaries** - these become platform Task interactions603. **Map dynamic patterns to static types** - use tag unions for variants614. **Redesign supervision trees** - Roc platforms handle failure differently625. **Extract pure logic** - separate computation from effects (Task, IO)636. **Handle hot code loading** - not a language feature in Roc647. **Test equivalence** - verify behavior matches despite different architecture6566---6768## Type System Mapping6970### Primitive Types7172| Elixir | Roc | Notes |73|--------|-----|-------|74| `:atom` | `[Tag]` | Atoms as tags in tag unions |75| `integer()` | `I64` | Default signed 64-bit |76| `integer()` | `U64` | Unsigned variant |77| `integer()` (small) | `I32` / `U32` | For smaller values |78| `integer()` (arbitrary) | - | Roc has fixed-size integers |79| `float()` | `F64` | 64-bit floating point |80| `boolean()` | `Bool` | Direct mapping |81| `String.t()` | `Str` | UTF-8 strings |82| `binary()` | `List U8` | Byte sequences |83| `bitstring()` | `List U8` | Byte-aligned only in Roc |84| `nil` | `None` | In tag union `[Some a, None]` |85| `pid()` | - | Processes don't exist in Roc |86| `port()` | - | Platform handles I/O |87| `reference()` | - | No direct equivalent |88| `function()` | Function types | See function mappings below |8990### Collection Types9192| Elixir | Roc | Notes |93|--------|-----|-------|94| `list()` | `List a` | Homogeneous lists (all same type) |95| `[T]` | `List T` | Type-safe, uniform elements |96| `tuple()` | `(A, B, C)` | Fixed-size tuples |97| `{A, B, C}` | `(A, B, C)` | Direct structural mapping |98| `map()` | `Dict k v` | Key-value dictionary (requires Hash+Eq for keys) |99| `%{K => V}` | `Dict K V` | Keys must implement Hash and Eq abilities |100| `MapSet.t()` | `Set a` | Unique values (requires Hash+Eq) |101| `keyword()` | `List (Str, a)` | List of tuples, no uniqueness guarantee |102| `[{:key, value}]` | `List (Str, a)` | Keyword lists as tuple lists |103| `Range.t()` | - | Use `List.range` to generate lists |104| `Stream.t()` | - | Roc has lazy iterators but no Stream type |105106### Composite Types107108| Elixir | Roc | Notes |109|--------|-----|-------|110| `defstruct` | `{ field : Type }` | Structs become records |111| `%Name{field: value}` | `{ field: value }` | Record literals |112| Tagged tuple `{:tag, value}` | `Tag(value)` | Tags with payloads |113| `@type name :: spec` | `Name : Type` | Type alias |114| `@opaque name :: spec` | Opaque type `Name := Type` | Hidden implementation |115| `@spec` annotations | Type signatures | Enforced in Roc |116117### Function Types118119| Elixir | Roc | Notes |120|--------|-----|-------|121| `(-> R)` | `({} -> R)` | Zero-argument function |122| `(A -> R)` | `(A -> R)` | Single argument |123| `(A, B -> R)` | `(A, B -> R)` | Multiple arguments (curried) |124| Variable arity | - | Roc doesn't support varargs |125| Default arguments | - | Use separate function signatures |126127### Error Types128129| Elixir | Roc | Notes |130|--------|-----|-------|131| `{:ok, value}` | `Ok(value)` | Success case |132| `{:error, reason}` | `Err(reason)` | Error case |133| `:ok` atom | `Ok({})` | Success with no value |134| `{:ok, V} \| {:error, R}` | `Result V R` | Result type |135| Exception raising | `Err` variant | No exceptions, use Result |136| `rescue` clause | Pattern match on Result | Explicit error handling |137138---139140## Idiom Translation141142### Pattern 1: Simple Module Conversion143144**Elixir:**145```elixir146defmodule MathUtils do147 @doc "Add two numbers"148 def add(a, b), do: a + b149150 @doc "Square a number"151 def square(n), do: n * n152153 # Private function154 defp internal_helper(x), do: x * 2155end156```157158**Roc:**159```roc160interface MathUtils161 exposes [add, square]162 imports []163164## Add two numbers165add : I64, I64 -> I64166add = \a, b -> a + b167168## Square a number169square : I64 -> I64170square = \n -> n * n171172# Private helper (not exposed)173internalHelper : I64 -> I64174internalHelper = \x -> x * 2175```176177**Why this translation:**178- Elixir modules become Roc interfaces179- Public functions go in `exposes`180- Private functions are simply not exposed181- Doctests become inline `expect` tests in Roc182- Type signatures are explicit (not optional like typespecs)183184### Pattern 2: Pattern Matching on Tagged Tuples185186**Elixir:**187```elixir188def process_result({:ok, data}) do189 {:success, data}190end191192def process_result({:error, reason}) do193 {:failure, reason}194end195196def process_result(_unknown) do197 {:failure, :unknown_result}198end199```200201**Roc:**202```roc203processResult : [Ok Data, Err Reason, Unknown] -> [Success Data, Failure Reason]204processResult = \result ->205 when result is206 Ok(data) -> Success(data)207 Err(reason) -> Failure(reason)208 Unknown -> Failure(UnknownResult)209```210211**Why this translation:**212- Elixir tagged tuples map to Roc tags213- Pattern matching syntax is similar (`when` vs pattern match in function head)214- Tag unions make all cases explicit in type signature215- Type system ensures exhaustiveness (can't forget cases)216217### Pattern 3: Pipe Operator218219**Elixir:**220```elixir221def process_data(data) do222 data223 |> String.trim()224 |> String.downcase()225 |> String.split(",")226 |> Enum.map(&String.trim/1)227 |> Enum.reject(&(&1 == ""))228end229```230231**Roc:**232```roc233processData : Str -> List Str234processData = \data ->235 data236 |> Str.trim237 |> Str.toLowercase238 |> Str.split(",")239 |> List.map(Str.trim)240 |> List.keepIf(\s -> s != "")241```242243**Why this translation:**244- Both languages have pipe operators with similar semantics245- Roc uses `keepIf` instead of `reject` with negated predicate246- Capture operator `&` in Elixir becomes explicit lambdas in Roc247- Type inference works similarly in both248249### Pattern 4: Enum Operations250251**Elixir:**252```elixir253def sum(list), do: Enum.reduce(list, 0, &+/2)254255def squares(list), do: Enum.map(list, fn x -> x * x end)256257def evens(list), do: Enum.filter(list, fn x -> rem(x, 2) == 0 end)258259def find_first_large(list) do260 Enum.find(list, fn x -> x > 100 end)261end262```263264**Roc:**265```roc266sum : List I64 -> I64267sum = \list ->268 List.walk(list, 0, Num.add)269270squares : List I64 -> List I64271squares = \list ->272 List.map(list, \x -> x * x)273274evens : List I64 -> List I64275evens = \list ->276 List.keepIf(list, \x -> x % 2 == 0)277278findFirstLarge : List I64 -> [Some I64, None]279findFirstLarge = \list ->280 list281 |> List.findFirst(\x -> x > 100)282 |> Result.map(Some)283 |> Result.withDefault(None)284```285286**Why this translation:**287- `Enum.reduce` becomes `List.walk` (fold)288- `Enum.filter` becomes `List.keepIf`289- `Enum.find` returns `Result`, needs conversion to option type290- Function captures (`&+/2`) become explicit function references (`Num.add`)291- Roc requires explicit handling of "not found" cases292293### Pattern 5: Struct to Record294295**Elixir:**296```elixir297defmodule User do298 defstruct [:name, :email, age: 0]299300 def new(name, email) do301 %User{name: name, email: email}302 end303304 def update_age(user, new_age) do305 %{user | age: new_age}306 end307308 def greet(%User{name: name}), do: "Hello, #{name}!"309end310```311312**Roc:**313```roc314interface User315 exposes [User, new, updateAge, greet]316 imports []317318User : {319 name : Str,320 email : Str,321 age : U32,322}323324new : Str, Str -> User325new = \name, email ->326 { name, email, age: 0 }327328updateAge : User, U32 -> User329updateAge = \user, newAge ->330 { user & age: newAge }331332greet : User -> Str333greet = \{ name } ->334 "Hello, \(name)!"335```336337**Why this translation:**338- Elixir structs map directly to Roc records339- Record update syntax is similar (`%{user | age:}` vs `{ user & age:}`)340- Pattern matching on records works similarly341- Roc records are structural (no `__struct__` metadata)342- Default values in struct definition become default in constructor343344### Pattern 6: GenServer → Pure State Machine345346**Elixir:**347```elixir348defmodule Counter do349 use GenServer350351 # Client API352353 def start_link(initial_value) do354 GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)355 end356357 def increment do358 GenServer.cast(__MODULE__, :increment)359 end360361 def get do362 GenServer.call(__MODULE__, :get)363 end364365 # Server Callbacks366367 @impl true368 def init(initial_value) do369 {:ok, initial_value}370 end371372 @impl true373 def handle_call(:get, _from, state) do374 {:reply, state, state}375 end376377 @impl true378 def handle_cast(:increment, state) do379 {:noreply, state + 1}380 end381end382```383384**Roc:**385```roc386# Pure state machine - no processes387interface Counter388 exposes [State, init, increment, get]389 imports []390391State : I64392393init : State394init = 0395396increment : State -> State397increment = \count ->398 count + 1399400get : State -> I64401get = \count ->402 count403404# If you need effects, use platform Tasks405# The platform would provide state management and concurrency406# Application code remains pure407```408409**Why this translation:**410- GenServer becomes pure state functions411- No process lifecycle - just data transformation412- State is explicit parameter and return value413- `call` operations become synchronous functions that return new state414- `cast` operations become functions that just transform state415- Effects and concurrency are platform responsibilities, not shown here416- Platform provides state management if needed417418### Pattern 7: With Statement Error Handling419420**Elixir:**421```elixir422def create_user(params) do423 with {:ok, validated} <- validate_params(params),424 {:ok, user} <- insert_user(validated),425 {:ok, _email} <- send_welcome_email(user) do426 {:ok, user}427 else428 {:error, reason} -> {:error, reason}429 end430end431```432433**Roc:**434```roc435createUser : Params -> Result User [ValidationErr, InsertErr, EmailErr]436createUser = \params ->437 validated = validateParams!(params)438 user = insertUser!(validated)439 _email = sendWelcomeEmail!(user)440 Ok(user)441```442443**Why this translation:**444- Elixir `with` becomes Roc `!` operator (try/propagate)445- `!` suffix propagates errors automatically446- Error types are unified in tag union447- Early return on error is implicit with `!`448- More concise than explicit pattern matching449450### Pattern 8: Optional Values451452**Elixir:**453```elixir454def find_user(id, users) do455 Enum.find(users, fn user -> user.id == id end)456end457458def get_email(nil), do: "no email"459def get_email(user), do: user.email460461# Using in pipeline462def display_email(id, users) do463 users464 |> find_user(id)465 |> case do466 nil -> "User not found"467 user -> user.email468 end469end470```471472**Roc:**473```roc474findUser : U64, List User -> [Some User, None]475findUser = \id, users ->476 users477 |> List.findFirst(\user -> user.id == id)478 |> Result.map(Some)479 |> Result.withDefault(None)480481getEmail : [Some User, None] -> Str482getEmail = \maybeUser ->483 when maybeUser is484 Some({ email }) -> email485 None -> "no email"486487displayEmail : U64, List User -> Str488displayEmail = \id, users ->489 when findUser(id, users) is490 Some(user) -> user.email491 None -> "User not found"492```493494**Why this translation:**495- Elixir `nil` maps to `None` in tag union496- `Enum.find` returns `nil` or value; Roc `findFirst` returns `Result`497- Explicit pattern matching on option types498- Type system prevents forgetting to handle `None` case499- Must convert `Result` to option type with `Some`/`None`500501### Pattern 9: List Comprehensions502503**Elixir:**504```elixir505def squares(list) do506 for x <- list, do: x * x507end508509def evens(list) do510 for x <- list, rem(x, 2) == 0, do: x511end512513def cartesian_product(list1, list2) do514 for x <- list1, y <- list2, do: {x, y}515end516517def filtered_map(list) do518 for x <- list, x > 0, into: %{}, do: {x, x * x}519end520```521522**Roc:**523```roc524squares : List I64 -> List I64525squares = \list ->526 List.map(list, \x -> x * x)527528evens : List I64 -> List I64529evens = \list ->530 List.keepIf(list, \x -> x % 2 == 0)531532cartesianProduct : List a, List b -> List (a, b)533cartesianProduct = \list1, list2 ->534 List.joinMap(list1, \x ->535 List.map(list2, \y -> (x, y))536 )537538filteredMap : List I64 -> Dict I64 I64539filteredMap = \list ->540 list541 |> List.keepIf(\x -> x > 0)542 |> List.map(\x -> (x, x * x))543 |> Dict.fromList544```545546**Why this translation:**547- Comprehensions become `map`/`keepIf` operations548- Nested comprehensions use `joinMap` (flatMap/concatMap)549- Filters become `keepIf`550- `into: %{}` becomes `Dict.fromList`551- More verbose but explicit552- Type signatures make intent clear553554### Pattern 10: Protocol Implementation555556**Elixir:**557```elixir558defprotocol Serializable do559 @doc "Serialize to JSON"560 def to_json(data)561end562563defimpl Serializable, for: Map do564 def to_json(map) do565 Jason.encode!(map)566 end567end568569defimpl Serializable, for: List do570 def to_json(list) do571 Jason.encode!(list)572 end573end574575# Usage576Serializable.to_json(%{name: "Alice"})577```578579**Roc:**580```roc581# Roc uses abilities (similar to typeclasses)582# Built-in Encode ability is auto-derived for most types583584# For custom encoding:585toJson : a -> Str where a implements Encode586toJson = \value ->587 value588 |> Encode.toBytes(Json.utf8)589 |> Str.fromUtf8590591# Automatic for records and tags592user = { name: "Alice", age: 30 }593json = toJson(user) # Works automatically594595# For custom types with specific behavior:596User := { name : Str, age : U32 }597598toJsonUser : User -> Str599toJsonUser = \@User({ name, age }) ->600 """601 {\"name\": \"\(name)\", \"age\": \(Num.toStr(age))}602 """603```604605**Why this translation:**606- Elixir protocols map to Roc abilities607- Many abilities are auto-derived (Encode, Decode, Eq, Hash, Inspect)608- For custom behavior, write explicit functions609- No dynamic dispatch in Roc - abilities are compile-time610- Roc's approach is more restrictive but type-safe611612---613614## Concurrency Patterns615616### Elixir Process Model vs Roc Task Model617618Elixir's concurrency is built on lightweight BEAM processes with message passing. Roc has no built-in concurrency - it's all platform-provided through Tasks.619620**Mental Model Shift:**621622| Elixir Concept | Roc Approach | Key Insight |623|----------------|--------------|-------------|624| Process with state | Pure state machine + platform Task | Data and behavior separated |625| Message passing | Function parameters and results | Explicit data flow, no mailboxes |626| `spawn` | Platform Task creation | Effects are platform capability |627| GenServer | Pure functions + Task orchestration | Business logic pure, I/O delegated |628| Supervisor | Platform-level concern | Fault tolerance in host |629| Hot code reload | Not available | Platform restart required |630631### Pattern: Spawned Task632633**Elixir:**634```elixir635defmodule Worker do636 def start do637 spawn(fn -> loop() end)638 end639640 defp loop do641 receive do642 {:work, from, data} ->643 result = process(data)644 send(from, {:result, result})645 loop()646 :stop ->647 :ok648 end649 end650651 defp process(data), do: String.upcase(data)652end653654# Usage655pid = Worker.start()656send(pid, {:work, self(), "hello"})657receive do658 {:result, result} -> IO.puts(result)659end660```661662**Roc:**663```roc664# Pure processing function665process : Str -> Str666process = \data ->667 Str.toUppercase(data)668669# If concurrency is needed, platform provides it670import pf.Task exposing [Task]671672processAsync : Str -> Task Str []673processAsync = \data ->674 # Platform handles concurrent execution675 Task.await(Task.fromThunk(\{} -> process(data)))676677# Usage (in Task context)678main : Task {} []679main =680 result = processAsync!("hello")681 Stdout.line!(result)682```683684**Why this translation:**685- No process spawning in Roc - platform handles concurrency686- Pure function for business logic (`process`)687- Platform Task for effects688- No message passing - direct function composition689- Platform decides execution strategy (sync/async/parallel)690691### Pattern: GenServer State692693**Elixir:**694```elixir695defmodule Cache do696 use GenServer697698 def start_link do699 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)700 end701702 def get(key) do703 GenServer.call(__MODULE__, {:get, key})704 end705706 def put(key, value) do707 GenServer.cast(__MODULE__, {:put, key, value})708 end709710 @impl true711 def init(_), do: {:ok, %{}}712713 @impl true714 def handle_call({:get, key}, _from, state) do715 {:reply, Map.get(state, key), state}716 end717718 @impl true719 def handle_cast({:put, key, value}, state) do720 {:noreply, Map.put(state, key, value)}721 end722end723```724725**Roc:**726```roc727# Pure state functions728State : Dict Str Str729730init : State731init = Dict.empty({})732733get : State, Str -> [Some Str, None]734get = \state, key ->735 Dict.get(state, key)736 |> Result.map(Some)737 |> Result.withDefault(None)738739put : State, Str, Str -> State740put = \state, key, value ->741 Dict.insert(state, key, value)742743# Platform would provide state management744# For example, a hypothetical Agent-like platform API:745#746# import pf.Agent exposing [Agent, start, getState, updateState]747#748# cacheAgent : Agent State749# cacheAgent = start(init)750#751# getValue : Str -> Task [Some Str, None] []752# getValue = \key ->753# Agent.getState(cacheAgent, \state -> get(state, key))754#755# putValue : Str, Str -> Task {} []756# putValue = \key, value ->757# Agent.updateState(cacheAgent, \state -> put(state, key, value))758```759760**Why this translation:**761- GenServer becomes pure state transformations762- State management delegated to platform (Agent, Store, etc.)763- No process registered names - platform handles references764- No `call` vs `cast` distinction - just sync vs async Task765- Fault tolerance handled by platform, not supervision tree766767### Pattern: Task.async768769**Elixir:**770```elixir771def fetch_multiple(urls) do772 tasks = Enum.map(urls, fn url ->773 Task.async(fn -> fetch_url(url) end)774 end)775776 Task.await_many(tasks, 5000)777end778779defp fetch_url(url) do780 case HTTPoison.get(url) do781 {:ok, %{body: body}} -> {:ok, body}782 {:error, reason} -> {:error, reason}783 end784end785```786787**Roc:**788```roc789import pf.Http790import pf.Task exposing [Task]791792fetchMultiple : List Str -> Task (List Str) [HttpErr]793fetchMultiple = \urls ->794 urls795 |> List.map(\url -> Http.get(url))796 |> Task.sequence # Platform may execute concurrently797 |> Task.map(\responses -> List.map(responses, \r -> r.body))798799# Platform-specific concurrent execution800# Some platforms may provide parallel primitives:801# fetchMultipleParallel : List Str -> Task (List Str) [HttpErr]802# fetchMultipleParallel = \urls ->803# Task.parallel(List.map(urls, Http.get))804```805806**Why this translation:**807- `Task.async` maps to platform Task creation808- Platform decides concurrency strategy809- `Task.sequence` combines multiple Tasks810- Timeout is platform-specific (may be in Task API)811- No separate "await" - composition with `!` or `Task.map`812813### Pattern: Agent State814815**Elixir:**816```elixir817defmodule Counter do818 use Agent819820 def start_link(_opts) do821 Agent.start_link(fn -> 0 end, name: __MODULE__)822 end823824 def increment do825 Agent.update(__MODULE__, &(&1 + 1))826 end827828 def get do829 Agent.get(__MODULE__, & &1)830 end831end832```833834**Roc:**835```roc836# Pure state functions837State : I64838839init : State840init = 0841842increment : State -> State843increment = \count -> count + 1844845get : State -> I64846get = \count -> count847848# Hypothetical platform API for stateful agents849# (actual API depends on platform)850#851# import pf.Agent exposing [Agent]852#853# counterAgent : Agent State854# counterAgent = Agent.start(init)855#856# incrementCounter : Task {} []857# incrementCounter =858# Agent.update(counterAgent, increment)859#860# getCounter : Task I64 []861# getCounter =862# Agent.get(counterAgent, get)863```864865**Why this translation:**866- Agent pattern becomes pure state + platform state management867- No global registered names - agent references are explicit868- Updates are explicit functions, not anonymous lambdas869- Platform provides concurrency-safe state updates870- Business logic (increment, get) remains pure and testable871872---873874## Error Handling875876### Elixir Error Model → Roc Result Type877878| Elixir Pattern | Roc Pattern | Translation Strategy |879|----------------|-------------|----------------------|880| `{:ok, value}` | `Ok(value)` | Direct mapping |881| `{:error, reason}` | `Err(reason)` | Direct mapping |882| `raise/1` | `Err` variant | No exceptions in Roc |883| `rescue` clause | Pattern match on `Result` | Explicit error handling |884| `try/rescue` | `Result` combinators | Compose with `Result.try`, `Result.map` |885| Multiple error tuples | Tag union error type | `[Err1, Err2, Err3]` |886| `!` (bang) functions | Regular functions returning `Result` | All errors explicit |887888### Pattern: Error Propagation889890**Elixir:**891```elixir892def calculate(a, b, c) do893 with {:ok, x} <- divide(a, b),894 {:ok, y} <- divide(x, c) do895 {:ok, y}896 else897 {:error, reason} -> {:error, reason}898 end899end900901# Or using the ! convention:902def calculate!(a, b, c) do903 x = divide!(a, b)904 y = divide!(x, c)905 y906end907```908909**Roc:**910```roc911calculate : I64, I64, I64 -> Result I64 [DivByZero]912calculate = \a, b, c ->913 x = divide!(a, b) # Propagates error automatically914 y = divide!(x, c)915 Ok(y)916917# Or explicitly:918calculateExplicit : I64, I64, I64 -> Result I64 [DivByZero]919calculateExplicit = \a, b, c ->920 divide(a, b)921 |> Result.try(\x ->922 divide(x, c)923 )924```925926**Why this translation:**927- Elixir `with` becomes Roc `!` operator928- `!` in Roc is try/propagate (not unwrap/crash like Elixir!)929- Both patterns allow early return on error930- Roc's approach is more concise931- Type system ensures all errors are handled932933### Pattern: Multiple Error Types934935**Elixir:**936```elixir937defmodule Parser do938 def parse_and_save(input) do939 with {:ok, data} <- parse(input),940 {:ok, validated} <- validate(data),941 :ok <- save(validated) do942 {:ok, validated}943 else944 {:error, :invalid_format} -> {:error, "Invalid format"}945 {:error, :validation_failed, msg} -> {:error, "Validation: #{msg}"}946 {:error, :save_failed} -> {:error, "Could not save"}947 end948 end949end950```951952**Roc:**953```roc954parseAndSave : Str -> Result Data [InvalidFormat, ValidationFailed Str, SaveFailed]955parseAndSave = \input ->956 data = parse!(input) # Returns Result Data [InvalidFormat]957 validated = validate!(data) # Returns Result Data [ValidationFailed Str]958 save!(validated) # Returns Result {} [SaveFailed]959 Ok(validated)960961# Error handling with descriptive messages962parseAndSaveWithMsg : Str -> Result Data Str963parseAndSaveWithMsg = \input ->964 parseAndSave(input)965 |> Result.mapErr(\err ->966 when err is967 InvalidFormat -> "Invalid format"968 ValidationFailed(msg) -> "Validation: \(msg)"969 SaveFailed -> "Could not save"970 )971```972973**Why this translation:**974- Elixir error atoms map to Roc tag variants975- Error payloads become tag parameters976- `!` operator unifies error types automatically977- `Result.mapErr` converts to user-friendly messages978- Type signature documents all possible errors979980### Pattern: Raise and Rescue981982**Elixir:**983```elixir984def process_file(path) do985 content = File.read!(path) # Raises on error986 parse(content)987rescue988 e in File.Error -> {:error, "File error: #{e.message}"}989 e in ArgumentError -> {:error, "Invalid arguments"}990end991992# Safer alternative993def process_file_safe(path) do994 case File.read(path) do995 {:ok, content} -> parse(content)996 {:error, reason} -> {:error, "File error: #{inspect(reason)}"}997 end998end999```10001001**Roc:**1002```roc1003# Roc has no exceptions - all errors are Result types1004import pf.File10051006processFile : Str -> Result Data [FileErr Str, ParseErr]1007processFile = \path ->1008 content = File.readUtf8!(path) # ! propagates error1009 parse!(content)10101011# Explicit error handling1012processFileExplicit : Str -> Result Data Str1013processFileExplicit = \path ->1014 when File.readUtf8(path) is1015 Ok(content) ->1016 when parse(content) is1017 Ok(data) -> Ok(data)1018 Err(ParseErr) -> Err("Parse error")1019 Err(err) -> Err("File error: \(File.errorToStr(err))")1020```10211022**Why this translation:**1023- No `raise`/`rescue` in Roc - all errors are values1024- File I/O returns `Result`, never throws1025- Bang functions in Roc propagate errors (not panic like Elixir)1026- Error handling is always explicit1027- Can't forget to handle errors (type system enforces)10281029---10301031## Metaprogramming10321033### Elixir Macros → Roc Alternatives10341035Roc has no macro system. Elixir's metaprogramming capabilities must be replaced with alternative patterns.10361037| Elixir Feature | Roc Alternative | Notes |1038|----------------|-----------------|-------|1039| `defmacro` | External codegen | Build-time code generation |1040| `use Module` | Interface composition | Import and compose interfaces |1041| `quote` / `unquote` | - | Not available |1042| Protocols | Abilities | Auto-derivation, compile-time |1043| `@derive` | Automatic | Most abilities auto-derived |1044| Compile-time code gen | Build scripts | External tools generate Roc |1045| AST manipulation | - | Not supported |10461047### Pattern: Use Directive10481049**Elixir:**1050```elixir1051defmodule MyGenServer do1052 use GenServer # Injects callbacks and helpers10531054 @impl true1055 def init(state), do: {:ok, state}10561057 @impl true1058 def handle_call(:get, _from, state) do1059 {:reply, state, state}1060 end1061end1062```10631064**Roc:**1065```roc1066# No macro injection - explicit structure1067interface MyServer1068 exposes [State, init, handleGet]1069 imports []10701071State : I6410721073init : I64 -> State1074init = \initialValue -> initialValue10751076handleGet : State -> (I64, State)1077handleGet = \state ->1078 (state, state)10791080# Platform would provide GenServer-like behavior1081# but without macro magic - explicit function signatures1082```10831084**Why this translation:**1085- No compile-time code injection in Roc1086- All functions are explicit1087- Behavior is defined by interface contract, not macros1088- Platform provides runtime, application provides logic1089- More verbose but clearer10901091### Pattern: Protocol Derivation10921093**Elixir:**1094```elixir1095defmodule User do1096 @derive {Jason.Encoder, only: [:name, :email]}1097 @derive Jason.Decoder10981099 defstruct [:name, :email, :age]1100end11011102# Automatic implementation1103Jason.encode!(%User{name: "Alice", email: "alice@example.com", age: 30})1104```11051106**Roc:**1107```roc1108# Abilities are auto-derived for most types1109User : {1110 name : Str,1111 email : Str,1112 age : U32,1113}11141115# Encode/Decode automatically available1116user = { name: "Alice", email: "alice@example.com", age: 30 }1117encoded = Encode.toBytes(user, Json.utf8)11181119# For custom encoding (rare):1120encodeUser : User -> List U81121encodeUser = \{ name, email, age } ->1122 # Manual JSON construction if needed1123 jsonStr = """1124 {"name":"\(name)","email":"\(email)","age":\(Num.toStr(age))}1125 """1126 Str.toUtf8(jsonStr)1127```11281129**Why this translation:**1130- Most abilities (Eq, Hash, Inspect, Encode, Decode) auto-derived1131- No need for `@derive` - happens automatically1132- Custom encoding requires explicit functions1133- More restrictive but simpler1134- No runtime overhead (compile-time derivation)11351136### Pattern: Compile-Time Configuration11371138**Elixir:**1139```elixir1140defmodule MyApp do1141 @api_url Application.compile_env(:my_app, :api_url, "https://default.com")11421143 def fetch_data do1144 HTTPoison.get(@api_url <> "/data")1145 end1146end1147```11481149**Roc:**1150```roc1151# No compile-time config in language1152# Use build scripts or environment-specific modules11531154# Option 1: Separate config modules (build-time switch)1155# config/prod.roc1156apiUrl : Str1157apiUrl = "https://prod.com"11581159# config/dev.roc1160apiUrl : Str1161apiUrl = "https://dev.com"11621163# Option 2: Platform environment variables1164import pf.Env11651166fetchData : Task Response [HttpErr, EnvErr]1167fetchData =1168 apiUrl = Env.var!("API_URL") # Runtime config1169 Http.get("\(apiUrl)/data")11701171# Option 3: External codegen1172# Build script generates config.roc from environment1173```11741175**Why this translation:**1176- No compile-time metaprogramming in Roc1177- Config is either build-time (separate modules) or runtime (Env vars)1178- External tools can generate Roc modules1179- Simpler language, more predictable builds1180- Clear separation of build vs runtime config11811182### Pattern: Macros for DSLs11831184**Elixir:**1185```elixir1186defmodule Router do1187 import MyWeb.Router11881189 pipeline :browser do1190 plug :accepts, ["html"]1191 plug :fetch_session1192 end11931194 scope "/", MyWeb do1195 pipe_through :browser11961197 get "/", PageController, :index1198 get "/users/:id", UserController, :show1199 end1200end1201```12021203**Roc:**1204```roc1205# No DSL macros - use plain data structures1206Route : {1207 method : [Get, Post, Put, Delete],1208 path : Str,1209 handler : Request -> Task Response [],1210}12111212Pipeline : List (Request -> Task Request [])12131214browserPipeline : Pipeline1215browserPipeline = [1216 acceptsHtml,1217 fetchSession,1218]12191220routes : List Route1221routes = [1222 { method: Get, path: "/", handler: pageIndex },1223 { method: Get, path: "/users/:id", handler: userShow },1224]12251226# Platform provides routing engine that interprets data1227# No macros needed - just data and functions1228```12291230**Why this translation:**1231- DSLs become data structures1232- Macros become data transformation functions1233- Platform interprets routing data1234- More verbose but explicit1235- Easier to reason about (no compile-time magic)12361237---12381239## Module System Translation12401241### Elixir Modules → Roc Interfaces12421243| Elixir | Roc | Notes |1244|--------|-----|-------|1245| `defmodule` | `interface` | Module declaration |1246| `@moduledoc` | Doc comments `##` | Module documentation |1247| `@doc` | Doc comments `##` | Function documentation |1248| `def` (public) | In `exposes` list | Public functions |1249| `defp` (private) | Not in `exposes` | Private functions |1250| `import` | `import` | Import modules |1251| `alias` | - | Roc uses full names |1252| `use` | - | No macro injection |12531254### Pattern: Module Organization12551256**Elixir:**1257```elixir1258# lib/my_app/accounts/user.ex1259defmodule MyApp.Accounts.User do1260 @moduledoc """1261 User account management.1262 """12631264 defstruct [:name, :email, :age]12651266 @doc "Create a new user"1267 def new(name, email) do1268 %__MODULE__{name: name, email: email, age: 0}1269 end12701271 @doc "Update user age"1272 def update_age(user, age) do1273 %{user | age: age}1274 end12751276 defp validate(user), do: # ...1277end12781279# lib/my_app/accounts.ex1280defmodule MyApp.Accounts do1281 alias MyApp.Accounts.User12821283 def create_user(name, email) do1284 User.new(name, email)1285 end1286end1287```12881289**Roc:**1290```roc1291# MyApp/Accounts/User.roc1292## User account management1293interface User1294 exposes [User, new, updateAge]1295 imports []12961297User : {1298 name : Str,1299 email : Str,1300 age : U32,1301}13021303## Create a new user1304new : Str, Str -> User1305new = \name, email ->1306 { name, email, age: 0 }13071308## Update user age1309updateAge : User, U32 -> User1310updateAge = \user, age ->1311 { user & age }13121313# Private function (not exposed)1314validate : User -> Bool1315validate = \user -> # ...13161317# MyApp/Accounts.roc1318interface Accounts1319 exposes [createUser]1320 imports [User]13211322createUser : Str, Str -> User.User1323createUser = \name, email ->1324 User.new(name, email)1325```13261327**Why this translation:**1328- File structure mirrors namespace1329- Interfaces replace modules1330- `exposes` replaces public `def`1331- Documentation uses `##` comments1332- Imports are explicit (no `alias` shorthand)1333- Nested namespaces use directory structure13341335### Pattern: Behaviours and Callbacks13361337**Elixir:**1338```elixir1339defmodule MyBehaviour do1340 @callback handle(term()) :: {:ok, term()} | {:error, term()}1341 @callback init(term()) :: {:ok, term()}1342end13431344defmodule MyImplementation do1345 @behaviour MyBehaviour13461347 @impl true1348 def init(config), do: {:ok, config}13491350 @impl true1351 def handle(data), do: {:ok, process(data)}13521353 defp process(data), do: data1354end1355```13561357**Roc:**1358```roc1359# Behaviours become ability constraints or explicit interfaces13601361# Option 1: Ability (for polymorphism)1362Handler implements1363 handle : a, Request -> Result Response Err where a implements Handler1364 init : Config -> Result a Err where a implements Handler13651366# Option 2: Interface contract (simpler, common case)1367interface MyHandler1368 exposes [State, init, handle]1369 imports []13701371State : { config : Config }13721373init : Config -> Result State Err1374init = \config -> Ok({ config })13751376handle : State, Request -> Result Response Err1377handle = \state, request ->1378 Ok(process(request))13791380# Private1381process : Request -> Response1382process = \request -> # ...1383```13841385**Why this translation:**1386- Behaviours map to abilities (for polymorphism) or interfaces (simpler)1387- No `@impl` annotations needed (type system checks)1388- Callbacks become function signatures in interface1389- Type system ensures implementation matches contract1390- More restrictive but type-safe13911392---13931394## Testing Strategy13951396### Elixir ExUnit → Roc Expect13971398| Elixir | Roc | Notes |1399|--------|-----|-------|1400| `ExUnit.Case` | `expect` statements | Inline tests |1401| `test "..."` | `expect ...` | No test names |1402| `assert` | `expect x == y` | Boolean expressions |1403| `refute` | `expect !(x == y)` | Negation |1404| `setup` | - | No test lifecycle hooks |1405| `describe` | Comments `#` | Organizational comments |1406| Doctest | `expect` in docs | Inline in documentation |1407| `assert_receive` | - | No message-based testing |14081409### Pattern: Basic Testing14101411**Elixir:**1412```elixir1413defmodule MathUtilsTest do1414 use ExUnit.Case14151416 describe "add/2" do1417 test "adds two positive numbers" do1418 assert MathUtils.add(2, 3) == 51419 end14201421 test "adds negative numbers" do1422 assert MathUtils.add(-1, 1) == 01423 end1424 end14251426 describe "divide/2" do1427 test "divides successfully" do1428 assert MathUtils.divide(10, 2) == {:ok, 5.0}1429 end14301431 test "returns error on division by zero" do1432 assert MathUtils.divide(10, 0) == {:error, :division_by_zero}1433 end1434 end1435end1436```14371438**Roc:**1439```roc1440interface MathUtils1441 exposes [add, divide]1442 imports []14431444add : I64, I64 -> I641445add = \a, b -> a + b14461447# Tests for add1448expect add(2, 3) == 51449expect add(-1, 1) == 01450expect add(0, 0) == 014511452divide : F64, F64 -> Result F64 [DivisionByZero]1453divide = \a, b ->1454 if b == 0 then1455 Err(DivisionByZero)1456 else1457 Ok(a / b)14581459# Tests for divide1460expect divide(10, 2) == Ok(5.0)1461expect divide(10, 0) == Err(DivisionByZero)1462expect1463 when divide(20, 4) is1464 Ok(result) -> result == 5.01465 Err(_) -> Bool.false1466```14671468**Why this translation:**1469- No test framework setup needed1470- `expect` statements run with `roc test`1471- No test names - expectations speak for themselves1472- Inline with code (closer to doctest philosophy)1473- Can use pattern matching in expects14741475### Pattern: Doctests14761477**Elixir:**1478```elixir1479defmodule Calculator do1480 @doc """1481 Adds two numbers.14821483 ## Examples14841485 iex> Calculator.add(2, 3)1486 514871488 iex> Calculator.add(-1, 1)1489 01490 """1491 def add(a, b), do: a + b1492end1493```14941495**Roc:**1496```roc1497interface Calculator1498 exposes [add]1499 imports []15001501## Adds two numbers.1502##1503## Examples:1504##1505## ```1506## expect add(2, 3) == 51507## expect add(-1, 1) == 01508## ```1509add : I64, I64 -> I641510add = \a, b -> a + b15111512# Actual test expectations (run with roc test)1513expect add(2, 3) == 51514expect add(-1, 1) == 01515```15161517**Why this translation:**1518- Documentation includes example `expect` statements1519- Actual tests are separate `expect` statements1520- No special doctest syntax1521- Examples in docs can be copy-pasted as tests1522- Simpler mental model15231524### Pattern: Setup and Teardown15251526**Elixir:**1527```elixir1528defmodule DatabaseTest do1529 use ExUnit.Case15301531 setup do1532 {:ok, conn} = Database.connect()1533 on_exit(fn -> Database.disconnect(conn) end)1534 {:ok, conn: conn}1535 end15361537 test "inserts user", %{conn: conn} do1538 assert {:ok, user} = Database.insert(conn, %User{name: "Alice"})1539 assert user.name == "Alice"1540 end1541end1542```15431544**Roc:**1545```roc1546# No setup/teardown in Roc tests1547# Tests are pure - create test data inline15481549interface Database1550 exposes [connect, disconnect, insert, User]1551 imports []15521553User : { name : Str }15541555# Tests create their own state1556expect1557 conn = testConnection # Helper for test connections1558 user = insert(conn, { name: "Alice" })1559 when user is1560 Ok(u) -> u.name == "Alice"1561 Err(_) -> Bool.false15621563# Helper for test data1564testConnection : Connection1565testConnection = # Create test connection1566```15671568**Why this translation:**1569- No setup/teardown hooks1570- Tests are pure functions1571- Create test data inline or with helper functions1572- No shared mutable state between tests1573- Simpler but requires more explicit test data creation15741575### Pattern: Property-Based Testing15761577**Elixir:**1578```elixir1579defmodule StringPropertiesTest do1580 use ExUnit.Case1581 use ExUnitProperties15821583 property "reversing twice returns original" do1584 check all string <- string(:printable) do1585 assert string |> String.reverse() |> String.reverse() == string1586 end1587 end15881589 property "length is preserved when reversing" do1590 check all string <- string(:alphanumeric) do1591 assert String.length(string) == String.length(String.reverse(string))1592 end1593 end1594end1595```15961597**Roc:**1598```roc1599# Roc doesn't have built-in property-based testing yet1600# Write tests for specific cases or use external tools16011602# Specific test cases1603expect1604 str = "hello"1605 str == (str |> Str.reverse |> Str.reverse)16061607expect1608 str = "Roc Lang"1609 str == (str |> Str.reverse |> Str.reverse)16101611expect1612 str = ""1613 str == (str |> Str.reverse |> Str.reverse)16141615# Length preservation1616expect1617 str = "testing"1618 Str.countUtf8Bytes(str) == Str.countUtf8Bytes(Str.reverse(str))1619```16201621**Why this translation:**1622- No built-in property-based testing library yet1623- Write representative test cases manually1624- Consider external codegen for test generation1625- Simpler but less comprehensive1626- May evolve as ecosystem matures16271628---16291630## Build System and Dependencies16311632### Mix → Roc Platform System16331634| Elixir (Mix) | Roc | Notes |1635|--------------|-----|-------|1636| `mix.exs` | `app` / `package` header | Project definition |1637| `deps` | Platform URL | Dependencies via platforms |1638| `mix deps.get` | Automatic | Platforms fetched automatically |1639| `mix compile` | `roc build` | Build command |1640| `mix test` | `roc test` | Test runner |1641| `mix format` | `roc format` | Code formatter |1642| `mix run` | `roc run` | Run application |16431644### Pattern: Project Configuration16451646**Elixir:**1647```elixir1648# mix.exs1649defmodule MyApp.MixProject do1650 use Mix.Project16511652 def project do1653 [1654 app: :my_app,1655 version: "0.1.0",1656 elixir: "~> 1.14",1657 start_permanent: Mix.env() == :prod,1658 deps: deps()1659 ]1660 end16611662 def application do1663 [1664 extra_applications: [:logger],1665 mod: {MyApp.Application, []}1666 ]1667 end16681669 defp deps do1670 [1671 {:phoenix, "~> 1.7"},1672 {:jason, "~> 1.4"},1673 {:httpoison, "~> 2.0"}1674 ]1675 end1676end1677```16781679**Roc:**1680```roc1681# MyApp.roc - Application header1682app [main] {1683 pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.10.0/vNe6s9hWzoTZtFmNkvEICPErI9ptji_ySjicO6CkucY.tar.br"1684}16851686import pf.Stdout1687import pf.Task exposing [Task]16881689main : Task {} []1690main =1691 Stdout.line!("Hello, World!")16921693# No separate config file1694# Platform URL includes all dependencies1695# Version is embedded in URL hash1696```16971698**Why this translation:**1699- No `mix.exs` equivalent - project is defined in app header1700- Dependencies come through platform (not direct package deps)1701- Version pinning via URL hash1702- Simpler dependency model but less flexible1703- Platform provides cohesive set of APIs17041705### Pattern: Custom Mix Tasks17061707**Elixir:**1708```elixir1709# lib/mix/tasks/generate_docs.ex1710defmodule Mix.Tasks.GenerateDocs do1711 use Mix.Task17121713 @shortdoc "Generate custom documentation"17141715 def run(_args) do1716 Mix.shell().info("Generating documentation...")1717 # Custom logic1718 end1719end17201721# Usage: mix generate_docs1722```17231724**Roc:**1725```roc1726# No mix task equivalent1727# Use external build scripts or just/make17281729# Justfile1730generate-docs:1731 #!/usr/bin/env bash1732 echo "Generating documentation..."1733 roc run generate_docs.roc17341735# Or shell script: scripts/generate_docs.sh1736#!/usr/bin/env bash1737roc build docs_generator.roc1738./docs_generator1739```17401741**Why this translation:**1742- No task system in Roc1743- Use external build tools (just, make, shell scripts)1744- Write Roc programs for custom tooling1745- Platform provides basic commands only1746- Simpler language, external orchestration17471748---17491750## Common Pitfalls17511752### 1. Process-Based Thinking in Pure Code17531754**Pitfall:**1755```roc1756# ❌ Trying to replicate GenServer with state1757# This doesn't work - Roc has no processes1758counter = 0 # Can't have mutable module-level state17591760increment = \{} ->1761 counter = counter + 1 # Error: counter is not mutable1762```17631764**Solution:**1765```roc1766# ✓ Use explicit state passing1767State : I6417681769increment : State -> State1770increment = \count -> count + 117711772# State is passed explicitly, not hidden in process1773# Platform provides state management if needed1774```17751776### 2. Expecting Dynamic Types17771778**Pitfall:**1779```roc1780# ❌ Trying to use heterogeneous lists1781users = [1782 { name: "Alice", age: 30 },1783 "Invalid user", # Error: different type1784 42, # Error: different type1785]1786```17871788**Solution:**1789```roc1790# ✓ Use tag unions for variants1791User : [Valid { name : Str, age : U32 }, Invalid Str, Unknown I64]17921793users : List User1794users = [1795 Valid({ name: "Alice", age: 30 }),1796 Invalid("Invalid user"),1797 Unknown(42),1798]1799```18001801### 3. Message Passing Patterns18021803**Pitfall:**1804```roc1805# ❌ Trying to use message passing1806# No send/receive in Roc1807send(pid, message) # Error: no send function1808```18091810**Solution:**1811```roc1812# ✓ Use function composition1813# Messages become function parameters1814handleMessage : Message -> State -> State1815handleMessage = \msg, state ->1816 when msg is1817 Increment -> increment(state)1818 Decrement -> decrement(state)1819 Get -> state1820```18211822### 4. Hot Code Loading Expectations18231824**Pitfall:**1825Expecting to reload modules without restart (Elixir/BEAM feature).18261827**Solution:**1828- Roc requires full program restart1829- Design for stateless or externalizable state1830- Use platform-level state persistence if needed1831- Accept different deployment model18321833### 5. Macro-Heavy Code18341835**Pitfall:**1836```elixir1837# Elixir macro-heavy DSL1838defmacro assert_valid(condition, message) do1839 quote do1840 unless unquote(condition) do1841 raise ArgumentError, unquote(message)1842 end1843 end1844end1845```18461847**Solution:**1848```roc1849# ✓ Use plain functions1850assertValid : Bool, Str -> Result {} [ValidationErr Str]1851assertValid = \condition, message ->1852 if condition then1853 Ok({})1854 else1855 Err(ValidationErr(message))1856```18571858### 6. nil vs None Confusion18591860**Pitfall:**1861```roc1862# ❌ Expecting nil to work like Elixir1863user = nil # Error: no nil value1864```18651866**Solution:**1867```roc1868# ✓ Use tag unions for optional values1869User : [Some { name : Str }, None]18701871user : User1872user = None18731874# Or simpler:1875MaybeUser : [Some { name : Str }, None]1876```18771878### 7. String vs Atom Usage18791880**Pitfall:**1881```roc1882# ❌ Using strings where tags are better1883status = "pending" # Strings don't get exhaustiveness checking1884```18851886**Solution:**1887```roc1888# ✓ Use tags for enumerations1889Status : [Pending, Approved, Rejected]18901891status : Status1892status = Pending18931894# Compiler ensures all cases handled1895when status is1896 Pending -> "waiting"1897 Approved -> "done"1898 Rejected -> "failed"1899 # Forgot a case? Compiler error!1900```19011902---19031904## Tooling19051906| Purpose | Elixir | Roc | Notes |1907|---------|--------|-----|-------|1908| Build | `mix compile` | `roc build` | Compile project |1909| Run | `mix run` | `roc run` | Execute application |1910| Test | `mix test` | `roc test` | Run tests |1911| Format | `mix format` | `roc format` | Code formatting |1912| REPL | `iex` | `roc repl` | Interactive shell |1913| Docs | `mix docs` (ExDoc) | `roc docs` | Generate documentation |1914| Dependency fetch | `mix deps.get` | Automatic | Platform URLs fetched automatically |1915| Type checking | Dialyzer | Built-in | Type checking |1916| Hot reload | `iex -S mix` | - | Not available in Roc |1917| Code analysis | Credo | - | No equivalent yet |19181919---19201921## Examples19221923### Example 1: Simple - Basic List Processing19241925**Before (Elixir):**1926```elixir1927defmodule ListUtils do1928 @doc "Sum all numbers in a list"1929 def sum(list), do: Enum.reduce(list, 0, &+/2)19301931 @doc "Double all numbers in a list"1932 def double(list), do: Enum.map(list, &(&1 * 2))19331934 @doc "Filter even numbers"1935 def evens(list), do: Enum.filter(list, &(rem(&1, 2) == 0))1936end19371938# Tests1939ExUnit.start()19401941defmodule ListUtilsTest do1942 use ExUnit.Case19431944 test "sum/1" do1945 assert ListUtils.sum([1, 2, 3, 4, 5]) == 151946 end19471948 test "double/1" do1949 assert ListUtils.double([1, 2, 3]) == [2, 4, 6]1950 end19511952 test "evens/1" do1953 assert ListUtils.evens([1, 2, 3, 4, 5]) == [2, 4]1954 end1955end1956```19571958**After (Roc):**1959```roc1960interface ListUtils1961 exposes [sum, double, evens]1962 imports []19631964## Sum all numbers in a list1965sum : List I64 -> I641966sum = \list ->1967 List.walk(list, 0, Num.add)19681969## Double all numbers in a list1970double : List I64 -> List I641971double = \list ->1972 List.map(list, \x -> x * 2)19731974## Filter even numbers1975evens : List I64 -> List I641976evens = \list ->1977 List.keepIf(list, \x -> x % 2 == 0)19781979# Tests (inline)1980expect sum([1, 2, 3, 4, 5]) == 151981expect double([1, 2, 3]) == [2, 4, 6]1982expect evens([1, 2, 3, 4, 5]) == [2, 4]1983```19841985### Example 2: Medium - Result Type and Error Handling19861987**Before (Elixir):**1988```elixir1989defmodule Calculator do1990 @doc "Safely divide two numbers"1991 def divide(a, b) when b != 0, do: {:ok, a / b}1992 def divide(_, 0), do: {:error, :division_by_zero}19931994 @doc "Chain multiple divisions"1995 def chain_divide(a, b, c) do1996 with {:ok, x} <- divide(a, b),1997 {:ok, y} <- divide(x, c) do1998 {:ok, y}1999 else2000 {:error, reason} -> {:error, reason}2001 end2002 end20032004 @doc "Safely parse and divide"2005 def parse_and_divide(a_str, b_str) do2006 with {:ok, a} <- parse_int(a_str),2007 {:ok, b} <- parse_int(b_str),2008 {:ok, result} <- divide(a, b) do2009 {:ok, result}2010 else2011 {:error, :invalid_integer} -> {:error, "Invalid number format"}2012 {:error, :division_by_zero} -> {:error, "Cannot divide by zero"}2013 end2014 end20152016 defp parse_int(str) do2017 case Integer.parse(str) do2018 {int, ""} -> {:ok, int}2019 _ -> {:error, :invalid_integer}2020 end2021 end2022end20232024# Tests2025defmodule CalculatorTest do2026 use ExUnit.Case20272028 test "divide/2 success" do2029 assert Calculator.divide(10, 2) == {:ok, 5.0}2030 end20312032 test "divide/2 by zero" do2033 assert Calculator.divide(10, 0) == {:error, :division_by_zero}2034 end20352036 test "chain_divide/3" do2037 assert Calculator.chain_divide(20, 2, 2) == {:ok, 5.0}2038 assert Calculator.chain_divide(10, 0, 2) == {:error, :division_by_zero}2039 end20402041 test "parse_and_divide/2" do2042 assert Calculator.parse_and_divide("10", "2") == {:ok, 5.0}2043 assert Calculator.parse_and_divide("abc", "2") == {:error, "Invalid number format"}2044 assert Calculator.parse_and_divide("10", "0") == {:error, "Cannot divide by zero"}2045 end2046end2047```20482049**After (Roc):**2050```roc2051interface Calculator2052 exposes [divide, chainDivide, parseAndDivide]2053 imports []20542055## Safely divide two numbers2056divide : F64, F64 -> Result F64 [DivisionByZero]2057divide = \a, b ->2058 if b == 0 then2059 Err(DivisionByZero)2060 else2061 Ok(a / b)20622063## Chain multiple divisions2064chainDivide : F64, F64, F64 -> Result F64 [DivisionByZero]2065chainDivide = \a, b, c ->2066 x = divide!(a, b) # ! propagates error2067 y = divide!(x, c)2068 Ok(y)20692070## Safely parse and divide2071parseAndDivide : Str, Str -> Result F64 [InvalidInteger, DivisionByZero]2072parseAndDivide = \aStr, bStr ->2073 a = parseFloat!(aStr) # Returns Result F64 [InvalidInteger]2074 b = parseFloat!(bStr)2075 divide!(a, b)20762077# Helper for parsing2078parseFloat : Str -> Result F64 [InvalidInteger]2079parseFloat = \str ->2080 when Str.toF64(str) is2081 Ok(num) -> Ok(num)2082 Err(_) -> Err(InvalidInteger)20832084# Convert to user-friendly messages2085parseAndDivideMsg : Str, Str -> Result F64 Str2086parseAndDivideMsg = \aStr, bStr ->2087 parseAndDivide(aStr, bStr)2088 |> Result.mapErr(\err ->2089 when err is2090 InvalidInteger -> "Invalid number format"2091 DivisionByZero -> "Cannot divide by zero"2092 )20932094# Tests2095expect divide(10, 2) == Ok(5.0)2096expect divide(10, 0) == Err(DivisionByZero)2097expect chainDivide(20, 2, 2) == Ok(5.0)2098expect chainDivide(10, 0, 2) == Err(DivisionByZero)2099expect2100 when parseAndDivideMsg("10", "2") is2101 Ok(result) -> result == 5.02102 Err(_) -> Bool.false2103expect parseAndDivideMsg("abc", "2") == Err("Invalid number format")2104expect parseAndDivideMsg("10", "0") == Err("Cannot divide by zero")2105```21062107### Example 3: Complex - GenServer to Pure State Machine with Platform Tasks21082109**Before (Elixir):**2110```elixir2111defmodule UserCache do2112 use GenServer21132114 # Client API21152116 def start_link(_opts) do2117 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)2118 end21192120 def get(user_id) do2121 GenServer.call(__MODULE__, {:get, user_id})2122 end21232124 def put(user_id, user) do2125 GenServer.cast(__MODULE__, {:put, user_id, user})2126 end21272128 def delete(user_id) do2129 GenServer.cast(__MODULE__, {:delete, user_id})2130 end21312132 def all_users do2133 GenServer.call(__MODULE__, :all_users)2134 end21352136 # Server Callbacks21372138 @impl true2139 def init(_args) do2140 {:ok, %{}}2141 end21422143 @impl true2144 def handle_call({:get, user_id}, _from, state) do2145 {:reply, Map.get(state, user_id), state}2146 end21472148 def handle_call(:all_users, _from, state) do2149 {:reply, Map.values(state), state}2150 end21512152 @impl true2153 def handle_cast({:put, user_id, user}, state) do2154 {:noreply, Map.put(state, user_id, user)}2155 end21562157 def handle_cast({:delete, user_id}, state) do2158 {:noreply, Map.delete(state, user_id)}2159 end2160end21612162# Supervision tree2163defmodule MyApp.Application do2164 use Application21652166 def start(_type, _args) do2167 children = [2168 UserCache2169 ]21702171 opts = [strategy: :one_for_one, name: MyApp.Supervisor]2172 Supervisor.start_link(children, opts)2173 end2174end21752176# Tests2177defmodule UserCacheTest do2178 use ExUnit.Case21792180 setup do2181 {:ok, _pid} = start_supervised(UserCache)2182 :ok2183 end21842185 test "get and put user" do2186 user = %{name: "Alice", email: "alice@example.com"}21872188 :ok = UserCache.put(1, user)2189 assert UserCache.get(1) == user2190 end21912192 test "get non-existent user returns nil" do2193 assert UserCache.get(999) == nil2194 end21952196 test "delete user" do2197 user = %{name: "Bob", email: "bob@example.com"}21982199 :ok = UserCache.put(2, user)2200 assert UserCache.get(2) == user22012202 :ok = UserCache.delete(2)2203 assert UserCache.get(2) == nil2204 end22052206 test "all_users returns all cached users" do2207 user1 = %{name: "Alice", email: "alice@example.com"}2208 user2 = %{name: "Bob", email: "bob@example.com"}22092210 :ok = UserCache.put(1, user1)2211 :ok = UserCache.put(2, user2)22122213 users = UserCache.all_users()2214 assert length(users) == 22215 assert user1 in users2216 assert user2 in users2217 end2218end2219```22202221**After (Roc):**2222```roc2223# Pure state machine - no GenServer2224interface UserCache2225 exposes [2226 State,2227 User,2228 init,2229 get,2230 put,2231 delete,2232 allUsers,2233 ]2234 imports []22352236User : {2237 name : Str,2238 email : Str,2239}22402241State : Dict U64 User22422243## Initialize empty cache2244init : State2245init = Dict.empty({})22462247## Get user by ID2248get : State, U64 -> [Some User, None]2249get = \state, userId ->2250 Dict.get(state, userId)2251 |> Result.map(Some)2252 |> Result.withDefault(None)22532254## Put user in cache2255put : State, U64, User -> State2256put = \state, userId, user ->2257 Dict.insert(state, userId, user)22582259## Delete user from cache2260delete : State, U64 -> State2261delete = \state, userId ->2262 Dict.remove(state, userId)22632264## Get all users2265allUsers : State -> List User2266allUsers = \state ->2267 Dict.values(state)22682269# Tests2270expect2271 state = init2272 user = { name: "Alice", email: "alice@example.com" }2273 newState = put(state, 1, user)2274 get(newState, 1) == Some(user)22752276expect2277 state = init2278 get(state, 999) == None22792280expect2281 state = init2282 user = { name: "Bob", email: "bob@example.com" }2283 stateWithUser = put(state, 2, user)2284 get(stateWithUser, 2) == Some(user)22852286 stateAfterDelete = delete(stateWithUser, 2)2287 get(stateAfterDelete, 2) == None22882289expect2290 state = init2291 user1 = { name: "Alice", email: "alice@example.com" }2292 user2 = { name: "Bob", email: "bob@example.com" }22932294 state2295 |> put(1, user1)2296 |> put(2, user2)2297 |> allUsers2298 |> List.len2299 |> \len -> len == 223002301# Hypothetical platform integration (if state management needed)2302# This would be provided by the platform, not shown here:2303#2304# import pf.Agent exposing [Agent]2305#2306# cacheAgent : Agent State2307# cacheAgent = Agent.start(init)2308#2309# getUser : U64 -> Task [Some User, None] []2310# getUser = \userId ->2311# Agent.get(cacheAgent, \state -> get(state, userId))2312#2313# putUser : U64, User -> Task {} []2314# putUser = \userId, user ->2315# Agent.update(cacheAgent, \state -> put(state, userId, user))2316#2317# deleteUser : U64 -> Task {} []2318# deleteUser = \userId ->2319# Agent.update(cacheAgent, \state -> delete(state, userId))2320#2321# getAllUsers : Task (List User) []2322# getAllUsers =2323# Agent.get(cacheAgent, allUsers)2324```23252326---23272328## See Also23292330For more examples and patterns, see:2331- `meta-convert-dev` - Foundational patterns with cross-language examples2332- `convert-erlang-roc` - Related BEAM → Roc conversion (similar paradigm shift)2333- `lang-elixir-dev` - Elixir development patterns2334- `lang-roc-dev` - Roc development patterns23352336Cross-cutting pattern skills (for areas not fully covered by lang-*-dev):2337- `patterns-concurrency-dev` - Process model vs Task model comparison2338- `patterns-serialization-dev` - JSON, validation across languages2339- `patterns-metaprogramming-dev` - Macros vs abilities comparison