Overview
This example demonstrates how to implement common mathematical functions in Dryft, including factorial calculation, exponentiation, and safe division with error handling.Source Code
What This Example Demonstrates
This example showcases:- Comments: Using
#for inline comments - Iterative algorithms: Implementing mathematical operations using loops
- Return values: Functions returning computed values by leaving them on the stack
- Multiple variable bindings: Declaring multiple variables in sequence
- Arithmetic operations: Using built-in operators like
*,-, and/ - Error handling: Implementing safe operations with validation
- Function composition: Calling functions from the main action
How It Works
Factorial Function
n! iteratively:
- Initializes
resultto 1 - Loops while
nis not zero - Multiplies
resultbynand decrementsn - Returns the final result
The function leaves the result on the stack, which is how Dryft functions return values.
Exponentiation Function
y^x through repeated multiplication:
- Takes two parameters:
x(exponent) andy(base) - Initializes
totalto 1 - Multiplies
totalbyyexactlyxtimes - Returns the computed power
Safe Division Action
- If divisor is 0: prints error message
- If dividend is 0: returns 0
- If divisor is 1: returns dividend unchanged
- Otherwise: performs the division
Main Action
Demonstrates all three functions:- Calculates
10!(factorial of 10) - Calculates
3^5(3 to the power of 5) - Performs safe division:
1/6and0/4
Compiling and Running
To compile and run this example:Expected Output
3628800is 10!243is 3^56is 6/1Division by zeromessage for 4/0