For in Standard ML
Standard ML (SML) doesn’t have a built-in looping construct like for
. Instead, we typically use recursion or higher-order functions to achieve similar results. Here are some examples of how we can replicate the Go for
loop behavior in SML:
To run this program, you would typically save it in a file (e.g., loops.sml
) and then use an SML interpreter or compiler. For example, with Standard ML of New Jersey (SML/NJ):
In Standard ML, we use recursion to implement loop-like behavior. Each function calls itself with updated parameters until a base condition is met. This is the idiomatic way to express iteration in functional programming languages like SML.
The range
-like functionality is simulated by passing a counter that decrements, and the “continue” behavior is achieved by using an if-else statement to skip the print for even numbers.
Note that Standard ML doesn’t have mutable variables in the same way as imperative languages, so we pass and return updated values instead of modifying variables in place.
This example demonstrates how to translate imperative loop constructs into functional programming patterns, which is a common task when moving between these different programming paradigms.