Procedures
This topic is meant to document procedures in Pile
Overview
In the Pile programming language, a procedure is a reusable block of code designed to perform specific tasks. Unlike traditional functions in other languages, procedures in Pile:
- Do not have named arguments: Data is passed and manipulated solely via the stack.
- Do not return values: The stack holds all the intermediate and final results of the operations performed.
- Procedures are a key part of writing modular and maintainable code in Pile, allowing you to define, organize, and reuse blocks of code.
Defining a Procedure
To define a procedure in Pile, use the proc
keyword followed by the name of the procedure and the end
keyword to mark the end of the procedure.
Syntax:
proc <NAME>
<CODE>
end
Code examples
Here's an example demonstrating a simple procedure to add two numbers:
proc add_three_numbers
+ +
end
5 5 5 add_three_numbers println
# Output: 15
Here's another example showing how procedures can interact with the stack for more complex operations:
proc square
dup *
end
8 square println
# Output: 64
This procedure is meant to check if a given number is even or odd:
proc even_odd
2 swap % 0 = if
"Even" println
else
"Odd" println
end
end
4 even_odd # Output: Even
7 even_odd # Output: Odd
Notice how the parameters (values on the stack) are manipulated within the procedure and the results remain on the stack after execution.