Skip to main content

Control Flow

Mux provides familiar control flow constructs with some unique features like pattern matching with guards.

If / Else

Standard if-else branching with curly braces:

if_else.mux
Loading...

If as an Expression

In Mux, if can be used as an expression that returns a value:

if_expression.mux
Loading...

For Loops

Mux uses range-based for loops only (no C-style for (int i = 0; i < n; i++)):

for_loops.mux
Loading...

Ignoring Loop Variables

Use _ when you don't need the loop variable:

ignoring_loop_vars.mux
Loading...

Iterating Collections

iterating_collections.mux
Loading...

While Loops

Standard while loops with boolean conditions:

while_loops.mux
Loading...

Break and Continue

Control loop execution:

break_continue.mux
Loading...

Match Statements

Pattern matching with guards and destructuring:

Basic Matching

basic_matching.mux
Loading...

This is equivalent to:

if_else_equivalent.mux
Loading...

Matching optional

matching_optional.mux
Loading...

Matching result

matching_result.mux
Loading...

Pattern Matching with Guards

Guards add conditional logic to patterns:

pattern_guards.mux
Loading...

Ignoring Values in Patterns

Use _ to ignore parts of patterns you don't need:

pattern_ignore.mux
Loading...

Matching Enums

matching_enums.mux
Loading...

Wildcard Pattern

The _ pattern matches anything:

wildcard_pattern.mux
Loading...

Exhaustive Matching

Mux requires that all possible cases are handled in a match statement. If you miss a case, the compiler will give an error:

exhaustive_matching.mux
Loading...

Match as Switch Statement

Match statements can be used as switch statements for any type, not just enums:

switch_on_primitives.mux
Loading...

Variable Binding in Switch Patterns

Capture matched values in variables:

switch_variable_binding.mux
Loading...

Constants in Switch Patterns

Use constants as match patterns:

switch_constants.mux
Loading...

List Literal Matching

Match on list structure:

switch_list_matching.mux
Loading...

Switch with Guards

Add conditions to switch cases:

switch_with_guards.mux
Loading...

Return Statement

Exit a function early:

return_statement.mux
Loading...

Best Practices

  1. Use match for result and optional - More expressive than if-else chains
  2. Prefer pattern matching with guards - Cleaner than nested if statements
  3. Use _ for unused values - Makes intent explicit
  4. Early returns for error conditions - Reduces nesting
  5. Use range() for numeric loops - Idiomatic Mux
  6. Break and continue judiciously - Can make code harder to follow if overused

See Also