Simple Algebraic Data Types
Define custom types with multiple variants (also called sum types or tagged unions):Expected Output:How it works:
pattern_matching.elr
type Shape = ...defines a new type with three variants- Each variant can carry data:
Circle Intholds a radius - Pattern matching ensures all cases are handled
- The
areafunction processes each shape differently
The Circle area uses
3 * r * r as an approximation of π since floating-point support is limited.Option Type
The Expected Output:How it works:
Option type handles values that might be absent, similar to Maybe in Haskell or Option in Rust:options.elr
Option Intrepresents a value that might not existSome valwraps a successful resultNonerepresents absence of a value (like null, but type-safe)safeDivreturnsNoneinstead of crashing on division by zero- Pattern matching forces you to handle both cases
Polymorphic Data Types
Data types can be generic over type parameters:Expected Output:How it works:
type Option a- the type parameteracan be any typeOption Int,Option String, etc. are all valid concrete typesmapworks with anyOptiontype, transforming the value inside if present- This is similar to
mapfor lists but for optional values
- Write generic code once, use it with many types
- Type safety:
maponOption Intmust returnOptionof some type - No runtime overhead: types are erased after compilation
Recursive Data Types
Data types can reference themselves, enabling powerful recursive structures:Expected Output:How it works:
Tree ais defined recursively - aNodecontains twoTree achildrenLeafis the base case with no children- Pattern matching with
_ignores the node value - Recursive function processes the tree structure
Lists in Elara are also recursive ADTs:
Pattern Matching Best Practices
Pattern matching provides exhaustive case analysis:Key Benefits:
- Exhaustiveness: The compiler ensures all cases are handled
- Safety: No runtime errors from missing cases
- Refactoring: Adding a new variant shows all code that needs updating
- Documentation: Pattern matching makes data flow explicit
Common Algebraic Data Types
Option
Represents a value that might not exist
Result
Represents success or failure with error info
List
A recursive sequence of values
Tree
Hierarchical data structure
Type Definition Syntax
TypeName: The name of your new typeparam1 param2: Optional type parameters for generic typesConstructor1,Constructor2: Variant names (must start with uppercase)Type1,Type2: The types of data each variant carries|: Separates different variants
Next Steps
- Pattern Matching - Deep dive into pattern matching syntax
- Type System - Understanding Elara’s type system
- Higher-Order Functions - Use ADTs with higher-order functions