Functions

Functions


Functions encapsulate reusable code. In Ruchy, functions are first-class values that can be passed around and returned.

Basic Function Definition

Define a function with fn:

Expected Output: Hello!

Test Coverage: ✅ tests/lang_comp/functions/definitions.rs

Try It in the Notebook

Expected Output: 8

Function with Return Value

The last expression is automatically returned:

Expected Output: 16

Explicit Return

Use return for early exit:

Expected Output: 5

Parameters

Functions can accept multiple parameters:

Expected Output: 10

Common Patterns

Pure Functions

Helper Functions

Validation Functions

Recursion

Functions can call themselves:

Expected Output: 120

Fibonacci

Expected Output: 13

Function Scope

Functions have their own scope:

Closures

Functions capture their environment:

Expected Output: 8

Higher-Order Functions

Functions that take or return functions:

Expected Output: 12

Anonymous Functions

Expected Output: 25

Arrow Functions

Shorthand syntax:

Expected Output: 7

Best Practices

✅ Small, Focused Functions

✅ Descriptive Names

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 96%

Functions are the building blocks of reusable code. Use them to organize logic, avoid repetition, and create abstractions.

Key Takeaways:

  • Last expression is returned automatically
  • Use return for early exit
  • Functions can be recursive
  • Closures capture environment
  • Keep functions small and focused

← Previous: Loop Control | Next: Parameters & Arguments →